<?php
/**
 * unit.php - Unit controller
 *
 * @author $Author: dtong $
 * @version $Id: unit.php,v 1.141 2011/05/26 07:48:28 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/
//TODO: Can't see why we need display_list. Double check and delete it.
require_once(APPPATH . 'libraries/mapping/display_list.php');
class Unit extends CI_Controller{
	private $multi_editor_support = TRUE;
	private $edit_turn_editingon = FALSE;
	private $pdf_mode = FALSE;

	function __construct() {
		parent::__construct();
		if ( !osa_is_function_name('indexsess') ) {
			$this->access_model->checkaccess_any('unit_read');
		}
		$this->load->helper('form');
		$this->load->library('form_validation');
		osa_load_lang('unit');
		osa_load_lang('general');
		$this->load->model('unit/unit_model');
		$this->load->model('unit/course_model');
		$this->load->model('unit/lt_model');
		$this->load->model('unit/resource_model');
		$this->load->model('course/course_model');
		$this->multi_editor_support = !$this->config->item('cms_single_unit_editor');
		//For debugging purpose
		$this->output->enable_profiler($this->config->item('cms_debug_enable_profiler'));
	}

	//Read-only unit page
	function index($unitid) {
		if ( !is_numeric($unitid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		//To make sure it is ok if a user clicks on a non-current or non-edit unit
		$unit = $this->unit_model->get_current_unit($unitid);
		if ( !$unit ) {
			echo osa_ajaxmsg(lang('unit_unitnotavailable'));
			exit;
		}
		$this->_load_ro_view($unit);
	}
	//Unit_Template
	function index_template($unitid,$current_page) {
		if ( !is_numeric($unitid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		//To make sure it is ok if a user clicks on a non-current or non-edit unit
		$unit = $this->unit_model->get_current_unit($unitid);
		if ( !$unit ) {
			echo osa_ajaxmsg(lang('unit_unitnotavailable'));
			exit;
		}
		$this->_load_ro_view($unit,FALSE,FALSE,FALSE,$current_page);
	}
	//paging Popup Parent Unit (Integrated Unit,Unified Unit )
	function index_paging($unitid, $current_page=1, $divid='unitread') {
		if ( !is_numeric($unitid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		//To make sure it is ok if a user clicks on a non-current or non-edit unit
		$unit = $this->unit_model->get_current_unit($unitid);
		if ( !$unit ) {
			echo osa_ajaxmsg(lang('unit_unitnotavailable'));
			exit;
		}
		$this->_load_ro_view($unit, TRUE, TRUE, FALSE, $current_page, $divid);
	}
	//For PDF
	function indexsess($unitid, $phpsessionid) {
		global $g_pdf_mode;
		$g_pdf_mode = TRUE;
		osa_init_phpci_sessions($phpsessionid);
		$this->access_model->checkaccess_any('unit_read');
		$this->pdf_mode = TRUE;
		$this->index($unitid);
	}
	//Tha Read-only for Unit_Calendar
	function read_unit_calendar($unitid ,$current_page=1, $divid='unitread') {
		if ( !is_numeric($unitid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		$unit = $this->unit_model->get_current_unit($unitid);
		if ( !$unit ) {
			echo osa_ajaxmsg(lang('unit_unitnotavailable'));
			exit;
		}
	    $this->_load_ro_view($unit,TRUE,TRUE,TRUE,$current_page, $divid);
	}
	//Function window pop up readonly unit page.
	function read($unitid) {
		if ( !is_numeric($unitid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		$unit = $this->unit_model->get_current_unit($unitid);
		if ( !$unit ) {
			echo osa_ajaxmsg(lang('unit_unitnotavailable'));
			exit;
		}
		//Tells a template has paging.
		if ( $this->get_paging($unit->template) === TRUE )
			$this->index_paging($unitid);
		else
			$this->_load_ro_view($unit,TRUE,TRUE);
	}

	/*
	 * For course teachers to view the editing units
	 */
	function editview($unitid) {
		if ( !is_numeric($unitid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		$unit = $this->unit_model->get_edit_unit($unitid);
		$user = $this->login_model->getLogin();
		if ( !$this->course_model->isMyCourse($user->id, $unit->courseid))
			$unit = FALSE;
		if ( !$unit ) {
			echo osa_ajaxmsg(lang('unit_unitnotavailable'));
			exit;
		}
		$this->_load_ro_view($unit);
	}

	//Page to add a unit
	function add($courseid,$unit_template=FALSE) {
		if ( !is_numeric($courseid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		$this->unit_model->checkEditAccess($courseid);

      	$data = $this->store_post($courseid, $_POST,$unit_template);

      	if (!$data) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		//var_dump($_POST);

		$this->load->view( 'unit/unit_add_view',$data);
	}

	/*
	 * This handles the cancel button in the unit title and desc. section
	 * Refreshes with the readonly version if there is one else refresh with the editing version
	 */
	function canceledit($unitid) {
		if ( !is_numeric($unitid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		//To make sure it is ok if a user clicks on a non-current or non-edit unit
		$unit = $this->unit_model->get_current_unit($unitid);
		if ( !$unit ) {
			$this->edit($unitid);
			return;
		}
		$this->_load_ro_view($unit);
	}

	//This is used from the read-only page - click on the 'Turn editing on' button
	function editp($unitid) {
		$this->edit_turn_editingon = TRUE;
		return $this->edit($unitid);
	}

	//Unit edit page
	function edit($unitid, $current_page=FALSE) {
		$unit = $this->unit_model->check_unit_editaccess($unitid);
		//Make sure this is a editing unit
		if ( $unit->status != $this->unit_model->STATUS_EDIT ) {
			$unit = $this->unit_model->get_edit_unit($unitid);
			if ( !$unit  ) {
				echo osa_ajaxmsg(lang('unit_unitnotavailable'));
				exit;
			}
			//Reassign unit id to the current unit id which will get reassinged to the editing id
			$unitid = $unit->id;
		}

		//Check to see already an editing unit or not
		if ( $unit->status == $this->unit_model->STATUS_EDIT ) {
			//Found an editing unit
			$unitid = $unit->id;
		}
		elseif (!is_null($unit->editunitid)) {
			//Input was a published unit with an editing unit
			$unitid = $unit->editunitid;
		}
		else {
			//Create a new editing unit
			$user = $this->login_model->getLogin();
			$unitid = $this->unit_model->copy_editunit($unitid, $user);
			if ( $this->multi_editor_support ) {
				$this->unit_model->lock_unit($unitid);
			}
			//$unit and $unitid are different now
			//This should never happen for int. and uni. units else
			//the int. and uni. code below will fail becuase it uses $unit in the if()
		}

		if ( !$unitid ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}

		$data = new stdClass;
		//This will add properties to the existing $data object
		//$unitid here can be id or object
		$data = $this->_get_viewdata($unitid, FALSE, $data);
		//Make sure we have the actual editing unit
		$unit = $data->unit;
		if ( $this->multi_editor_support ) {
			//$data is object so pass by reference
			if ( $this->_multi_editor_handle($unit, $data) == FALSE )
				return;
		}

		//By now, we are sure we have a valid editing unit in $unit
		//Update the edit_accessdate to current date time.
		if ( $this->unit_model->update_edit_accessdate($data->unit) ) {
			//$unit variable still has old datetime so update it in memory so multi_editor_support time limit works properly.
			//The actual DB value can be a second older which is OK here.
			$data->unit->edit_accessdate = osa_dbdate();
		}

		//$this->_checkEditAccess($data->unit->courseid);
		$this->load->library('unit/Unitmain',
			array('action'=>CMS_ACTION_EDIT,'unitid'=>$unitid, 'courseid'=>$unit->courseid,'unittype'=>$data->unit->type,
				  'parentid'=>$data->unit->parentid, 'unit_template'=>$unit->template, 'current_page'=>$current_page));

		$TYPE_INT_PARENT = $this->unit_model->TYPE_INT_PARENT;
		$TYPE_UNI_PARENT = $this->unit_model->TYPE_UNI_PARENT;
		$TYPE_INT        = $this->unit_model->TYPE_INT;
		$TYPE_UNI        = $this->unit_model->TYPE_UNI;

		$publish_id = FALSE;
		$publish_id = $unitid;

		if  ( isset($unit->type) && ( $unit->type==$TYPE_INT_PARENT || $unit->type==$TYPE_UNI_PARENT ) ) {
			$publish = FALSE;
			$publish = $this->unit_model->get_publish_units_bygroup($unit);

			if (!$publish)
				$publish_id = $unitid;	// nothing for else
			else
				$publish_id = $publish->id;
		}

		$data->publish_id = $publish_id;

		$data->master_courseid = $unit->courseid;
		$data->child_courseids = $this->unit_model->get_childs_dynamic($publish_id);
		$data->current_page = $current_page;
		$data->unit_template = $unit->template;
		//Tells a template has paging.
		if ( $this->get_paging($unit->template) === TRUE )
			$data->unitpage = $this->unitmain->render_page($unitid,$current_page);
		if ($unit->type==$TYPE_INT_PARENT)
			$data->unitbody = $this->unitmain->render();
		else
			$data->unitbody = $this->unitmain->render($data->meta_flag);

		//Set up the parent unit info for child unified and integrated units
		$data->valid_parent_unit = FALSE;
		if ( $unit->type==$TYPE_INT || $unit->type==$TYPE_UNI ) {
			$parentinfo = $this->unit_model->get_parentinfo($unit);
			//var_dump($parentinfo);
			if ( $parentinfo !== FALSE ) {
				$data->parentinfo = $parentinfo;
				if ( $this->unit_model->get_current_unit($parentinfo->id) ) {
					//Only make the parent link active if parent unit is valid
					$data->valid_parent_unit = TRUE;
				}
			}
		}
		//hidden unit_button_show_hide
		//$data->hidden = lang('unit_button_show');
		$data->hidden = lang('unit_label_show');
		if ($data->unit->hidden == CMS_HIDDEN_YES){
			//$data->hidden = lang('unit_button_hide');
			$data->hidden = lang('unit_label_hide');
		}

		$data->disable_compare_button = TRUE;
		if (isset($data->unit) && $data->unit !== FALSE && isset($data->unit->currentunitid) &&
		    $data->unit->currentunitid != null  && $data->unit->currentunitid != '' )
			 $data->disable_compare_button = FALSE;
		/*
		//Check button popup (ict,gc,tail).
		$data->use_button_ict = FALSE;
	 	if ( $this->config->item('cms_use_it_standard') && $this->access_model->is_ict_editor(CMS_ICT_USER_TYPE) )
	 		$data->use_button_ict = TRUE;
	 	$data->use_button_gc = FALSE;
	 	if ( $this->config->item('cms_use_gc') && $this->access_model->is_ict_editor(CMS_GC_USER_TYPE) )
	 		$data->use_button_gc = TRUE;
	 	$data->use_button_tail = FALSE;
	 	if ( $this->config->item('cms_use_tail') && $this->access_model->is_ict_editor(CMS_TAIL_USER_TYPE) )
	 		$data->use_button_tail = TRUE;
		*/
		//Every time edit page is access the editaccess date is logged
		//Access from admin for a locked unit is not logged
		$teacher_course = $this->teacher_course($unit->courseid,$unit->template);
		$data->tearchers = lang('unit_teacher_empty');
		$data->grade_level = lang('unit_grade_level_empty');
		$data->template = $unit->template;
		if (isset($teacher_course['tearchers']) && $teacher_course['tearchers'] != FALSE)
			$data->tearchers = $teacher_course['tearchers'];
		if (isset($teacher_course['grade_level']) && $teacher_course['grade_level'] != FALSE)
			$data->grade_level = $teacher_course['grade_level'];

		if ( $this->config->item('cms_pdf_private_resource_select') ) {
			$data->show_pdf_private_resource_select = TRUE;
			$user = & osa_login_object();
			if ( $user->hide_unit_private_resource ) {
				$data->checked_privateres = '';
			}
			else {
				$data->checked_privateres = 'checked="checked"';
			}
		}

		$this->load->view( 'unit/unit_edit_view', $data);
	}

	function stage($stagenum, $action, $unitid) {
		//Read-only user would never run this controller so check for editor access
		//$unit = $this->unit_model->check_unit_editaccess($unitid);
		$unit = $this->unit_model->get_unit($unitid);
		if ( !$unit || (!osa_is_mycourse($unit->courseid) && !$this->unit_model->check_unit_editaccess($unitid)) ) {
			echo osa_ajaxmsg(lang('gen_no_permission_ajaxmsg'));
			exit;
		}
		$this->load->library('unit/Unitmain',
			array('action'=>$action, 'unitid'=>$unitid, 'courseid'=>$unit->courseid,'unit_template'=>$unit->template));

		$meta_flag = $this->_get_unittype_meta($unit->type);

		$data['html'] =  $this->unitmain->render_stage($stagenum, $meta_flag);
		$this->load->view('template/dataonly_view', $data);
		if ( $this->multi_editor_support && $action == CMS_ACTION_EDIT ) {
			//Update access time everytime we refresh a stage for edit action
			//This function only updates if the assigned editor is the current user
			$this->unit_model->update_edit_accessdate($unit);
		}
	}

	//Add a unit
	//edit for integrated & unified
	function addunit($unit_template=FALSE) {

		//$this->access_model->checkaccess_any('unit_write');
		$this->form_validation->set_message('required', lang('unit_requiredfileds'));
		$this->form_validation->set_rules('title', lang('unit_title'),'trim|required');
		$this->form_validation->set_rules('description', lang('unit_description'),'trim|required');
      	$this->form_validation->set_rules('startdate', lang('unit_startdate') ,'trim|required|callback__checkdate');
		$this->form_validation->set_rules('enddate', lang('unit_enddate'),'trim|required|callback__checkdate');
		$this->form_validation->set_rules('courseid', 'CourseID','trim');
		$this->form_validation->set_rules('unittype', 'unittype','trim');
		//select units when integrated & unitfied type
		$this->form_validation->set_rules('courseids', 'courseids','trim');
		$this->form_validation->set_rules('coursenames', 'coursenames','trim');
		if ( ! $this->form_validation->run() ) {
	      	//Caused the client print an error window with the validation errors.
	    	echo osa_ajaxmsg(lang('unit_pleasecorrecterror') . validation_errors());
	      	exit;
	    }

	    $courseid = trim(set_value('courseid'));
	    if ( !is_numeric($courseid) || $courseid == '') {
			echo osa_ajaxmsg(lang('unit_internalservererror'));
	      	exit;
	    }

	    $unittype = set_value('unittype');

	    $this->unit_model->checkEditAccess($courseid);
	    $dbdate = osa_dbdate();
	    $user = $this->login_model->getLogin();
	    $this->date_validation(set_value('startdate'),set_value('enddate'));
		$data = array (
			'courseid' => $courseid,
			'creatorid' => $user->id,
			'lasteditorid' => $user->id,
			'title' => set_value('title'),
			'description' => set_value('description'),
			'startdate' => set_value('startdate'),
			'enddate' => set_value('enddate'),
			'createdate' => $dbdate,
			'modifydate' => $dbdate,
			'editdate' => $dbdate,
			'status' => $this->unit_model->STATUS_EDIT,
			'type' => $unittype,	// for meta unit , integrated unit and unified unit
			//'type' => $this->unit_model->TYPE_NORMAL, 	old code
			'template' => $unit_template,
		);

		if ( $unittype==$this->unit_model->TYPE_INT_PARENT || $unittype==$this->unit_model->TYPE_UNI_PARENT ) {
			$courseids = trim(set_value('courseids'));
			$coursenames = trim(set_value('coursenames'));

			$unitid = $this->unit_model->add_master_child($data, $courseids , $coursenames) ;
			if ( !$unitid ) {
				echo osa_ajaxmsg(lang('unit_failedtoaddunit'));
		      	exit;
			}

			//$unitid = osa_db_lastinsertid($this->db);
			//$this->_load_ro_view($unitid);
			$this->edit($unitid);
		} else {
			if ( !$this->unit_model->add($data) ) {
				echo osa_ajaxmsg(lang('unit_failedtoaddunit'));
		      	exit;
			}

			$unitid = osa_db_lastinsertid($this->db);
			//$this->_load_ro_view($unitid);
			$this->edit($unitid);
		}

	}

	//Update a unit
	function update() {
		//$this->access_model->checkaccess_any('unit_write');
		$this->form_validation->set_message('required', lang('unit_requiredfileds'));
      $this->form_validation->set_rules('title', lang('unit_title'),'trim|required');
      $this->form_validation->set_rules('description', lang('unit_description'),'trim|required');
      $this->form_validation->set_rules('startdate', lang('unit_startdate') ,'trim|required|callback__checkdate');
      $this->form_validation->set_rules('enddate', lang('unit_enddate'),'trim|required|callback__checkdate');
      //$this->form_validation->set_rules('courseid', 'CourseID','trim');
      $this->form_validation->set_rules('unitid', 'UnitID','trim');
      if ( ! $this->form_validation->run() ) {
      	//Caused the client print an error window with the validation errors.
      	echo osa_ajaxmsg(lang('unit_pleasecorrecterror') . validation_errors());
      	exit;
      }

      $unitid = set_value('unitid');
      if ( !is_numeric($unitid) || $unitid == '') {
			echo osa_ajaxmsg(lang('unit_internalservererror'));
      	exit;
      }
      $viewdata = $this->_get_viewdata($unitid);
      $unit = $viewdata->unit;
      $this->unit_model->checkEditAccess($unit->courseid);
      $dbdate = osa_dbdate();
      $user = $this->login_model->getLogin();
      $this->date_validation(set_value('startdate'),set_value('enddate'));
		$data = array (
			'lasteditorid' => $user->id,
			'title' => set_value('title'),
			'description' => set_value('description'),
			'startdate' => set_value('startdate'),
			'enddate' => set_value('enddate'),
			'modifydate' => $dbdate,
		);
		$update_unitid = $unit->id;
		if ( $unit->status != CMS_UNIT_STATUS_EDIT ) {
			//If the submitted unit id is not an editing unit then find the related editing unit id. (issue: 194)
			if ( !osa_is_int_one($unit->editunitid) ) {
				//If we can not get the editing unit id then print error and exit
				echo osa_ajaxmsg(lang('gen_internalservererror'));
				exit;
			}
			$update_unitid = $unit->editunitid;
		}
		if ( !$this->unit_model->update($data, $update_unitid) ) {
			echo osa_ajaxmsg(lang('unit_failedtoaddunit'));
      	exit;
		}
		if ( !property_exists($this, 'cms_cache')) {
			$this->load->library('cms/cms_cache');
		}
		//Need to reset the db cache else the ro view will use the data before the update.
		$this->cms_cache->db_reset();
		$this->_load_ro_view($update_unitid);
	}

	//Undo/cancel an add/edit page
	function undo($unitid) {
		$unit = $this->unit_model->check_unit_editaccess($unitid);
		if ( $unit->status != $this->unit_model->STATUS_EDIT ) {
			echo osa_ajaxmsg(lang('unit_internalservererror'));
      	exit;
		}
		$cur_unitid = $unit->currentunitid;
		if ( !$this->unit_model->del_unit($unit) ) {
			echo osa_ajaxmsg(lang('unit_internalservererror'));
      	exit;
		}
		if ( !is_null($cur_unitid) ) {
			$this->_load_ro_view($cur_unitid);
			return;
		}
		echo '<center><div style="margin-top:100px;font-weight:bold;font-size:20px;color:red">' . lang('unit_editunitdeleted') . '</div></center>';
	}

	//Confirm/publich an unit
	function confirm($unitid) {
		$unit = $this->unit_model->check_unit_editaccess($unitid);
		if ( $unit->status != $this->unit_model->STATUS_EDIT ) {
			echo osa_ajaxmsg(lang('unit_internalservererror'));
      	exit;
		}
		//$cur_unitid = $unit->currentunitid;
		if ( !$this->unit_model->confirm_unit($unit) ) {
			echo osa_ajaxmsg(lang('unit_internalservererror'));
      	exit;
		}
		$this->_load_ro_view($unitid);
		//We know we just published a unit so run the unit cache update
		$this->load->library('cms/memory_table/unit_cache_table');
		$this->unit_cache_table->update();
	}

	//Remove a unit
	function remove($unitid) {
		$unit = $this->unit_model->check_unit_editaccess($unitid);
		if ( !$this->unit_model->remove_unit($unit) ) {
			echo osa_ajaxmsg(lang('unit_internalservererror'));
      	exit;
		}
		echo '<center><div style="margin-top:100px;font-weight:bold;font-size:20px;color:red">' .
				lang('unit_completeunitdeleted') . '</div></center>';
		//We just removed a published unit so update the unit memory table
		if ( $unit->status == CMS_UNIT_STATUS_PUBLISH ) {
			$this->load->library('cms/memory_table/unit_cache_table');
			$this->unit_cache_table->update();
		}
	}

	/*
	 * $unitid can be an object
	 */
	private function _load_ro_view($unitid, $skipedit_buttons=FALSE, $show_closebutton=FALSE,$unit_calendar=FALSE,$current_page=FALSE,$divid=FALSE) {
		$data = $this->_get_viewdata($unitid);
		if (is_object($unitid))
			$unitid = $unitid->id;

		$data->iseditor = $this->unit_model->iseditor($data->unit->courseid);
		if ( !$this->pdf_mode ) {
			$data->skipedit_buttons = $skipedit_buttons;
			$data->show_closebutton = $show_closebutton;
		}
		else {
			$data->show_closebutton = FALSE;
		}

		$this->load->library('cms/cms_template/cms_template');

		//$data->skipeditbutton = FALSE;
		$courseid = $data->unit->courseid;
		$unittype = $data->unit->type;
		$parentid = $data->unit->parentid;
		$statusid = $data->unit->status;
		//unit_template
		$template = $data->unit->template;
		$display_unittype = FALSE;

		$data->hide_visible_button_css='display:none;';
		if ( $data->iseditor && !$this->pdf_mode ){
			//$data->hide_visible_button_css='display:block;';
			$data->hide_visible_button_css='';
			$data->editmodebutton = lang('unit_turnediton');
			$data->show_hidebutton = TRUE;
		}

		//TODO: Should make isedtor and is_mycourse into one single query
		if ( !$this->pdf_mode && ($data->iseditor || osa_is_mycourse($courseid)) ) {
			if ( $this->config->item('cms_pdf_private_resource_select') ) {
				$data->show_pdf_private_resource_select = TRUE;
				$user = & osa_login_object();
				if ( $user->hide_unit_private_resource ) {
					$data->checked_privateres = '';
				}
				else {
					$data->checked_privateres = 'checked="checked"';
				}
			}
		}

		if ($show_closebutton && !$this->pdf_mode )
			$data->readmodebutton = lang('unit_closebutton');

		//if ( ($unittype == $this->unit_model->TYPE_INT_PARENT ) || ($unittype == $this->unit_model->TYPE_UNI_PARENT) ) {
		if ( $unittype != $this->unit_model->TYPE_NORMAL ) {
			$display_unittype = TRUE;
		}
		/* else {
				$unitid = $parentid;
		}*/

		$data->url = base_url()."unit/unit/showhide/".$data->unit->groupid.'/';
		if (isset($data->unit->hidden) && $data->unit->hidden==CMS_HIDDEN_YES) {
			$data->hidevisible_label  = lang('unit_label_hide');
			$data->hidebutton_text = lang('unit_button_show');
			$data->url   .= CMS_HIDDEN_NO;
		} else {
			$data->hidevisible_label  = lang('unit_label_show');
			$data->hidebutton_text = lang('unit_button_hide');
			$data->url   .= CMS_HIDDEN_YES;
		}
		$data->display_unittype = $display_unittype;

		$this->load->library('unit/Unitmain',
			array('action'=>CMS_ACTION_READ,'unitid'=>$unitid, 'courseid'=>$courseid,'unittype'=>$unittype,'parentid'=>$parentid,
				'unit_template'=>$template, 'current_page'=>$current_page, 'divid'=>$divid));
			$data->current_page = $current_page;
		if ($this->pdf_mode	==FALSE){
			//Tells a template has paging
			if ( $this->get_paging($template) === TRUE )
				$data->unitpage = $this->unitmain->render_page($unitid,$current_page);
		}

		$data->unitbody = $this->unitmain->render($data->meta_flag);

		//Special handling for multi editor support
		if ( $this->multi_editor_support && !$this->pdf_mode) {
			$this->_multi_editor_handle($data->unit, $data, TRUE);
		}
		//The following was added because editing units can be in read-only page
		$data->removebutton_text = lang('unit_removeunit');
		$data->unitremove_function = 'remove'; //For published unit
		$data->unitremove_jscript_msg = lang('unit_removemsg');
		if ( $data->unit->status == $this->unit_model->STATUS_EDIT ) {
			$data->removebutton_text = lang('unit_undoeditingunit');
			$data->unitremove_function = 'undo'; //For published unit
			$data->unitremove_jscript_msg = lang('unit_undoconfirmmsg');
		}
		//Check button popup (ict,gc,tail).
		$data->use_button_ict = FALSE;
		$data->use_button_gc = FALSE;
		$data->use_button_tail = FALSE;
		//Let's see do we need these buttons. Check for config, permission and valid type according to template id/filename
	 	if ( $this->config->item('cms_use_it_standard') && $this->access_model->is_ict_editor(CMS_ICT_USER_TYPE) &&
	 		  $this->cms_template->valid_type($data->unit->template, CMS_ICT_USER_TYPE) &&
	 		  $this->config->item('cms_hide_unit_page_ict_button') !== TRUE ) {
	 		$data->use_button_ict = TRUE;
	 	}
	 	if ( $this->config->item('cms_use_gc') && $this->access_model->is_ict_editor(CMS_GC_USER_TYPE) &&
	 			$this->cms_template->valid_type($data->unit->template, CMS_GC_USER_TYPE) ) {
	 		$data->use_button_gc = TRUE;
	 	}
	 	if ( $this->config->item('cms_use_tail') && $this->access_model->is_ict_editor(CMS_TAIL_USER_TYPE) &&
	 			$this->cms_template->valid_type($data->unit->template, CMS_TAIL_USER_TYPE) ) {
	 		$data->use_button_tail = TRUE;
	 	}

		$data->add_js = '';
		if ($unit_calendar!=FALSE)
			$data->add_js = "showDhtmlWindow('unit_calendar');";

		$teacher_course = $this->teacher_course($courseid,$template);
		$data->tearchers = lang('unit_teacher_empty');
		$data->grade_level = lang('unit_grade_level_empty');
		$data->template = $template;
		if (isset($teacher_course['tearchers']) && $teacher_course['tearchers'] != FALSE)
			$data->tearchers = $teacher_course['tearchers'];
		if (isset($teacher_course['grade_level']) && $teacher_course['grade_level'] != FALSE)
			$data->grade_level = $teacher_course['grade_level'];

		//Make sure parent unit is not deleted and then we show the parent history button
		$data->show_parent_hist_button = FALSE;
		if ( $data->unit->type == CMS_UNIT_TYPE_UNIFIED_CHILD || $data->unit->type == CMS_UNIT_TYPE_INTEGRATED_CHILD ) {
			if ( $this->unit_model->get_current_unit($data->unit->parentid) )
				$data->show_parent_hist_button = TRUE;
		}

		$this->load->view('unit/unit_ro_view', $data);
	}

	/*
	 * $unitid can be an object
	 */
	private function _get_viewdata($unitid,$all_flag=FALSE,$data=FALSE) {
		if (is_object($unitid)) {
			$unit = $unitid;
			$unitid = $unit->id;
		}
		else {
			if ($all_flag==FALSE)
				$unit = $this->unit_model->get_unit($unitid);
			else
				$unit = $this->unit_model->get_unit_any($unitid);
		}
		if ( !$unit ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		$course = $this->unit_model->get_course($unitid);
      	if ( !$course ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}

		if ( $data == FALSE )
			$data = new stdClass;
      $data->coursename = $course->name;
      $data->unit = $unit;
   	$this->_get_unittype_lang($unit, $data, $course);
   	return $data;
	}


	//Callback has to be public
	public function _checkdate($str) {
		if ( strlen($str) != 10 ) {
			$this->form_validation->set_message('_checkdate', lang('unit_invaliddate'));
		   return FALSE;
		}
		$pattern = '/[1-9][0-9][0-9][0-9]\-[0-1][0-9]\-[0-3][0-9]/';
		if ( preg_match($pattern, $str) ) {
		   return TRUE;
		}
		else {
			$this->form_validation->set_message('_checkdate', lang('unit_invaliddate'));
         return FALSE;
		}
	}

	/*
	 * Get Unit Type
	 */
	private function _get_unittype_meta($type) {
      	$result = FALSE;

		if  ($type == $this->unit_model->TYPE_META)
			$result = TRUE;

		return $result;
	}

	/*
	 * Case Unit Type to Unit Language
	 */
	private function _get_unittype_lang($unit, $data, $course, $courseid=FALSE) {
		$type   = $unit->type;
		$status = $unit->status;
		$data->displaytype = TRUE;	// normal:not display , another type: display
		$data->iscreator   = FALSE;
		$data->integrated_flag = FALSE;
		$data->unified_flag    = FALSE;
		$unit_lang ='';

		$data->change_flag = TRUE;
		$data->distribute  = FALSE;
		switch ($type) {
			case $this->unit_model->TYPE_NORMAL:
				$unit_lang = lang('unit_normal');
				break;
			case $this->unit_model->TYPE_META:
				//meta unit don't change unit type
				$data->change_flag = FALSE;
				$unit_lang = lang('unit_metaunit');
				break;
			case $this->unit_model->TYPE_INT_PARENT:
				$data->integrated_flag = TRUE;
				$unit_lang = lang('unit_integratedunit');
				$data->distribute = $this->unit_model->status_distribute($unit);
				break;
			case $this->unit_model->TYPE_INT:
				$data->integrated_flag = TRUE;
				$unit_lang = lang('unit_integratedunit');
				break;
			case $this->unit_model->TYPE_UNI_PARENT:
				$data->unified_flag = TRUE;
				$unit_lang = lang('unit_unifiedunit');
				$data->distribute = $this->unit_model->status_distribute($unit);
				break;
			case $this->unit_model->TYPE_UNI:
				$data->unified_flag = TRUE;
				$unit_lang = lang('unit_unifiedunit');
				break;
      	}



      	$data->unittypename= $unit_lang;
      	$data->meta_flag   = $this->_get_unittype_meta($type);

		//if ( ($type == $this->unit_model->TYPE_INT_PARENT ) || ($type == $this->unit_model->TYPE_UNI_PARENT) ) {
		if ( $type != $this->unit_model->TYPE_NORMAL ) {
		      $data->displaytype = TRUE;
		}

      	if ($courseid != FALSE) {
			$action = CMS_ACTION_EDIT;
		    if ($courseid != $course->id ) {
		        if ($data->unified_flag==TRUE) {
		            $action = CMS_ACTION_READ;
		        } else {
		        	$action = CMS_ACTION_EDIT;
		        }
		    } else {
		        	$data->iscreator = TRUE;
		    }

	        $this->load->library('unit/Unitmain',
			array('action'=>$action, 'unitid'=>$unit->id, 'courseid'=>$unit->courseid));
			$data->unitbody = $this->unitmain->render($data->meta_flag);
      	}
	}

	function selcourse_add($selcourseids=FALSE,$unit_template=FALSE) {
		$keys = array_keys($_POST);
	    foreach($keys as $key) {
	    	 if ($key == 'courseid') {
	    	 	 $courseid = $_POST[$key];
	    	 }
	    	 if ($key == 'courseids')
				 $selcourseids = $_POST[$key];
	    }
		$this->selcourse($courseid, $selcourseids, FALSE, TRUE,$unit_template);
	}

	function selcourse_edit($unitid, $courseid,$unit_template=FALSE) {
		/*
	    $keys = array_keys($_POST);
	    foreach($keys as $key) {
	    	 if ($key == 'unitid')
	    	 	 $unitid = $_POST[$key];
	    	 if ($key == 'courseid')
	    	 	 $courseid = $_POST[$key];
	    }*/
	    $child_courseids = $this->unit_model->get_childs_dynamic($unitid);
		$this->selcourse($courseid, $child_courseids, $unitid, FALSE,$unit_template);
	}

	/* for select the type of unit [normal,meta,integrated,unified] */
	function selcourse($courseid, $selcourseids, $unitid, $addmode,$unit_template=FALSE) {
		if ( !is_numeric($courseid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}

		$all_courses = $this->unit_model->get_enable_courses($courseid);
		if (!$all_courses) {
			echo osa_ajaxmsg(lang('gen_internalservererror')); // no data
			exit;
		}

	    $sel_course_array = array();
		if ($selcourseids != FALSE) {
			$sel_course_array = explode(' ', $selcourseids);
		}

		$old_courses = array();

		$coursearray = array();
		foreach ($all_courses as $course) {
		 	if( in_array($course->courseid, $sel_course_array) ) {
		 	    $old_courses[$course->courseid] = $course->course;
		 	} else
		 		$coursearray["{$course->courseid}"] = $course->course;
		}


		$data = array();

		if ($addmode==TRUE) {
			$keys = array_keys($_POST);
			foreach($keys as $key) {
				if ($key == 'unittype')
					$unittype = $_POST[$key];
				if ($key == 'title')
					$title = $_POST[$key];
				if ($key == 'description')
					$description = $_POST[$key];
				if ($key == 'startdate')
					$startdate = $_POST[$key];
				if ($key == 'enddate')
					$enddate = $_POST[$key];

	    	}
	    	$data['unittype'] = $unittype;
			$data['title'] = $title;
		    $data['description'] = $description;
		    $data['startdate'] = $startdate;
		    $data['enddate'] = $enddate;
		}

		$data['selcourses'] = $courseid;
		$data['courseid'] = $courseid;
		$data['courseids']  = $selcourseids;
		$data['addmode'] = $addmode;
		$data['coursearray'] = $coursearray;
	    $data['old_courses'] = $old_courses;
	    $data['unit_template'] = $unit_template;

		if ( is_numeric($unitid)  ) {
	    	$data['unitid'] = $unitid;
	    	$lastids = $this->unit_model->get_childs_dynamic($unitid,TRUE);
	    	$data['lastids'] = $lastids;
		}

		$this->load->view('unit/listunit_view',$data);
	}

	function distribute($unitid) {
		$unit = $this->unit_model->check_unit_editaccess($unitid);

		if ( !$this->unit_model->confirm_distribute_unit($unit) ) {
			echo osa_ajaxmsg(lang('unit_internalservererror'));
     		exit;
		}
		$this->edit($unitid);
	}

	//TODO: this is a function that is totally not necessary. It can be done on the Javascript side.
	//This looks like to tell the browser did the user select linked courses to delete from unified and integrated unit
	function check_delete_mode() {
	    $dels = '';
		$keys = array_keys($_POST);
	    $pattern = 'courseid';
	    $isDelete = 0;	// 0 = FALSE;

		if (!is_array($keys) || count($keys) == 0 ) {
			// not error but no data
			$command = $isDelete.'|'.$dels.'|';
			ECHO $command;
			return FALSE;
		}

	    foreach($keys as $key) {
	    	$tok = strtok($key,'_');
	    	if ( $key != $pattern && $tok==$pattern && isset($_POST[$key]) && $_POST[$key] != '' && is_numeric(str_replace($pattern.'_','',$key)) ) {
	    		$tmp = str_replace($pattern.'_','',$key) ;
	    		$dels .= $tmp.' ';
	    		$tmp = '';
	    		$isDelete = 1; //1 = TRUE;
	    	}
	    }
	    $command = $isDelete.'|'.$dels.'|';

	    ECHO $command;

	    return FALSE;
	}

	//Add a unit for integrated & unified units
	//Right now we let editors to put unified and int. units to courses even if they have no edit access to the other courses
	//As long as they are the editor for the current unit/course then it is OK to let them go crazy!
	function insert_child_unit() {
	   $unitid = $_REQUEST['unitid'];
		if ( !is_numeric($unitid) ) {
			echo lang('gen_internalservererror');
			return FALSE;
		}
		//Check to see if the current user can edit the master unit
		//This is only access checking. This function does not check fo the target course access. This is a feature and not a bug.
		if ( !$this->unit_model->check_unit_editaccess($unitid) ) {
			echo lang('gen_no_permission_ajaxmsg');
			return FALSE;
		}

		$course_array = FALSE;

	   if (isset($_REQUEST['_course']))
	    	$course_array   = $_REQUEST['_course'];
		else {
			echo lang('unit_no_data'); // not error but no data
			return FALSE;
		}

		$original = array();
		//$passAccess = TRUE;
		if ($course_array != FALSE && is_array($course_array)  ) {
			foreach ($course_array as $course) {
				$original[$course]= $course;
				/*
				if ($this->unit_model->checkEditAccess($course)!==TRUE) {
					$passAccess = FALSE;
					break;
				} else {
					$original[$course]= $course;
				}
				*/
			}
		}
		/*
		if (!$passAccess) {
			echo lang('gen_no_permission_ajaxmsg');
			return FALSE;
		}*/
		if (!is_array($original) || count($original) == 0 ) {
			// not error but no data
			return FALSE;
		}
		$data_add = array();
	    $data = $this->make_child_dataarray($unitid);

	    if ( $data==FALSE || !is_array($data)) {
			echo lang('gen_internalservererror');
			return FALSE;
		}

		foreach ($original as $key => $value) {
			$data['courseid'] = $key;
			$data_add[]  = $data;
		}

		$add_units = $this->unit_model->add_childs($data_add , $unitid) ;

		if ( $add_units==FALSE) {
		  	echo 'FALSE';
		} else
	    	echo 'TRUE';

		return FALSE;
	}

	function make_child_dataarray($unitid) {
		$dbdate = osa_dbdate();
	   $user = $this->login_model->getLogin();
		$unit = $this->unit_model->get_unit($unitid);

		if ( $user==FALSE) {
			echo lang('gen_internalservererror');
			return FALSE;
		}
		if ( $unit==FALSE) {
			echo lang('gen_internalservererror');
			return FALSE;
		}

		$courseid = '';
	    $child_type = $this->unit_model->TYPE_NORMAL;
	    if ($unit->type == $this->unit_model->TYPE_INT_PARENT) {
	    	$child_type =  $this->unit_model->TYPE_INT;
	    } elseif ($unit->type == $this->unit_model->TYPE_UNI_PARENT) {
	    	$child_type =  $this->unit_model->TYPE_UNI;
	    }

	    $data = array (
			'courseid' => $courseid,
			'creatorid' => $user->id,
			'lasteditorid' => $user->id,
			'title' =>  $unit->title,
			'description' => $unit->description,
			'startdate' => $unit->startdate,
			'enddate' =>  $unit->enddate,
			'createdate' => $dbdate,
			'modifydate' => $dbdate,
			'editdate' => $dbdate,
			'status' => $this->unit_model->STATUS_NOTACTIVE,
			'type' => $child_type,
		);
		return $data;
	}

	function delete_child_unit() {
		$unitid = $_REQUEST['unitid'];

		if ( !is_numeric($unitid) ) {
			echo lang('gen_internalservererror');
			return FALSE;
		}

	    $keys = array_keys($_POST);
	    $pattern = 'courseid';
	    $del_course = array();

	    if (!is_array($keys) || count($keys) == 0 ) {
			echo lang('gen_internalservererror');
			return FALSE;
		}

	    foreach($keys as $key) {
	    	$tok = strtok($key,'_');
	    	if ($key != $pattern && $tok==$pattern && isset($_POST[$key]) && $_POST[$key] != '' ) {
	    		$courseid = str_replace($tok.'_','',$key);
	    		$del_course[$courseid] = $_POST[$key];
	    	}
	    }
	    $unit_del = array();
		$unit_old = $this->unit_model->get_childs_unit($unitid);

	 	if (!is_array($del_course) || count($del_course) == 0 ) {
			echo lang('gen_internalservererror');
			return FALSE;
		}

		if (!is_array($unit_old) || count($unit_old) == 0 ) {
			echo lang('gen_internalservererror');
			return FALSE;
		}

		foreach ($unit_old as $unit) {
			if (array_key_exists( (int)$unit->courseid , $del_course ) )
				$unit_del[(int)$unit->courseid] = $unit;
		}

		if (!is_array($unit_del) || count($unit_del) == 0 ) {
			echo lang('gen_internalservererror');
			return FALSE;
		}

		if ($this->unit_model->remove_childs($unit_del) ) {
		  	echo 'TRUE';
		} else
	    	echo 'FALSE';

		return FALSE;
	}

	//Prepare data variables for $this->add function/view
	function store_post($courseid, $_POST,$unit_template) {
		$course = $this->course_model->get_course($courseid);
		if ( $course==FALSE || !isset($course->name)) {
				echo lang('gen_internalservererror');
			return FALSE;
		}

		$coursename = $course->name;
	    //For Integrated Unit & Unified Unit : store data before save
	    $pattern = 'courseid';
	    $keys = array_keys($_POST);

		if (!is_array($keys) || count($keys) == 0 ) {
			echo lang('gen_internalservererror');
			return FALSE;
		}

		$del_array= array();
		$courseids = '';
		foreach($keys as $key) {
			if ($key == 'unittype')
				$unittype = $_POST[$key];
			if ($key == 'title')
				$title = $_POST[$key];
			if ($key == 'description')
				$description = $_POST[$key];
			if ($key == 'startdate')
				$startdate = $_POST[$key];
			if ($key == 'enddate')
				$enddate = $_POST[$key];
			if ($key == '_course')
				$_course = $_POST[$key];
			$tok = strtok($key,'_');

	    	if ($tok==$pattern && isset($_POST[$key]) && is_numeric( str_replace($pattern.'_','',$key) )  ) {
	    		$tmp = str_replace($pattern.'_','',$key) ;
	    		if ($_POST[$key] != '')
	    			$del_array[] = $tmp;
	    		else
	    			$courseids .= $tmp.' ';
	    	}
	    }

	   	if (!isset($unittype))
	   		$unittype = '';
	   	if (!isset($title))
	   		$title = '';
	   	if (!isset($description))
	   		$description = '';
	   	if (!isset($startdate))
	   		$startdate = '';
	    if (!isset($enddate))
	   		$enddate = '';

	    if (isset($_course)) {
	   		foreach ($_course as $course) {
	   			$courseids .= $course.' ';
	   		}
	   	}
	   	$key_courseids = explode(" ", trim($courseids));
	   	asort($key_courseids);

	   	$sel_coursenames = '';
	   	$all_courses = $this->unit_model->get_enable_courses($courseid);
	   	$i = 0;
	   	if ( $all_courses ) { //Make sure we have courses,without this app with an empty DB would break
		   	foreach ($all_courses as $course) {
		   		if (in_array($course->courseid, $key_courseids) ) {
		   			$sel_coursenames .=$course->course.'|';
		   			$i +=1;
		   		}
		   		if ($i >= count($key_courseids)) {
		   			break;
		   		}
		   	}
	   	}
	   	$coursenames_array = array();
	   	if ($sel_coursenames != '' && strlen($sel_coursenames) > 1) {
	   		$sel_coursenames = substr($sel_coursenames,0, strlen($sel_coursenames)-1);
	   		$coursenames_array = explode("|", trim($sel_coursenames));
	   	}
		// for meta unit , integrated unit and unified unit
      	$template=$this->unit_model;

	   	$data = array();
		$data['unittype'] = $unittype;
		$data['sel_coursenames'] = $coursenames_array;
		$data['unit_title'] = $title;
		$data['description'] = $description;
		$data['startdate'] = $startdate;
		$data['enddate'] = $enddate;

		$data['courseids'] = $courseids;
		$data['courseid'] = $courseid;
		$data['coursename'] = $coursename;
		$data['template']  = $template;
		$data['unit_template']  = $unit_template;

		return $data;
	}

	function changetype($unitid , $courseid,$unit_template=FALSE) {
		if ( !is_numeric($unitid) && !is_numeric($courseid))
			return FALSE;
		$childs = $this->unit_model->get_childs_unit($unitid);

		$data->courseids = '';
		$sep = '';
		if ($childs != FALSE && is_array($childs)) {
			foreach ($childs as $row) {
				$data->courseids .= $sep . $row->courseid;
				$sep = ' ';
			}
		}

	    $unit = $this->unit_model->check_unit_editaccess($unitid);
	    $data->radios = array();
	    $data->radios[$this->unit_model->TYPE_NORMAL] = lang('unit_normal');
	  //if ($unit_template == CMS_PYP_TEMPLATE || $unit_template == CMS_MYP_TEMPLATE){
	    	if ($this->config->item('cms_use_all_unit_types') || $this->config->item('cms_use_unit_integrated') )
	    		$data->radios[$this->unit_model->TYPE_INT_PARENT] = lang('unit_integratedunit');
	 //}

	    if ($this->config->item('cms_use_all_unit_types') || $this->config->item('cms_use_unit_unified') )
	    	$data->radios[$this->unit_model->TYPE_UNI_PARENT] = lang('unit_unifiedunit');

	    if ($unit != FALSE)
	    	$data->default = $unit->type;
	    else
	    	$data->default = $this->unit_model->TYPE_NORMAL;

	    $data->comfirm = array();
	    if ($data->default  == $this->unit_model->TYPE_NORMAL) {
			$data->comfirm[$this->unit_model->TYPE_NORMAL]     = '';
			$data->comfirm[$this->unit_model->TYPE_INT_PARENT] = lang('unit_change_type_comfirm');
			$data->comfirm[$this->unit_model->TYPE_UNI_PARENT] = lang('unit_change_type_comfirm');
	    }
		elseif ($data->default  == $this->unit_model->TYPE_INT_PARENT) {
			$data->comfirm[$this->unit_model->TYPE_NORMAL]     = lang('unit_change_type_haschilds');
			$data->comfirm[$this->unit_model->TYPE_INT_PARENT] = '';
			$data->comfirm[$this->unit_model->TYPE_UNI_PARENT] = lang('unit_change_type_haschilds');
		}
		elseif ($data->default  == $this->unit_model->TYPE_UNI_PARENT) {
			$data->comfirm[$this->unit_model->TYPE_NORMAL]     = lang('unit_change_type_haschilds');
			$data->comfirm[$this->unit_model->TYPE_INT_PARENT] = lang('unit_change_type_haschilds');
			$data->comfirm[$this->unit_model->TYPE_UNI_PARENT] = '';
	    }
	 //   $childs = $this->unit_model->get_childs_unit($unitid);
	  //  if ($childs == FALSE)
	  //  	$childs = $this->unit_model->get_childs_unit($unit->currentunitid);
		/*
	    if ($childs != FALSE)
	    	$data->comfirm = lang('unit_button_change_haschilds');
	    else
	        $data->comfirm = lang('unit_button_change_comfirm');
	    */

		$data->title   = lang('unit_change_type_title');
		$data->body    = lang('unit_change_type_body');

		$data->unitid    = $unitid;
		$data->courseid  = $courseid;
		$this->load->view( 'unit/unit_change_view',$data);
	}

	function updatetype($unitid) {
		$unit = $this->unit_model->check_unit_editaccess($unitid);
		if ( $unit->status != $this->unit_model->STATUS_EDIT ) {
			echo osa_ajaxmsg(lang('unit_internalservererror'));
      		exit;
		}
		//$update->id   = $unit->id;
		$update->type = $_POST['unittype'];
		$this->unit_model->update_change_type($unit->id, $update);
		//$childs = $this->unit_model->get_childs_unit($unitid);

		if ($unit->type != $this->unit_model->TYPE_NORMAL  ) {
			//var_dump($unit);
			$currentunitid = $unitid;
			$childs = $this->unit_model->get_childs_unit($unitid);
	    	//if ($childs == FALSE) {
	    		//$childs = $this->unit_model->get_childs_unit($unit->currentunitid);
	    		//$currentunitid = $unit->currentunitid;
	    	//}

	    	if ($childs == FALSE) {
	    		echo 'success';
	    		return FALSE;
	    	}

	    	$course = array();
	    	foreach ($childs as $child) {
	    		$temp = null;
	    		$temp->currentunitid = $currentunitid;
	    		$temp->id = $child->id;
	    		$course[] = $temp;
	    	}

	    	//var_dump($course);
			$this->unit_model->remove_childs($course);
		}
		echo 'success';
		return FALSE;
	}
    function showhide($groupid, $showhide) {
		if ( !is_numeric($groupid) && !is_numeric($showhide))
			return FALSE;

		$result=$this->unit_model->edit_showhide($groupid,$showhide);

		if ($result == 1)
			$result = 'success';

		echo $result;
		$this->load->library('cms/memory_table/unit_cache_table');
		$this->unit_cache_table->update();
	}
    private function display_none() {
    	return 'display:none;';
    }
 	private function display_block() {
    	return 'display:block;';
    }

    function copy_refresh($desc_courseid) {
		$this->copy_index($desc_courseid, FALSE, TRUE);
    }

	function copy_index($desc_courseid, $from_courseid=FALSE, $refresh=FALSE , $undo_unitid=FALSE) {
		if ($refresh) {
			if (isset($_POST['unitids'])) {
				$_POST['unitids'] = null;
			}
		}
		$notin_unit = FALSE;
		$unit_select = '';
		$sep = '';

    	if (isset($_POST['unitids'])) {
			$unit_select = implode(',', $_POST['unitids']) ;
    	}
    	if ( !is_numeric($desc_courseid) )
			return FALSE;

		if ($from_courseid == FALSE) {
			if (isset($_POST['courseid']))
				$from_courseid    = $_POST['courseid'];
			else
				$from_courseid    = '';//$desc_courseid;
		}

		$sep = '';
    	if ($unit_select != '') {
    		$sep = ',';
    	}

		if (isset($_POST['txt_unitids']) && $_POST['txt_unitids'] != FALSE) {
    		$unit_select .= $sep . $_POST['txt_unitids'];
		}

    	$notin_unit  = explode(',',$unit_select);
    	$temp_unitid = FALSE;
    	if ($undo_unitid != FALSE) {
    		$temp_unitid  = array_search($undo_unitid, $notin_unit);
    	}

    	if (is_numeric($temp_unitid) && is_array($notin_unit))
    		unset($notin_unit[$temp_unitid]);

		$unit_select = implode(',',$notin_unit);

		$data = new stdClass();
		$data->from_courseid  = $from_courseid;
		$data->course    	  = $this->unit_model->get_course_unit();
		$data->unit_select	 = $unit_select;
		$data->unit    		  = $this->unit_model->get_publish_unit($from_courseid, $notin_unit);
		$data->units_title	  = $this->unit_model->get_units($notin_unit);
		$data->courseoldid    = $desc_courseid;
		$courseoldname   	  = $this->unit_model->get_sel_course($data->courseoldid);
   	$data->courseoldname  = $courseoldname->name;
   	$coursename   	      = $this->unit_model->get_sel_course($desc_courseid);
   	$data->coursename	  = $coursename->name;
   	$data->coursenew	  = $data->course ;
   	$data->courseid =$desc_courseid;
   	$data->target = array();
   	$data->selected_tar  = null;

   	osa_array_natsort($data->course, 0, TRUE);
   	osa_array_natsort($data->unit, 0, TRUE);
   	$this->load->view('unit/unit_copy_view',$data);
    }

   //Function for copying a unit for the copy unit web function
	function copy_save($desc_courseid) {
		//Make sure couseid is numeric and user has permission for the course
		if ( !is_numeric($desc_courseid) || !$this->unit_model->iseditor($desc_courseid) ) {
			//TODO: needs better error handling
			return false;
		}

		if (isset($_POST['txt_unitids']) && $_POST['txt_unitids'] != FALSE)
			$unitids  = explode(',', $_POST['txt_unitids']);
		else {
			$this->copy_index($desc_courseid, FALSE, TRUE);
			return false;
		}

		//Setting $_POST to null so it empties out the unit selections in copy_index()
		//TODO: This is a very bad programming practice, have to change it later
		$_POST = null;
		$user = $this->login_model->getLogin();
	 	foreach ($unitids as $unitid) {
	 		//$unit = $this->unit_model->check_unit_editaccess($unitid);
	 		$unit = $this->unit_model->get_current_unit($unitid);
	 		//TODO: should have better error handle if no unit from above
	 		if ( !$unit ) {
	 			continue;
	 		}
			$unitid = $unit->id;

			if ($unit->type == $this->unit_model->TYPE_UNI && isset($unit->parentid)) {
				$parentid = $unit->parentid;
				$newunitid = $this->unit_model->copy_unit($parentid, $user, $desc_courseid);
				$this->unit_model->reinitialize(lang('unit_copyof') . " $unit->title", $newunitid);
				//$this->copy_index($desc_courseid, FALSE, TRUE);
			}elseif ($unit->type == $this->unit_model->TYPE_INT && isset($unit->parentid)) {
				$newunitid = $this->unit_model->copy_unit($unitid, $user, $desc_courseid);
				$this->unit_model->reinitialize(lang('unit_copyof') . " $unit->title", $newunitid);
				//$this->copy_index($desc_courseid, FALSE, TRUE);
			}
			else  {
				//normal type & meta type
				$newunitid = $this->unit_model->copy_unit($unitid, $user, $desc_courseid);
				$this->unit_model->reinitialize(lang('unit_copyof') . " $unit->title", $newunitid);
				//$//this->unit_model->update($newdata, $newunitid);
				//$this->copy_index($desc_courseid, FALSE, TRUE);
			}
	 	}
	 	$this->copy_index($desc_courseid, FALSE, TRUE);
	 	return false;
		//var_dump($newdata);
	//	update_copyunit($newunitid, $desc_courseid);
    }

   //Check and handle multiple editor for read and edit unit page
   private function _multi_editor_handle($unit, $data, $ro_page=FALSE) {
   	if ( !$this->multi_editor_support )
   		return TRUE;
   	//User with unit admin write can do anything
   	if ( !is_object($unit) || !is_object($data) ) {
   		echo osa_ajaxmsg(lang('unit_unitnotavailable'));
			exit;
   	}
   	if ( $unit->status != $this->unit_model->STATUS_EDIT )
   		$unit = $this->unit_model->get_edit_unit($unit->id);
   	if ( !is_object($unit) ) {
   		echo osa_ajaxmsg(lang('unit_unitnotavailable'));
			exit;
   	}
   	$user = $this->login_model->getLogin();
   	$has_admin_unitwrite = $this->unit_model->has_admin_write_access();
   	$unitlock_expired = $this->_lock_time_expired($unit);
   	$edit_inative_hours = $this->_editaccess_inactive_hours($unit);
   	$is_mycourse = TRUE;
   	//$data->skipedit_buttons = FALSE;
   	$data->show_finishediting_button = FALSE;

   	if ( ($is_editor = $this->unit_model->iseditor($unit->courseid)) == FALSE )
   		$is_mycourse = $this->course_model->isMyCourse($user->id, $unit->courseid);

   	if ( $is_mycourse ) {
   		$data->unit_editor_name =
   			osa_user_getname($this->login_model->getDbUserByid($unit->editorid));
   		$this->_get_timelimit_msg($data,$unit,$edit_inative_hours);
   	}

   	//We still get the published unit and no editing unit so do nothing here and return
   	if ( $unit->status != $this->unit_model->STATUS_EDIT && !$ro_page )
   		return TRUE;

   	//Editing unit exists and it is available for edit and not clicked from published page
   	if ( is_null($unit->editorid) && $is_editor && !$this->edit_turn_editingon) {
   		if ( !$ro_page ) {
   			$this->_load_ro_view($unit->id);
   		}
   		return FALSE;
   	}

   	//Someone else is editing the unit
   	//if ( !is_null($unit->editorid) && !$has_admin_unitwrite && $unit->editorid != $user->id && $is_editor) {
   	//If unit lock expires then we want admin to get the readonly page with turnediton
   	if ( !is_null($unit->editorid) && !$has_admin_unitwrite && $unit->editorid != $user->id && $is_editor ||
   		  ($has_admin_unitwrite && $unit->editorid != $user->id) ) {
   		if ( !$has_admin_unitwrite || $unitlock_expired )
   			$data->unit_lock_release_msg = lang('unit_lock_release_msg');
   		else {
   			//Show Done Editing button on unit read for admin
   			$data->unit_lock_release_msg = FALSE;
				$data->show_finishediting_button = TRUE;
   		}
   		if ( $unitlock_expired || $has_admin_unitwrite ) {
   			$data->disable_edit_button = FALSE;
	   		$data->disable_remove_button = FALSE;
	   		//edit_turn_editingon should not get read only page
	   		if ( $this->edit_turn_editingon ) {
					if ( $this->unit_model->lock_unit($unit->id, $unit->editorid) ) {
						$data->unit_editor_name = osa_user_getname($user);
						$data->unit->editorid = $user->id;
						$this->unit_model->update_edit_accessdate($data->unit);
						$data->unit->edit_accessdate = osa_dbdate();
						$unit->edit_accessdate = osa_dbdate();
						$edit_inative_hours = $this->_editaccess_inactive_hours($data->unit);
						$this->_get_timelimit_msg($data,$unit,$edit_inative_hours);
						$data->show_finishediting_button = TRUE;
						return TRUE;
					}
					return FALSE;
	   		}
	   		if ( !$ro_page ) {
	   			$this->_load_ro_view($unit->id);
	   			return FALSE;
	   		}
	   		//$data->unit_lock_release_msg = 'You can do it';
   		}
   		else {
	   		$data->disable_edit_button = TRUE;
	   		$data->disable_remove_button = TRUE;
	   		if ( !$ro_page )
	   			$this->_load_ro_view($unit->id);
   			return FALSE;
   		}
   	}

   	//In valid edit mode. Add finish edit button
   	if ( !$ro_page && $unit->status == $this->unit_model->STATUS_EDIT &&
   		  ($unit->editorid == $user->id || $has_admin_unitwrite || is_null($unit->editorid) )) {
   		$data->show_finishediting_button = TRUE;
   		if ( is_null($unit->editorid ) || $unitlock_expired ) {
   			//Won't let admin lock the unit unless he is the original editior
   			//if ( (!$has_admin_unitwrite || $unit->editorid == $user->id) && $this->unit_model->lock_unit($unit->id) ) {
   			if ( $this->unit_model->lock_unit($unit->id) ) {
   				//This is to prevent admin user looking at a unexpired editing unit
   				//if ( is_null($unit->editorid) || $unit->editorid == $user->id ) {
   					$data->unit->editorid = $user->id;
	   				$this->unit_model->update_edit_accessdate($data->unit);
	   				$data->unit->edit_accessdate = osa_dbdate();
	   				$unit->edit_accessdate = osa_dbdate();
	   				$data->unit_editor_name = osa_user_getname($user);
   				//}
	   			$edit_inative_hours = $this->_editaccess_inactive_hours($data->unit);
					$this->_get_timelimit_msg($data,$unit,$edit_inative_hours);
   			}
   		}
   	}
   	//If we get here then we just continue edit or read-only page like usual
   	return TRUE;
   }

   function unlock($unitid) {
   	$this->unit_model->unlock_unit($unitid);
   	$this->index($unitid);
   }

   //Updates the hide private resources for PDF to the user table
	function privateres($flag) {
		if ( strtolower($flag) == 'false' ) {
			$flag = CMS_DB_BOOLEAN_TRUE;
		}
		else {
			$flag = CMS_DB_BOOLEAN_FALSE;
		}
		if ( !$this->unit_model->update_user_privateres_flag($flag) ) {
			echo osa_ajaxmsg(lang('unit_failed_update_pdf_privateres_msg'));
			exit;
		}
   }

   private function _lock_time_expired($unit) {
   	//Feature is disabled if set to FALSE
   	if ( $this->config->item('cms_unitlock_hour_expire') == FALSE )
   		return FALSE;
   	$inactive_hours = $this->_editaccess_inactive_hours($unit);
   	//Problem happened
   	if ( $inactive_hours === FALSE )
   		return FALSE;
   	if ( $inactive_hours >= $this->config->item('cms_unitlock_hour_expire') )
   		return TRUE;
   	return FALSE;
   }

   //FALSE - Not expired and keep locking. Have to use ===
   //Integer - edited how many days ago
   private function _editaccess_inactive_hours($unit) {
   	if ( !is_object($unit) )
   		return FALSE;
   	//No time means expired but this should never happen
   	if ( is_null($unit->edit_accessdate) )
   		return FALSE;
   	$edit_time = strtotime($unit->edit_accessdate);
   	//Current time should never be less than 1000000000 - 2001/9/9
   	//if ( $edit_time == FALSE || $edit_time < 1000000000 )
   	if ( empty($edit_time) )
   		return FALSE;
   	//UNIX time in seconds
   	$current_time = time();
   	//$diff is zero for unit editor since the edit_accessdat was updated right before this function
   	$diff = $current_time - $edit_time;
   	if ( $diff < 0 )
   		return FALSE;
   	//return (int)($diff/3600);
   	//return sprintf('%01.2f', ($diff/3600));
   	return ($diff/3600);
   }

   //$data contains $unit but it can be published unit. $unit parameter is always the edting unit if there is one
   //since the timelimt and editacess date should come from the editing unit
   private function _get_timelimit_msg($data, $unit, $edit_inative_hours) {
   	if ( !is_object($data) || !is_object($unit) )
   		return FALSE;
   	if ( ($time_limit = $this->config->item('cms_unitlock_hour_expire')) != FALSE &&
   		   !is_null($unit->editorid)) {
   		if ( $time_limit > 24 ) {
   			$day_limit = (int)($time_limit/24);
   			$inactive_days = (int)($edit_inative_hours/24);
   			$data->timelimit_msg = sprintf(lang('unit_timelimit_day_msg'),$inactive_days,$day_limit);
   		}
   		else {
   			if ( $edit_inative_hours > 48 )
   				$data->timelimit_msg = sprintf(lang('unit_timelimit_hour_msg_day'),(int)($edit_inative_hours/24),$time_limit);
   			else
   				$data->timelimit_msg = sprintf(lang('unit_timelimit_hour_msg'),(int) $edit_inative_hours,$time_limit);
   		}
   	}
   }
   function read_bygroupid($groupid) {
   	if ( !is_numeric($groupid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}

		$unit = $this->unit_model->get_publish_units_bygroup($groupid);

		if ($unit == FALSE) {
			 $unit = $this->unit_model->get_publish_unit_byedit($groupid);  // STATUS_EDIT
			 if ( !$unit ) {
			 	 $unit = $this->unit_model->get_publish_unit_bydelete($groupid);  // STATUS_EDIT

				 if ( !$unit ) {
					echo osa_ajaxmsg(lang('unit_unitnotavailable'));
					exit;
				}
			}
			if (is_array($unit))
				 $unit = $unit[0];
		   $this->_load_ro_view($unit,TRUE,TRUE);
		}
		else //STATUS_PUBLISH
			 $this->read($unit->id);
   }

	private function date_validation($startdate,$enddate){
	 	if ($enddate <= $startdate){
	    	echo osa_ajaxmsg(lang('unit_pleasecorrecterror').lang('unit_error_date'));
	      exit;
	    }
   }
   private function teacher_course($courseid,$template){
   	$data = array();
   	$grade_level = '';
   	if ( !is_numeric($courseid) )
			return;
		$gradesobj = $this->course_model->get_grades($courseid);
		$display_grades = $this->course_model->get_displaygrades($courseid);
		$tearchers = $this->course_model->getEditorUsers($courseid,FALSE);
		$editornames = osa_user_getname($tearchers);
		if ( isset($gradesobj) && is_array($gradesobj) ) {
			$sep='';
			foreach($gradesobj as $grade){;
				if ( isset($display_grades) && is_array($display_grades) ) {
					foreach ($display_grades as $dgrade) {
						if ( $dgrade->gradeid == $grade->id ) {
							$grade_level .= $sep.$grade->name;
							$sep=', ';
							break;
						}
					}
				}
			}
		}
		if ($template == CMS_MYP_TEMPLATE){
			$data['tearchers'] = $editornames;
	   	$data['grade_level'] = $grade_level;
		}
		else{
			$data['tearchers'] = '';
	   	$data['grade_level'] = '';
		}

   	return $data;
   }
   //Tells a template has paging or not.
   private function get_paging($template) {
   	if ( $template === FALSE ){
			osa_errorlog(__METHOD__ . " -  Invalidate template filename in Function get_paging ", $template);
			echo osa_ajaxmsg(lang('unit_no_permissionmsg'));
			exit;
		}
   	$this->load->library('cms/cms_template/cms_template');
		return $this->cms_template->ispaging($template);
   }
}
?>