<?php
/**
 * sort_model.php
 *
 * FILE IS OBSOLETE! This was a total nightmare.
 * Someone with no OOP and not much DB experience did his best effort but it was slow and almost unusable...
 * Took me 3 days to rewrite the new button sort sub-system and another 5 days to cleanup the old code/queries despite
 * it took like 2 months for the guy who did the old one! The new one is much easier to use, faster and actually works!
 *
 * @author $Author: dtong $
 * @version $Id: sort_model.php,v 1.56 2011/05/09 04:48:53 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/
echo 'sort_model.php is obsolete, aborted.';
exit;

class Sort_model extends CI_Model {

	function __construct() {
		parent::__construct();
		//osa_load_lang('general');
		//osa_load_lang('unit');
    }

    function get_data($unit, $type) {
    	if ( !is_numeric($unit) )
    		return FALSE;
    	if ( !is_numeric($type) )
    		return FALSE;

    	$this->db->select('d.*,r.sortkey');
    	$this->db->from('department d');
		$this->db->join('res_sort r', 'r.fk3 = d.id', 'left');
		$this->db->order_by('r.sortkey');
    	$res = $this->db->get();
    	if ( $res->num_rows <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
    }


 	function get_all($unit, $type) {
    	if ( !is_numeric($unit) )
    		return FALSE;
    	if ( !is_numeric($type) )
    		return FALSE;

    	$this->db->select('d.id, d.name, r.sortkey');
    	$this->db->from('department d');
		$this->db->join('res_sort r', 'r.fk3 = d.id', 'left');
		$this->db->order_by('r.sortkey desc');
    	$res = $this->db->get();
    	if ( $res->num_rows <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	$arrs = array();
		foreach ($rows as $row) {
			$arrs[$row->id] = $row;
		}
		//$resobj = $res->result()
    	//$rows = $res->result_array();

    	return $arrs;
    }

	 function get_sort($unit, $type, $old, $new) {
    	if ( !is_numeric($unit) )
    		return FALSE;
    	if ( !is_numeric($type) )
    		return FALSE;

    	$this->db->select('d.*,r.sortkey');
    	$this->db->from('department d');
		$this->db->join('res_sort r', 'r.fk3 = d.id', 'left');
		$this->db->where('r.sortkey', $old);
		$this->db->where('r.sortkey', $new);
		$this->db->order_by('r.sortkey');

    	$res = $this->db->get();
    	if ( $res->num_rows <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
    }
    function add_res($resid, $data) {
    	if ( !is_numeric($resid) || !$data )
    		return FALSE;
    	$maxid = $this->max_sort($data->type, $data->unitid, $data->type);

    	if ($this->check_item($data->unitid, $resid, $data->type) && $data->type >= CMS_SORT_GOAL_RESOURCE) {
    		 $row->unitid = $data->unitid;
	    	 $row->id = $resid;
	    	 $row->type = $data->type;

	    	 $this->add_sort($data->type, $row, $maxid);
	    	 return TRUE;
    	}
    	return FALSE;
    }
    function check_item($id1, $id2, $type) {
    	if ( !is_numeric($id1) || !is_numeric($id2) )
    		return FALSE;

    	$this->db->select('id');
    	$this->db->from('res_sort');
    	$this->db->where('fk1', $id1);
    	$this->db->where('fk3', $id2);
    	$this->db->where('type', $type);

    	$res = $this->db->get();
    	if ( $res->num_rows > 0 )
    		return FALSE;

    	return TRUE;
    }
    function add_sort($sort_flag, $row, $sortkey) {
     	$check = FALSE;
     	$fk1   = FALSE;
     	$fk2   = FALSE;
     	$fk3   = FALSE;
		$type  = FALSE;
		//This section tells which component and assign the DB fk field properly
		//Right now, there are 4 different components - resource, LT, Outcome&skills, goal resource
     	if ($sort_flag == CMS_SORT_LT_COURSE) {
     		$fk2  = $row->courseid;
     		$fk3  = $row->id;
     		$type = $row->type;
     	}
     	elseif ($sort_flag == CMS_SORT_LT_UNIT  || $sort_flag == CMS_SORT_IT_UNIT ||
     				$sort_flag == CMS_SORT_RESOURCE || $sort_flag == CMS_SORT_OS_UNIT ) {
     	        //$sort_flag == CMS_SORT_RESOURCE || $sort_flag == CMS_SORT_OS_UNIT || $sort_flag == CMS_SORT_PYP_KEY_CONCEPT) {
     		$fk1  = $row->unitid;
     		$fk3  = $row->id;
     		$type = $row->type;
     	}
    	elseif ($sort_flag == CMS_SORT_OS_COURSE) {
     		$fk2  = $row->courseid;
     		$fk3  = $row->id;
     		$type = $row->type;
     	}
    	elseif ($sort_flag >= CMS_SORT_GOAL_RESOURCE) {
     		$fk1  = $row->unitid;
     		$fk3  = $row->id;
     		$type = $row->type;
     	}
     	else {
 			 echo osa_ajaxmsg(lang('unit_outcomes_type_error'));
     		 exit;
     	}

		if ( !is_numeric($type) || !is_numeric($fk3) )
    		 return FALSE;

		    if ( is_numeric($fk1) &&
		    	($sort_flag == CMS_SORT_LT_UNIT  || $sort_flag == CMS_SORT_IT_UNIT ||
		    	 $sort_flag == CMS_SORT_RESOURCE || $sort_flag == CMS_SORT_OS_UNIT ) )
    	  	 return $this->db->insert('res_sort', array('fk1'=>$fk1, 'fk3'=>$fk3, 'type'=>$type, 'sortkey'=>$sortkey));
    	elseif ( is_numeric($fk2) &&
    			($sort_flag == CMS_SORT_LT_COURSE || $sort_flag == CMS_SORT_OS_COURSE) )
    	  	 return $this->db->insert('res_sort', array('fk2'=>$fk2, 'fk3'=>$fk3, 'type'=>$type, 'sortkey'=>$sortkey));
    	elseif ( is_numeric($fk1) && ($sort_flag >= CMS_SORT_GOAL_RESOURCE ) )
			 return $this->db->insert('res_sort', array('fk1'=>$fk1, 'fk3'=>$fk3, 'type'=>$type, 'sortkey'=>$sortkey));
		else
			 return FALSE;
    }

    //Function to update the DB when a sort button is pressed
    function update_sort($sort_flag, $fkey, $type, $source, $target) {
     	$check = FALSE;
     	$fk1   = FALSE;
     	$fk2   = FALSE;
     	$fk3   = FALSE;

     	if ( !is_numeric($type) )
    		 return FALSE;

    	//TODO: should not assign foreign keys like here. Have to fix it.
    	if ($sort_flag == CMS_SORT_LT_COURSE) {
     		$fk2  = $fkey;
     	}
     	elseif ($sort_flag == CMS_SORT_LT_UNIT  || $sort_flag == CMS_SORT_IT_UNIT ||
     	        $sort_flag == CMS_SORT_RESOURCE || $sort_flag == CMS_SORT_OS_UNIT) {
     		$fk1  = $fkey;
     	}
    	elseif ($sort_flag == CMS_SORT_OS_COURSE) {
     		$fk2  = $fkey;
     	}
     	elseif ($sort_flag >= CMS_SORT_GOAL_RESOURCE) {
     		$fk1  = $fkey;
     	}
     	else {
     		 echo osa_ajaxmsg(lang('unit_outcomes_type_error'));
     		 exit;
     	}

     	$fk3  =  $source->id;
     	$sortkey = $target->realsortkey;

     	if ( !is_numeric($fk3) )
    		 return FALSE;

		if ( is_numeric($fk1) &&
		    	($sort_flag == CMS_SORT_LT_UNIT  || $sort_flag == CMS_SORT_IT_UNIT ||
		    	 $sort_flag == CMS_SORT_RESOURCE || $sort_flag == CMS_SORT_OS_UNIT ) )
    	  	 $this->db->where('fk1', $fk1);
    	elseif ( is_numeric($fk2) &&($sort_flag == CMS_SORT_LT_COURSE || $sort_flag == CMS_SORT_OS_COURSE) )
    	  	 $this->db->where('fk2', $fk2);
    	elseif ( is_numeric($fk1) && ($sort_flag >= CMS_SORT_GOAL_RESOURCE ) )
    	  	 $this->db->where('fk1', $fk1);
		else
    		 return FALSE;

   		$this->db->where('type', $type);
   		$this->db->where('fk3', $fk3);

		return $this->db->update('res_sort', array('sortkey'=>$sortkey));
     }

    function max_sort($sort_flag, $fkey, $type) {
    	$table_res_sort = $this->db->dbprefix('res_sort');

    	$select = "max(sortkey)+1 sortkey";
    	$from   = $table_res_sort;

   		if ($sort_flag == CMS_SORT_LT_COURSE) {
     		$where  = "fk2=$fkey and type=$type";
     		$groupby= "group by type, fk2";
     	}
     	elseif ($sort_flag == CMS_SORT_LT_UNIT  || $sort_flag == CMS_SORT_IT_UNIT ||
     			  $sort_flag == CMS_SORT_RESOURCE || $sort_flag == CMS_SORT_OS_UNIT ||
     			  $sort_flag >= CMS_SORT_GOAL_RESOURCE) {
     		$where  = "fk1=$fkey and type=$type";
     		$groupby= "group by type, fk1";
     	}
     	else
     		 return 1;

    	$query  = "select $select from $from where $where $groupby ";

    	$res = $this->db->query( $query );

		if ( $res->num_rows() <= 0 )
    		return 1;

    	$rows = $res->result();
		if ($rows[0]->sortkey == null)
			return 1;

    	return $rows[0]->sortkey;
    }

	function xget_strand_tree_lt($deptid, $courseid, $type, $lt_only_flag=FALSE, $wherein=FALSE) {
		if ( !is_numeric($deptid) || !is_numeric($type) ) {
			return FALSE;
		}
		if ( $lt_only_flag ) {
			$join_direction = 'right';
		}
		else {
			$join_direction = 'left';
		}

		$table_benchmark   = $this->db->dbprefix('benchmark');
		$table_target_text = $this->db->dbprefix('target_text');
		$table_standard    = $this->db->dbprefix('standard');
		$table_strand      = $this->db->dbprefix('strand');
		$table_res_sort    = $this->db->dbprefix('res_sort');

		$select  = '';
		$from    = '';
		$join    = '';
		$where   = '';
		$orderby = '';

		$select .= "case when r.sortkey is null then ";
		$select .= "ifnull( (select max(sortkey)+1 from $table_res_sort where type=".CMS_SORT_LT_COURSE." and fk2=$courseid group by type, fk2 ), 0 ) ";
		$select .= "else r.sortkey end as 'sortmaxid', ";
		$select .= 'r.sortkey realsortkey, ';
		$select .= 'b.id as realbenchid, b.data as benchmark, b.mingradeid, b.maxgradeid, ';
		$select .= 'sta.data as standard, sta.id as standardid, str.id as strandid, str.data as strand, ';
		//$select .= 't.id, t.benchmarkid, t.courseid, t.select1, t.data, case when t.type ='.CMS_LEARNING_TARGETS_TYPE.' then '.CMS_SORT_LT_COURSE.' else t.type end as "type" ';
		$select .= 't.id, t.benchmarkid, t.courseid, t.select1, t.data, '.CMS_SORT_LT_COURSE.' as "type" ';
		$select .= ',str.importid as strand_importid,sta.importid as standard_importid,b.importid as benchmark_importid ';

		$from 	 = "$table_strand as str ";

      $join   .= "left join $table_standard as sta on sta.type = str.type and sta.strandid=str.id ";
	   $join   .= "left join $table_benchmark as b on b.type=str.type and b.standardid=sta.id ";
		$join   .= "$join_direction join $table_target_text as t on t.type=b.type and t.benchmarkid=b.id and t.courseid='$courseid' ";
		$join   .= "left join $table_res_sort as r on r.fk2=t.courseid and r.fk3=t.id ";

		$where  .= "str.type='".CMS_LEARNING_TARGETS_TYPE."' ";
		$where  .= "and str.departmentid='$deptid' ";
		//Check Enable
		$where  .= " and str.enabled=" .CMS_ADMIN_ENABLE;
		$where  .= " and sta.enabled=" .CMS_ADMIN_ENABLE;
		$where  .= " and b.enabled=" .CMS_ADMIN_ENABLE ." ";

	  //  $where  .= "and r.type='".CMS_SORT_LT_COURSE."' ";
		//$where  .= "and t.courseid='".$courseid."' ";

		if ($wherein != FALSE && is_array($wherein)) {
			$in = implode(',', $wherein);
			$where  .= "and t.id in ($in) ";
		}

		if ( $this->config->item('cms_lt_importid_support') ) {
			$orderby = 'str.importid_int,sta.importid_int,b.importid_int,';
		}
		$orderby .= 'str.data asc, sta.data asc, b.id asc, sortmaxid asc, r.sortkey asc ,t.data';

		$query   = "select $select from $from $join where $where order by $orderby";

		$res = $this->db->query( $query );
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
	}

	/*
	 * This is the learning targets section on the unit page.
	 * $use_strands - Will get strands, standards and benchmarks.
	 * config cms_lt_importid_support will force to use strands
	 */
	function get_targets($unitid, $type, $wherein=FALSE, $use_strands=FALSE) {
		if ( !is_numeric($unitid) || !is_numeric($type) ) {
			return FALSE;
		}
		$use_importid = FALSE;
		if ( $this->config->item('cms_lt_importid_support') ) {
			$use_importid = TRUE;
		}

		$table_unit_target = $this->db->dbprefix('unit_target');
		$table_target_text = $this->db->dbprefix('target_text');
		$table_res_sort    = $this->db->dbprefix('res_sort');
		$table_course_sis = $this->db->dbprefix('course_sis');
		$table_department = $this->db->dbprefix('department');

		$table_strand = $this->db->dbprefix('strand');
		$table_standard = $this->db->dbprefix('standard');
		$table_benchamrk = $this->db->dbprefix('benchmark');

		$select  = '';
		$from    = '';
		$join    = '';
		$where   = '';
		$orderby = '';

		$select .= "d.id departmentid,c.name coursename,case when r.sortkey is null then ";
		$select .= "ifnull( (select max(sortkey)+1 from $table_res_sort where type=".CMS_SORT_LT_UNIT." and fk1=$unitid group by fk1, type ), 0 ) ";
		$select .= "else r.sortkey end as 'sortmaxid', ";
		$select .= 'r.sortkey realsortkey, ';
		$select .= 't.id, t.benchmarkid, t.courseid, t.select1, t.data, case when t.type ='.CMS_LEARNING_TARGETS_TYPE.' then '.CMS_SORT_LT_UNIT.' else t.type end as "type", ';
		$select .= 'u.unitid ';

		$from = "$table_target_text as t";
		//Need all related strands, standards and benchmarks
		if ( $use_strands || $use_importid ) {
			$select .= ',str.id as strandid,std.id as standardid,str.data as strand,std.data as standard,bench.data as benchmark,
						   str.importid as strand_importid,std.importid as standard_importid,bench.importid as benchmark_importid ';

			$from = "$table_strand as str";
			$join = "left join $table_standard as std on str.id=std.strandid ";
			$join .= "left join $table_benchamrk as bench on std.id=bench.standardid ";
			$join .= "left join $table_target_text as t on bench.id=t.benchmarkid ";
		}

		$join .= "right join $table_unit_target as u on t.id=u.targetid ";
		$join .= "left  join $table_res_sort as r on r.fk3=t.id and r.fk1=u.unitid ";
		$join .= "left join $table_course_sis as c on c.id=t.courseid ";
		$join .= "left join $table_department as d on d.id=c.departmentid ";

		$where .= "u.unitid=$unitid ";
		$where .= 'and t.type= ' . CMS_LEARNING_TARGETS_TYPE . ' ';
	   // $where  .= "and t.type=$type ";

		if ($wherein != FALSE && is_array($wherein)) {
			$in = implode(',', $wherein);
			$where  .= "and t.id in ($in) ";
		}
		$orderby = 'sortmaxid asc, r.sortkey asc ';
		//$orderby.= 'd.name,d.id,t.data,t.id,sortmaxid, r.sortkey asc ';
		if ( $this->config->item('cms_lt_importid_support') ) {
			$orderby = "str.importid_int,std.importid_int,bench.importid_int,{$orderby} ";
		}

		$query   = "select $select from $from $join where $where order by $orderby";
		$res = $this->db->query( $query );

		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
	}
	/*
	 * Get resource records by unitid and resource type
	 * It is like getting all the Enduring understaning records etc.
	 */
	function xget_resources($unitid, $restype, $wherein=FALSE,$courseid=FALSE) {
		if ( !is_numeric($unitid) )
   			  return FALSE;

   		$select  = '';
		$from    = '';
		$join    = '';
		$where   = '';
		$orderby = '';
		$type 	 = '';

		if (is_array($restype)) {
			foreach ($restype as $item) {
				//TODO: have to take out the hardcoded type translation here.
				if ($item == CMS_ASSESSMENT_TYPE || $item == CMS_ASSESSMENT_UPLOAD_TYPE)  {
					if ($type == '' || $type == CMS_SORT_AE_UNIT)
						$type = CMS_SORT_AE_UNIT;
					else
						$type = FALSE;
		   	}
	   		else if ($item == CMS_LEARNING_TYPE || $item == CMS_LEARNING_UPLOAD_TYPE) {
					if ($type == '' || $type == CMS_SORT_LA_UNIT)
						$type = CMS_SORT_LA_UNIT;
					else
						$type = FALSE;
	   		}
	   		/*
	   		//This is for the PYP stage 2 Key Concept's 3 buttons
				else if ($item == CMS_PYP18_TYPE || $item == CMS_PYP37_TYPE || $item == CMS_PYP38_TYPE) {
					if ($type == '' || $type == CMS_SORT_PYP_KEY_CONCEPT)
						$type = CMS_SORT_PYP_KEY_CONCEPT;
					else
						$type = FALSE;
	   		} */
			}
		} else {
			$type = $restype;
			$restype = array();
			//Looks like these are special for sections with 2 resource pop-ups and we need to sort them together
			//Very bad to hard code template related data here. TODO: have to fix this later
			if ($type == CMS_SORT_AE_UNIT)  {
				$restype[] = CMS_ASSESSMENT_TYPE;
				$restype[] = CMS_ASSESSMENT_UPLOAD_TYPE;
			}
			else if ($type == CMS_SORT_LA_UNIT)  {
				$restype[] = CMS_LEARNING_TYPE;
				$restype[] = CMS_LEARNING_UPLOAD_TYPE;
			}
			else if ($type == CMS_SORT_EU_UNIT)  {
				$restype[] = CMS_ENDURING_RES_TYPE;
				//$restype[] = CMS_LEARNING_UPLOAD_TYPE;
			}
			else if ($type == CMS_ENDURING_RES_TYPE)  {
				$type = CMS_SORT_EU_UNIT;
				$restype[] = CMS_ENDURING_RES_TYPE;
			} /*
			else if ($type == CMS_SORT_PYP_KEY_CONCEPT)  {
				$restype[] = CMS_PYP18_TYPE;
				$restype[] = CMS_PYP37_TYPE;
				$restype[] = CMS_PYP38_TYPE;
			} */
			/*
			else if ($type == CMS_SORT_EQ_UNIT)  {
				$restype[] = CMS_ESSENTIAL_QUESTION_TYPE;
				$restype[] = CMS_TEACHER_EQ_TYPE;
				//$restype[] = CMS_LEARNING_UPLOAD_TYPE;
			}
			*/
		}

		$table_resource = $this->db->dbprefix('resource');
		$table_res_sort = $this->db->dbprefix('res_sort');

   	$select .= "case when r.sortkey is null then ";
		$select .= "ifnull( (select max(sortkey)+1 from $table_res_sort where type=".$type." and fk1=$unitid group by fk1, type ), 0 ) ";
		$select .= "else r.sortkey end as 'sortmaxid', ";
		$select .= 'r.sortkey realsortkey, ';
		//$select .= 'res.id,res.courseid,res.text1,res.url1,res.ispublic,res.unitid,res.type restype,res.date1,' .
		$select .= 'res.id,res.courseid,res.text1,res.ispublic,res.unitid,res.type restype,res.date1,' .
					  'res.creatorid,res.modifierid,';
		//TODO: have to take out the hardcoded types here.
		$select .= 'case when res.type ='.CMS_ASSESSMENT_TYPE.' then '.CMS_SORT_AE_UNIT.' ';
		$select .= ' 	 when res.type ='.CMS_ASSESSMENT_UPLOAD_TYPE.' then '.CMS_SORT_AE_UNIT.' ';
		$select .= ' 	 when res.type ='.CMS_LEARNING_TYPE.' then '.CMS_SORT_LA_UNIT.' ';
		$select .= ' 	 when res.type ='.CMS_LEARNING_UPLOAD_TYPE.' then '.CMS_SORT_LA_UNIT.' ';
		$select .= ' 	 when res.type ='.CMS_ENDURING_RES_TYPE.' then '.CMS_SORT_EU_UNIT.' ';
		//$select .= ' 	 when res.type ='.CMS_PYP37_TYPE.' then '.CMS_SORT_PYP_KEY_CONCEPT.' ';
		//$select .= ' 	 when res.type ='.CMS_PYP38_TYPE.' then '.CMS_SORT_PYP_KEY_CONCEPT.' ';
		//$select .= ' 	 when res.type ='.CMS_PYP18_TYPE.' then '.CMS_SORT_PYP_KEY_CONCEPT.' ';
		//$select .= ' 	 when res.type ='.CMS_ESSENTIAL_QUESTION_TYPE.' then '.CMS_SORT_EQ_UNIT.' ';
		//$select .= ' 	 when res.type ='.CMS_TEACHER_EQ_TYPE.' then '.CMS_SORT_EQ_UNIT.' ';
		$select .= ' 	 else res.type end as "type" ';

		$from   = "$table_resource as res ";

		$join   .= "left join $table_res_sort as r on r.fk3=res.id and r.fk1=res.unitid ";

		$where  .= "res.unitid=$unitid ";
		if ($courseid != FALSE)
			$where  .= " and res.courseid=$courseid ";

		/*
		if ($restype != FALSE && is_array($restype)) {
			$in = implode(',', $restype);
			$where  .= "and res.type in ($in) ";
		}
		*/

		if ( is_array($restype) && count($restype) > 0) {
			$in = implode(',', $restype);
			$where  .= "and res.type in ($in) ";
		}
		else {
			$where  .= "and res.type=$type ";
		}

		if ($wherein != FALSE && is_array($wherein) && count($wherein) > 0) {
			$in = implode(',', $wherein);
			$where  .= "and res.id in ($in) ";
		}

		$orderby.= 'sortmaxid asc, r.sortkey asc ';

		$query   = "select $select from $from $join where $where order by $orderby";

		$res = $this->db->query( $query );

		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;

   }

	/*
    * Get all the uploads for a resource type in a unit
    * Group the uploads by resourceid in a 2-d array
    */
   	function xget_uploads($unitid, $restype) {
   		echo __METHOD__ . ' FUNCTION IS OBSOLETE.';
   		exit;
		if ( !is_numeric($unitid) )
   		return FALSE;

		if (is_array($restype) ) {
			if (count($restype) == 0)
	   			return FALSE;
	   	}
	   	else {
	   		if (!is_numeric($restype) )
	   			return FALSE;
	   	}

		$type = $restype;

	   	$this->db->select('r.id as resid, r.courseid, r.unitid, r.type, u.size length, u.*');
	   	$this->db->from('resource as r');
	   	$this->db->join('upload as u', 'r.id=u.resourceid');
	   	$this->db->where('r.unitid', $unitid);

	    if ( is_array($restype) )
			$this->db->where_in('r.type', $type);
		else
			$this->db->where('r.type', $type);

	   $this->db->order_by('resid,filename', 'asc');
	   $res = $this->db->get();
	   if ( $res->num_rows() <= 0 )
	   		return FALSE;
	   $rows = $res->result();
	   $retarray = array();
	   //Build the data structure in a 2-d array
	   foreach ($rows as $row) {
		   	if (!array_key_exists($row->resid, $retarray)) {
		   		$retarray[$row->resid] = array();
		   	}
		   	$retarray[$row->resid][] = $row;
	   }
	   return $retarray;
   }

	/*
    * Get all the selections for a resource type in a unit
    * Group the selections by resourceid in a 2-d array
    */
	function get_selections_by_restype($unitid, $restype, $resid=FALSE) {
		echo __METHOD__ . ' FUNCTION IS OBSOLETE.';
		exit;
		if ( !is_numeric($unitid) )
   		return FALSE;

   	if (is_array($restype) ) {
			if (count($restype) == 0)
				return FALSE;
	   }
	   else {
	   	if (!is_numeric($restype) )
	   		return FALSE;
	   }

   	$type = $restype;

   	$this->db->select('r.id as resid, r.type as restype, r.text1, s.type, s.choice');
   	$this->db->from('resource as r');
   	$this->db->join('resource_select as s', 'r.id=s.resourceid');
   	$this->db->where('r.unitid', $unitid);

   	if ($resid !== FALSE && is_numeric($resid))
   		$this->db->where('r.id', $resid);

   	if ( is_array($restype) )
			$this->db->where_in('r.type', $type);
		else
			$this->db->where('r.type', $type);

   	$this->db->order_by('r.id,s.type', 'asc');
   	$res = $this->db->get();
   	if ( $res->num_rows() <= 0 )
			return FALSE;
   	$rows = $res->result();
   	$retarray = array();
   	//Build the data structure to be used in the dropdown function for each select in each resource
   	//The index is resource id and select type joined by '_'
   	foreach ($rows as $row) {
   		$index = $row->resid . '_' . $row->type;
   		if (!array_key_exists($index, $retarray)) {
   			$retarray[$index] = array();
   		}
   		if ($resid !== FALSE && is_numeric($resid))
   			$retarray[$index][] = $row;
   		else
   			$retarray[$index][] = $row->choice;
   	}
   	return $retarray;
	}

 	/*
	 * Gets strands, standards, benchmarks selected for a particular unit. This involves 5 tables
	 * This is the ITstd select popup
	 */
	function get_strand_tree_render($unitid, $type, $wherein=FALSE) {
		if ( !is_numeric($unitid) || !is_numeric($type) ) {
			return FALSE;
		}
		$select  = '';
		$from    = '';
		$join    = '';
		$where   = '';
		$orderby = '';

		$sorttype = $type;
		if ($type === CMS_ITSTANDARDS_TYPE || $type === CMS_SORT_IT_UNIT) {
			 $type = CMS_ITSTANDARDS_TYPE;
			 $sorttype = CMS_SORT_IT_UNIT;
		}

		$table_unit_target = $this->db->dbprefix('unit_target');
		$table_target_text = $this->db->dbprefix('target_text');
		$table_benchmark   = $this->db->dbprefix('benchmark');
		$table_standard    = $this->db->dbprefix('standard');
		$table_strand      = $this->db->dbprefix('strand');
		$table_res_sort    = $this->db->dbprefix('res_sort');
		//$table_school      = $this->db->dbprefix('school');

   	$select .= "case when r.sortkey is null then ";
		$select .= "ifnull( (select max(sortkey)+1 from $table_res_sort where type=".$sorttype." and fk1=$unitid group by fk1, type ), 0 ) ";
		$select .= "else r.sortkey end as 'sortmaxid', ";
		$select .= 'r.sortkey realsortkey, ';
		$select .= 't.id, case when t.type ='.$type.' then '.$sorttype.' else t.type end as "type", ';
		$select .= 'd.id strandid, d.data strand, d.schoolid, ';
		//$select .= 'd.id strandid, d.data strand, d.schoolid, c.name schoolname, ';
		$select .= 's.id standardid, s.data standard, ';
		$select .= 'b.id benchmarkid, b.data benchmark, ';
		$select .= 'u.targetid, u.unitid, u.select1, u.select2,';
		$select .= 'd.importid strand_importid,s.importid standard_importid,b.importid benchmark_importid ';

		$from   = "$table_unit_target as u ";

		$join   .= "left join $table_res_sort    as r on r.fk3=u.targetid and r.fk1=u.unitid ";
		$join   .= "left join $table_target_text as t on t.id=u.targetid and t.benchmarkid=u.benchmarkid and t.type=u.target_type ";
		$join   .= "left join $table_benchmark   as b on b.id=t.benchmarkid and b.type=t.type ";
		$join   .= "left join $table_standard    as s on s.id=b.standardid and s.type=b.type ";
		$join   .= "left join $table_strand      as d on d.id=s.strandid and d.type=s.type ";
		//$join   .= "left join $table_school      as c on c.id=d.schoolid ";


		$where  .= "u.unitid=$unitid ";
		$where  .= "and d.type=". $type . " ";

		if ($wherein != FALSE && is_array($wherein) && count($wherein) > 0) {
			$in = implode(',', $wherein);
			$where  .= "and t.id in ($in) ";
		}

		if ( $this->config->item('cms_lt_importid_support') ) {
			$orderby = 'd.importid_int,s.importid_int,b.importid_int,sortmaxid asc,r.sortkey asc ';
		}
		else {
			$orderby = 's.strandid, sortmaxid asc, r.sortkey asc ';
		}

		$query   = "select $select from $from $join where $where order by $orderby";

		$res = $this->db->query( $query );

		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	if ( $this->config->item('cms_lt_importid_support') ) {
    		foreach ($rows as $record) {
    			if ( !empty($record->strand_importid) ) {
					$record->strand = "$record->strand_importid $record->strand";
    			}
    			if ( !empty($record->standard_importid) ) {
					$record->standard = "$record->standard_importid $record->standard";
    			}
    			if ( !empty($record->benchmark_importid) ) {
					$record->benchmark = "$record->benchmark_importid $record->benchmark";
    			}
    		}
    	}
    	return $rows;

	}

	function sortResourceItem($unitid, $targetid, $type, $mode) {
		return $this->sortItem($unitid, $targetid, $type, $mode, CMS_SORT_RESOURCE);
    }

	function sortItem($fkey, $targetid, $type, $mode, $sort_flag=FALSE) {
		if ($sort_flag==FALSE)
			$sort_flag = $type;

		if ( !is_numeric($type) ||  !is_numeric($mode) )
    		return FALSE;

    	if ( !is_numeric($targetid) || !is_numeric($fkey) )
    		return FALSE;

    	//$all = $this->sort_model->get_array($sort_flag, $fkey, $type);
    	$all = $this->get_array($sort_flag, $fkey, $type);

    	if (is_array($all)==FALSE)
			return FALSE;

		$source  = FALSE;
		$target  = FALSE;

		$mode_plus = 0;
		if ($mode == 1) { // down +1
			$mode_plus += 1 ;
		} elseif ($mode == 0) { // up -1
			$mode_plus -= 1 ;
		}

		if (array_key_exists($targetid,  $all)) {
			$source = $all[$targetid];
			$target_sortkey = $source->realsortkey + $mode_plus;
		}

		if ($source ==FALSE)
			return FALSE;

		$before_lock     = FALSE;
		$after_unlock    = FALSE;
		$before 		 = FALSE;
		$after 		     = FALSE;

		$rowid = $this->max_sort($sort_flag, $fkey, $type);
		$last_groupid = 0;
		foreach($all as $key => $row) {
			if ($source->id  == $row->id ) {
				$before_lock = TRUE;
				$after_unlock= TRUE;
			}

			if ($row->realsortkey == null) {
				/*
				if (isset($row->strandid)) {

					if ($last_groupid != 0 && $last_groupid != $row->strandid) {
						$rowid += 10;
					}
					$last_groupid = $row->strandid;
				}
				*/
				$this->add_sort($sort_flag, $row, $rowid);
				$rowid += 1;
			}

			if ($before_lock  == FALSE)
				$before  = $row; //$row->id;
			if ($after_unlock == TRUE && $row->id != $source->id) {
				$after_unlock  = FALSE;
				$after   = $row; //$row->id;
			}

		}

		if ($mode == 1) { // down +1
			$target = $after;
		} elseif ($mode == 0) { // up -1
			$target = $before;
		}

		$sort = array();
		if ( ($source != FALSE && $target != FALSE ) && ( $source->realsortkey == FALSE || $target->realsortkey == FALSE ) ) {
				  //$sort = $this->sort_model->get_array($sort_flag, $fkey, $type, array($source->id, $target->id));
				  $sort = $this->get_array($sort_flag, $fkey, $type, array($source->id, $target->id));

			  if ($sort  != FALSE ) {
			      $source->realsortkey = $sort[$source->id]->realsortkey;
			      $target->realsortkey = $sort[$target->id]->realsortkey;
			  }
		}

		$check = $this->update_sort($sort_flag, $fkey, $type, $source, $target);
		$check = $this->update_sort($sort_flag, $fkey, $type, $target, $source);

		return FALSE;
	}

	//TODO: Types are hard coded here. Have to fix them
	//sort_flag is res_sort.type such as 501, 502...
	//fkey can be courseid, unitid etc. depends on sort_flag
	//type
	function get_array($sort_flag, $fkey, $type, $wherein=FALSE) {
		$rows = FALSE;

		if ($sort_flag == CMS_SORT_LT_COURSE) {
			//$deptid = 1;
			$this->load->model('course/course_model');
			if ( ($course = $this->course_model->get_course($fkey)) === FALSE ) {
				echo osa_ajaxmsg(lang('unit_outcomes_course_error'));
				exit;
			}
			$deptid = $course->departmentid;
		   //$rows = $this->get_strand_tree_lt($deptid, $fkey, $type, $lt_only_flag=FALSE, $wherein);
		   $rows = $this->get_strand_tree_lt($deptid, $fkey, $type, FALSE, $wherein);
		}
		elseif ($sort_flag == CMS_SORT_LT_UNIT) {
			$rows = $this->get_targets($fkey, $type, $wherein);
		}
		elseif ($sort_flag == CMS_SORT_IT_UNIT)
			$rows = $this->get_strand_tree_render($fkey, $type, $wherein);
		elseif ($sort_flag == CMS_SORT_RESOURCE) {
			$rows = $this->get_resources($fkey, $type, $wherein);
		}
		elseif ($sort_flag == CMS_SORT_OS_COURSE) {
/*
			$this->load->model('course/course_model');
			if ( ($course = $this->course_model->get_course($fkey)) === FALSE ) {
				echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
				exit;
			}
			$deptid = $course->departmentid;
			*/
		    $rows = $this->get_outcomes_skills_all($fkey, CMS_OUTCOMES_SKILLS_TYPE);
		}
		elseif ($sort_flag == CMS_SORT_OS_UNIT) {
			$rows = $this->get_outcomes_skills($fkey, CMS_OUTCOMES_SKILLS_TYPE);
		}
		elseif ($sort_flag >= CMS_SORT_GOAL_RESOURCE) {
			$rows = $this->get_linkunit_resources($fkey, $type);
		}
		else {
			echo osa_ajaxmsg(lang('unit_outcomes_type_error'));
			exit;
		}

		if ( $rows == FALSE )
    		return FALSE;

    	$arrs = array();
		foreach ($rows as $row) {
			 if ($row->id != null )
			 	 $arrs[$row->id] = $row;
		}

		return $arrs;
	}

 function xget_resourcetype($unit, $type, $old, $new) {
    	if ( !is_numeric($unit) )
    		return FALSE;
    	if ( !is_numeric($type) )
    		return FALSE;

    	$this->db->select('d.*,r.sortkey');
    	$this->db->from('department d');
		$this->db->join('res_sort r', 'r.fk3 = d.id', 'left');
		$this->db->where('r.sortkey', $old);
		$this->db->where('r.sortkey', $new);
		$this->db->order_by('r.sortkey');

    	$res = $this->db->get();
    	if ( $res->num_rows <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
    }

	//get all outcomes/skills (by department and not fix strand, standard) for render on unit page.
	function xget_outcomes_skills($unitid, $type, $strandid=1, $standardid=1) {
		$select  = '';
		$from    = '';
		$join    = '';
		$where   = '';
		$orderby = '';

		$table_unit_target = $this->db->dbprefix('unit_target');
		$table_standard    = $this->db->dbprefix('standard');
		$table_strand      = $this->db->dbprefix('strand');
		$table_benchmark   = $this->db->dbprefix('benchmark');
		$table_target_text = $this->db->dbprefix('target_text');
		$table_res_sort    = $this->db->dbprefix('res_sort');
		$table_course_sis = $this->db->dbprefix('course_sis');

		// outcomes by department
		//$select .= "c.name coursename ,case when r.sortkey is null then ";
		$select .= "case when c.name  is null then concat(s.data,' - ',d.data,'') else c.name end as coursename, ";
		$select .= "case when r.sortkey is null then ";
		$select .= "ifnull( (select max(sortkey)+1 from $table_res_sort where type=".CMS_SORT_OS_UNIT." and fk1=$unitid group by fk1, type ), 0 ) ";
		$select .= "else r.sortkey end as 'sortmaxid', ";
		$select .= 'r.sortkey realsortkey, ';
		$select .= 't.id, case when t.type ='.$type.' then '.CMS_SORT_OS_UNIT.' else t.type end as "type", ';

		//$select .= 'b.data outcomes, b.id outcomesid, b.courseid, ';
		$select .= 'b.data outcomes, b.id outcomesid, ';
		$select .= 'case when b.courseid is null then concat(s.id,d.id)  else b.courseid end as courseid, ';
		$select .= 't.data skills, t.id skillsid, t.id , u.unitid ';

		$from   = "$table_strand as s ";
	    $join   .= "left join $table_standard    as d on d.strandid=s.id     and d.type= $type ";// not fix standardid: and d.id= $standardid ";
		$join   .= "left join $table_benchmark   as b on b.standardid=d.id   and b.type= $type ";
		$join   .= "left join $table_target_text as t on t.benchmarkid=b.id  and t.type= $type ";
		$join   .= "left join $table_unit_target as u on u.targetid=t.id     and u.target_type= $type and  u.benchmarkid=t.benchmarkid and u.unitid=$unitid ";
		$join   .= "left join $table_res_sort    as r on r.fk1=u.unitid      and r.fk3 = t.id ";
		$join   .= "left join $table_course_sis as c on c.id=b.courseid  ";
		//// not fix strandid: $where  .= "s.id = $strandid ";
		$where  .= " s.type=". $type . " ";
		$where  .= "and u.unitid = $unitid ";
/*
		if ($wherein != FALSE && is_array($wherein) && count($wherein) > 0) {
			$in = implode(',', $wherein);
			$where  .= "and t.id in ($in) ";
		}
*/
		$orderby.= 'coursename,c.id,b.data, b.id, sortmaxid asc, r.sortkey asc,  t.data, t.id  ';
		$query   = "select $select from $from $join where $where order by $orderby ";

		//echo '<pre>'. print_r( $query ,true). '</pre>';

		$res = $this->db->query( $query );

		if ( $res->num_rows() <= 0 )
    		 return FALSE;

    	$rows = $res->result();

    	if ( $res->num_rows() == 1 && $rows[0]->id == null)
    	 	 return FALSE;

    	return $rows;
	}

	function xget_outcomes_skills_all($courseid, $type, $strandid=1, $standardid=1,$multicourse=FALSE) {
		$select  = '';
		$from    = '';
		$join    = '';
		$where   = '';
		$orderby = '';

		$table_standard    = $this->db->dbprefix('standard');
		$table_strand      = $this->db->dbprefix('strand');
		$table_benchmark   = $this->db->dbprefix('benchmark');
		$table_target_text = $this->db->dbprefix('target_text');
		$table_res_sort    = $this->db->dbprefix('res_sort');
		$table_course_sis  = $this->db->dbprefix('course_sis');

   	$select .= "case when c.id={$courseid} then 0 else 1 end sortcourseid,";
   	$select .= "c.name coursename ,case when r.sortkey is null then ";
		$select .= "ifnull( (select max(sortkey)+1 from $table_res_sort where type=".CMS_SORT_OS_COURSE." and fk2=$courseid group by fk1, type ), 0 ) ";
		$select .= "else r.sortkey end as 'sortmaxid', ";
		$select .= 'r.sortkey realsortkey, ';
		$select .= 't.id, case when t.type ='.CMS_OUTCOMES_SKILLS_TYPE.' then '.CMS_SORT_OS_COURSE.' else t.type end as "type", ';

		$select .= 'b.data outcomes, b.id outcomesid, b.courseid, ';
		$select .= 't.data skills, t.id skillsid, t.id ';

		$from   = "$table_strand as d ";
	    $join   .= "left join $table_standard    as s on s.strandid=d.id     and s.type= $type and s.id= $standardid ";
		$join   .= "left join $table_benchmark   as b on b.standardid=s.id   and b.type= $type and ";
		if ($multicourse!=FALSE){
			$join .= " b.courseid in ( $courseid) ";
		}
		else{
			$course_result = $this->get_course_lt_link($courseid);
	 		$sep = '';
	 		$course_select='';
			if (is_array($course_result)) {
				foreach ($course_result as $row){
					$course_select .=$sep. $row->lt_courseid ;
					$sep = ',';
				}
				$course_id = $courseid.','.$course_select;
			}
			else{
				$course_id=$courseid;
			}

			$join .= " b.courseid in ($course_id) ";
		}
		$join   .= "left join $table_course_sis as c on c.id=b.courseid  ";
		$join   .= "left join $table_target_text as t on t.benchmarkid=b.id  and t.type= $type ";
		$join   .= "left join $table_res_sort    as r on r.fk2=t.courseid    and r.fk3 = t.id ";

		$where  .= "d.id = $strandid ";
		$where  .= "and d.type=". CMS_OUTCOMES_SKILLS_TYPE . " ";
/*
		if ($wherein != FALSE && is_array($wherein) && count($wherein) > 0) {
			$in = implode(',', $wherein);
			$where  .= "and t.id in ($in) ";
		}
*/
		$orderby.= 'sortcourseid, c.name,c.id,b.data, b.id, sortmaxid asc, r.sortkey asc,  t.data, t.id  ';

		$query   = "select $select from $from $join where $where order by $orderby ";

		$res = $this->db->query( $query );

		if ( $res->num_rows() <= 0 )
    		 return FALSE;

    	$rows = $res->result();

    	if ( $res->num_rows() <= 0 && $rows[0]->id == null)
    	 	 return FALSE;
    	return $rows;


/*
		$this->db->select('b.data outcomes, t.data skills, b.id outcomesid, t.id skillsid, t.id ');
		$this->db->from('strand s');
		$this->db->join('standard d', 'd.strandid=s.id AND d.type=s.type ');
		$this->db->join('benchmark b','b.standardid=d.id AND b.type=d.type');
		$this->db->join('target_text t', 't.benchmarkid = b.id AND t.courseid = b.courseid AND b.type=t.type ', 'left');
	 	$this->db->where('s.id', $strandid );
	 	$this->db->where('d.id', $standardid);
	 	$this->db->where('b.courseid', $courseid);
		$this->db->where('b.type', $type);
		$this->db->order_by('b.data, b.id, t.datax');

		$resobj = $this->db->get();
		if ( $resobj->num_rows() <= 0 )
			return FALSE;
		$rows = $resobj->result();

		return $rows;

*/


	}
	function xget_course_lt_link($courseid) {
		$this->db->select('lt_courseid');
		$this->db->from('course_lt_link');
		if ($courseid!=FALSE)
		$this->db->where_in('courseid',$courseid);
		$resobj = $this->db->get();
	    if ( $resobj->num_rows() <= 0 )
			return FALSE;
		return  $resobj->result();
	}
	function xget_linkunit_resources($unitid, $restype) {
		if ( !is_numeric($unitid) || !is_numeric($restype) )
   			  return FALSE;

   	$select  = '';
		$from    = '';
		$join    = '';
		$where   = '';
		$orderby = '';

		$table_resource = $this->db->dbprefix('resource');
		$table_res_sort = $this->db->dbprefix('res_sort');
		$table_linkunit = $this->db->dbprefix('linkunit');

   	$select  = "case when r.sortkey is null then ";
		//$select .= "ifnull( (select max(sortkey)+1 from $table_res_sort where type=".$type." and fk1=$unitid group by fk1, type ), 0 ) ";
		$select .= "ifnull( (select max(sortkey)+1 from $table_res_sort where type={$restype} and fk1={$unitid} group by fk1, type ), 0 ) ";
		$select .= "else r.sortkey end as 'sortmaxid', ";
		$select .= 'r.sortkey realsortkey, '.$restype.' as "type", ';
		//$select .= 'res.id,res.courseid,res.text1,res.url1,res.ispublic,res.unitid,res.type restype,res.groupid,' .
		$select .= 'res.id,res.courseid,res.text1,res.ispublic,res.unitid,res.type restype,res.groupid,' .
					  'res.creatorid,res.modifierid ';
		//$from   .= "( SELECT unitid fk1, null as fk2, id fk3, type, id, courseid, text1, url1, null as groupid, ispublic, unitid, type restype " .
		$from   .= "( SELECT unitid fk1, null as fk2, id fk3, type, id, courseid, text1, null as groupid, ispublic, unitid, type restype " .
					  "  FROM " . $table_resource . " WHERE type='{$restype}' and unitid = '{$unitid}' " .
					  "  union ".
					  "  SELECT link.extid fk1,  null as fk2, link.id as fk3, link.type, ".
       			  "			link.id, u.groupid as courseid, u.title text1, ".
       			  //"			null as url1, u.groupid, ".
       			  "			u.groupid, ".
       			  "			1 as ispublic,  ".
       			  "			link.extid unitid,  ".
       			  "			link.type restype " .
       			  "  FROM " . $table_linkunit . " link " .
					  "  JOIN unit u on link.unitid = u.groupid and u.status =".CMS_UNIT_STATUS_PUBLISH .
					  "  WHERE link.type='{$restype}' and link.extid = '{$unitid}' " .

					  ") res";

		$join   .= "left join $table_res_sort as r on r.fk1=res.fk1 and r.fk3=res.fk3 ";

		$where  .= " res.type={$restype} ";
		$where  .= " and res.fk1={$unitid} ";

		$orderby.= 'sortmaxid asc, r.sortkey asc ';

		$query   = "select $select from $from $join where $where  order by $orderby";

		$res = $this->db->query( $query );

		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;

   }
	function get_coursebyunitgroup($groupids) {
		echo __METHOD__ . ' FUNTION IS OBSOLETE';
		exit;
		if ( $groupids == FALSE || !is_array($groupids) || count($groupids) == 0 )
			return FALSE;

		$this->db->select('u.groupid,u.title unittitle,u.hidden u_hidden,c.name,c.id courseid,c.hidden c_hidden');
	   $this->db->from('unit u');
	   $this->db->join('course_sis c', 'c.id=u.courseid and c.enabled = '.CMS_ADMIN_ENABLE);
	   $this->db->where_in('u.groupid',$groupids);
	   $this->db->where('u.status',CMS_UNIT_STATUS_PUBLISH);

		$res = $this->db->get();
		if ( $res->num_rows()<= 0 )
			return FALSE;
		$rows = $res->result();
		$result = FALSE;
		foreach ($rows as $row) {
			$result[$row->groupid] = $row;
		}
		return $result;
		//return $rows[0];
	}

}
?>