<?php
 //die('hhehe');
set_time_limit(0);
if($_REQUEST['servicemod']=='mod_curriculum/ScdStudSchedWizard.php' && !$_REQUEST['run'])
{
	$function = 'Prompt';
	get_student_info();
}
else
	$function = '_returnTrue';
//echo "<pre>";print_r($_REQUEST);die;	
$school_terms_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,SHORT_NAME,TITLE FROM SCHOOL_SEMESTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
$mps_html_extra = '<center><BR><TABLE width=100% cellspacing=0 cellpadding=2 BGCOLOR=#'.Preferences('HIGHLIGHT_BACKGROUND').'><TR><TD style="border-width:1px;border-color:'.Preferences('HIGHLIGHT').';border-style:inset none inset none;">'._('Check the semester(s) if you want to create the schedule within these semesters:').'</TD>';

if(Preferences('MULTI_CHECKBOX_MPS','Schedule'))
	$mps = unserialize(Preferences('MULTI_CHECKBOX_MPS','Schedule'));
else
{
	foreach($school_terms_array as $mp)
		$mps[$mp['SCHOOL_TERM_ID']] = 'Y';
}

foreach($school_terms_array as $mp)
{
	$mps_html_extra .= '<TD style="border-width:1px;border-color:'.Preferences('HIGHLIGHT').';border-style:inset none inset none;"><INPUT type=checkbox name=mps['.$mp['SCHOOL_TERM_ID'].'] id=mps['.$mp['SCHOOL_TERM_ID'].'] value="Y" '.($mps[$mp['SCHOOL_TERM_ID']]=='Y'?'CHECKED':'').'><LABEL for="mps['.$mp['SCHOOL_TERM_ID'].']">'.$mp['SHORT_NAME'].'</LABEL></TD>';
}
$mps_html_extra .= '</TR></TABLE>';
//echo $mps_html_extra;
//die('test');
if($function(_('Run Scheduler Confirmation'),_('Do you want to run the scheduler?'),'<TABLE><TR><TD><INPUT type=checkbox name=test_mode id=test_mode value=Y></TD><TD><LABEL for="test_mode"><font color=red>'._('Test Mode').'</font> (<small>'._('Using the Test Mode, you can make any changes, but they will not be saved and at the same time you can watch the results of theses changes.').'</small>)'.'</LABEL></TD></TR><TR><TD><INPUT type=checkbox name=delete id="delete" value=Y></TD><TD><LABEL for="delete"><font color=red>'._('Delete Current Schedules').'</font> (<small>'._('You can delete the existing in system schedules, so that scheduler can start from scratch. Locked sections in the students schedule will not be deleted.').'</small>)'.'</LABEL></TD></TR></TABLE></CENTER>'.$mps_html_extra.'<CENTER>'))
{
	$mps_extra = "'0'";
	if($_REQUEST['mps'])
	{ 
		foreach($_REQUEST['mps'] as $sem=>$y)
		{
			$mps_extra .= ",'".$sem."'";
			if(get_child_school_term('SEM',$sem))
				$mps_extra .= ",".get_child_school_term('SEM',$sem);
		}
	}
	else
	{
		foreach($school_terms_array as $sem)
		{
			$sem = $sem['SCHOOL_TERM_ID'];
			$mps_extra .= ",'".$sem."'";
			if(get_child_school_term('SEM',$sem))
				$mps_extra .= ",".get_child_school_term('SEM',$sem);
		}
		
	}

	if($_REQUEST['student_id'])
		echo '<DIV id=scheduler_confirm style="background-color:#b6b7cb;padding:20px;position:absolute;display:block;left:50%;top:150px;height:200px;width:400px;margin-left:-200px;border:1px solid #f8f8f9;">';
	else
	{
		echo '<BR>';
		PopTable('header',_('Scheduler Progress'));
	}
	echo '<CENTER><TABLE cellpadding=0 cellspacing=0 style="border: inset #C9C9C9 2px;"><TR><TD><TABLE height=19 cellspacing=0 border=0 bgcolor=#FFFFFF><TR>';
	for($i=1;$i<=100;$i++)
		echo '<TD id=cell'.$i.' width=1 bgcolor=#FFFFFF></TD>';
	echo '</TR></TABLE></TD></TR></TABLE><BR><DIV id=percentDIV><IMG SRC=images/spinning.gif> '._('Processing Requests').' ... </DIV></CENTER>';

	if($_REQUEST['student_id'])
		echo '<BR><BR><CENTER><INPUT style="width:100px;" type=button value="'._('OK').'" onclick="document.getElementById(\'scheduler_confirm\').style.display=\'none\';"></CENTER></DIV>';
	else
		PopTable('footer');

	ob_flush();
	flush();
	ini_set('MAX_EXECUTION_TIME',0);
	//die('testinnnng');
	$sql = "SELECT r.REQUEST_ID,r.STUDENT_ID,s.CFIELD_50000 as GENDER,r.SUBJECT_ID,r.COURSE_ID,r.COURSE_CREDIT_TITLE,SCHOOL_TERM_ID,WITH_TEACHER_ID,NOT_TEACHER_ID,WITH_SCHOOL_PERIOD_ID,NOT_SCHOOL_PERIOD_ID,(SELECT COUNT(*) FROM COURSE_SECTIONS cp2 WHERE cp2.COURSE_ID=r.COURSE_ID AND cp2.COURSE_CREDIT_TITLE=r.COURSE_CREDIT_TITLE) AS SECTIONS 
	FROM STUDENT_SCHEDULE_REQUESTS r,COURSES c LEFT OUTER JOIN GRADUATION_REQ_SUBJECTS gs ON (c.GRAD_SUBJECT_ID=gs.ID),STUDENTS s,STUDENT_REGISTRATION ssm LEFT OUTER JOIN SCHOOL_CLASSLEVELS sgl ON (ssm.CLASSLEVEL_ID=sgl.ID)
	WHERE c.COURSE_ID=r.COURSE_ID AND s.STUDENT_ID=ssm.STUDENT_ID AND ssm.SCHOOL_YEAR=r.SCHOOL_YEAR 
	AND ('".get_db_date()."' BETWEEN ssm.START_DATE AND ssm.END_DATE OR ssm.END_DATE IS NULL) ";
	if($_REQUEST['student_id'])
		$sql .= " AND s.STUDENT_ID='".$_REQUEST['student_id']."' ";
	$sql .= "
	AND s.STUDENT_ID=r.STUDENT_ID AND r.SCHOOL_YEAR='".get_school_year()."' AND r.SCHOOL_ID='".get_school_id()."' ORDER BY sgl.SORT_ORDER DESC,COALESCE(r.PRIORITY,-1) ASC,COALESCE(gs.SORT_ORDER,100) ASC,SECTIONS";
	$requests_array = db_request(db_execute($sql),array(),array('REQUEST_ID'));
	//echo "<pre>";print_r($requests_array);die('test');
/*	$sql = "SELECT r.REQUEST_ID,r.PRIORITY,r.STUDENT_ID,s.CFIELD_50000 as GENDER,r.SUBJECT_ID,r.COURSE_ID,r.COURSE_CREDIT_TITLE,SCHOOL_TERM_ID,WITH_TEACHER_ID,NOT_TEACHER_ID,WITH_SCHOOL_PERIOD_ID,NOT_SCHOOL_PERIOD_ID,(SELECT COUNT(*) FROM COURSE_SECTIONS cp2 WHERE cp2.COURSE_ID=r.COURSE_ID AND cp2.COURSE_CREDIT_TITLE=r.COURSE_CREDIT_TITLE) AS SECTIONS 
	,(SELECT REQUEST_ID AS HAS_PRIORITY FROM STUDENT_SCHEDULE_REQUESTS sr2 where r.SCHOOL_YEAR=sr2.SCHOOL_YEAR AND r.SCHOOL_ID=sr2.SCHOOL_ID AND r.REQUEST_ID=sr2.PRIORITY) AS HAS_PRIORITY
	FROM STUDENT_SCHEDULE_REQUESTS r,STUDENTS s,STUDENT_REGISTRATION ssm 
	WHERE s.STUDENT_ID=ssm.STUDENT_ID AND ssm.SCHOOL_YEAR=r.SCHOOL_YEAR 
	AND ('".get_db_date()."' BETWEEN ssm.START_DATE AND ssm.END_DATE OR ssm.END_DATE IS NULL) ";
	if($_REQUEST['student_id'])
		$sql .= " AND s.STUDENT_ID='".$_REQUEST['student_id']."' ";
	$sql .= "
	AND s.STUDENT_ID=r.STUDENT_ID AND r.SCHOOL_YEAR='".get_school_year()."' AND r.SCHOOL_ID='".get_school_id()."' AND r.PRIORITY IS NOT NULL ORDER BY HAS_PRIORITY,SECTIONS";
	$alternates_array = db_request(db_execute($sql),null,array('PRIORITY'));
*/
	if($_REQUEST['student_id'])
	{ 
       //die('helllo');
		if(count($requests_array))
		{
			foreach($requests_array as $request)
			{
				$student_id_courses_extra .= ",'".$request[1]['COURSE_ID']."'";
			}
			$student_id_courses_extra = ' AND COURSE_ID IN ('.substr($student_id_courses_extra,1).') ';
		}
	}
   //die('jiiiiiii');
	if($_REQUEST['delete']=='Y' && count($requests_array)>0)
	{
		if($_REQUEST['student_id'])
       
			$student_id_extra = " AND STUDENT_ID='".$_REQUEST['student_id']."'";
		db_execute("DELETE FROM STUDENT_SCHEDULE WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."'".$student_id_extra." AND SCHOOL_TERM_ID IN (".$mps_extra.") AND (SCHEDULER_LOCK!='Y' OR SCHEDULER_LOCK IS NULL OR SCHEDULER_LOCK='')");
		// NOW, WE still need to update the seats when auto-scheduling just one student
		if(!$_REQUEST['student_id'])
		{
			$course_sections_array = db_request(db_execute("SELECT COURSE_SECTION_ID FROM COURSE_SECTIONS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"),null);
			$current_array = db_request(db_execute("SELECT COURSE_SECTION_ID,FILLED_SEATS,TITLE FROM COURSE_SECTIONS WHERE SCHOOL_YEAR='".get_school_year()."'"),null,array('COURSE_SECTION_ID'));
			$addition = array(
					'SELECT_ONLY'=>'COUNT(*) AS COUNT,cp.COURSE_SECTION_ID',
					'FROM'=>",COURSE_SECTIONS cp LEFT OUTER JOIN STUDENT_SCHEDULE s2 ON (s2.COURSE_SECTION_ID=cp.COURSE_SECTION_ID AND (s2.END_DATE IS NULL OR s2.END_DATE<'".get_db_date('postgres')."'))",
					'WHERE'=>str_replace("COURSE_ID","cp.COURSE_ID",$student_id_courses_extra)." AND s2.STUDENT_ID=ssm.STUDENT_ID AND s2.SCHOOL_YEAR=ssm.SCHOOL_YEAR",
					'GROUP'=>' cp.COURSE_SECTION_ID',
					'group' => array('COURSE_SECTION_ID')
				);
				$scheduled_array = get_student_list($addition);
			
			foreach($course_sections_array as $cp)
			{
				if($scheduled_array[$cp['COURSE_SECTION_ID']])
				{
					$section = $scheduled_array[$cp['COURSE_SECTION_ID']][1];
					if($section['COUNT']!=$current_array[$section['COURSE_SECTION_ID']][1]['FILLED_SEATS'])
						db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS='".$section['COUNT']."' WHERE COURSE_SECTION_ID='".$section['COURSE_SECTION_ID']."'");
					$cp_seats_updated[$section['COURSE_SECTION_ID']] = true;
				}
				else
					$empty_sections[] = $cp['COURSE_SECTION_ID'];
			}
			if(count($empty_sections))
			{
				$sections_extra = '';
				foreach($empty_sections as $section)
				{
					$sections_extra .= ','.$section;
				}
				$sections_extra = substr($sections_extra,1);
				db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS='0' WHERE COURSE_SECTION_ID IN (".$sections_extra.")");
			}
		}
		//db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=0 WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_TERM_ID IN (".$mps_extra.")");
	}
	//$count = db_request(db_execute("SELECT count(*) as count from schedule WHERE SCHOOL_ID='".get_school_id()."'"));	
	// echo "<pre>"; print_r( $_REQUEST);die;
	if($DBType == 'mssql')
		$sql = "SELECT PARENT_ID,COURSE_SECTION_ID,COURSE_ID,COURSE_CREDIT_TITLE,CAST(COURSE_ID AS VARCHAR)".CCAT."'-'".CCAT."COURSE_CREDIT_TITLE AS COURSE,GENDER_RESTRICTION,SCHOOL_PERIOD_ID,DAYS,TEACHER_ID,SCHOOL_TERM_ID,MP,COALESCE(TOTAL_SEATS,0)-COALESCE(FILLED_SEATS,0) AS AVAILABLE_SEATS,(SELECT COUNT(*) FROM COURSE_SECTIONS cp2 WHERE cp2.COURSE_ID=cp.COURSE_ID AND cp2.COURSE_CREDIT_TITLE=cp.COURSE_CREDIT_TITLE) AS SECTIONS FROM COURSE_SECTIONS cp WHERE 1=1 ".$student_id_courses_extra." AND cp.SCHOOL_TERM_ID IN (".$mps_extra.") ORDER BY SECTIONS,AVAILABLE_SEATS";
	else
		$sql = "SELECT PARENT_ID,COURSE_SECTION_ID,COURSE_ID,COURSE_CREDIT_TITLE,COURSE_ID".CCAT."'-'".CCAT."COURSE_CREDIT_TITLE AS COURSE,GENDER_RESTRICTION,SCHOOL_PERIOD_ID,DAYS,TEACHER_ID,SCHOOL_TERM_ID,MP,COALESCE(TOTAL_SEATS,0)-COALESCE(FILLED_SEATS,0) AS AVAILABLE_SEATS,(SELECT COUNT(*) FROM COURSE_SECTIONS cp2 WHERE cp2.COURSE_ID=cp.COURSE_ID AND cp2.COURSE_CREDIT_TITLE=cp.COURSE_CREDIT_TITLE) AS SECTIONS FROM COURSE_SECTIONS cp WHERE 1=1 ".$student_id_courses_extra." AND cp.SCHOOL_TERM_ID IN (".$mps_extra.") ORDER BY SECTIONS,AVAILABLE_SEATS";

	$cp_parent_array = db_request(db_execute($sql),array(),array('PARENT_ID'));
	//echo "<pre>";print_r($cp_parent_array);die;
	
	if($DBType == 'mssql')
		$sql = "SELECT PARENT_ID,COURSE_SECTION_ID,COURSE_ID,COURSE_CREDIT_TITLE,CAST(COURSE_ID AS VARCHAR)".CCAT."'-'".CCAT."COURSE_CREDIT_TITLE AS COURSE,GENDER_RESTRICTION,SCHOOL_PERIOD_ID,DAYS,TEACHER_ID,SCHOOL_TERM_ID,MP,COALESCE(TOTAL_SEATS,0)-COALESCE(FILLED_SEATS,0) AS AVAILABLE_SEATS,(SELECT COUNT(*) FROM COURSE_SECTIONS cp2 WHERE cp2.COURSE_ID=cp.COURSE_ID AND cp2.COURSE_CREDIT_TITLE=cp.COURSE_CREDIT_TITLE) AS SECTIONS FROM COURSE_SECTIONS cp WHERE PARENT_ID=COURSE_SECTION_ID AND cp.SCHOOL_TERM_ID IN (".$mps_extra.") ".$student_id_courses_extra." ORDER BY SECTIONS,AVAILABLE_SEATS";
	else
		$sql = "SELECT PARENT_ID,COURSE_SECTION_ID,COURSE_ID,COURSE_CREDIT_TITLE,COURSE_ID".CCAT."'-'".CCAT."COURSE_CREDIT_TITLE AS COURSE,GENDER_RESTRICTION,SCHOOL_PERIOD_ID,DAYS,TEACHER_ID,SCHOOL_TERM_ID,MP,COALESCE(TOTAL_SEATS,0)-COALESCE(FILLED_SEATS,0) AS AVAILABLE_SEATS,(SELECT COUNT(*) FROM COURSE_SECTIONS cp2 WHERE cp2.COURSE_ID=cp.COURSE_ID AND cp2.COURSE_CREDIT_TITLE=cp.COURSE_CREDIT_TITLE) AS SECTIONS FROM COURSE_SECTIONS cp WHERE PARENT_ID=COURSE_SECTION_ID AND cp.SCHOOL_TERM_ID IN (".$mps_extra.") ".$student_id_courses_extra." ORDER BY SECTIONS,AVAILABLE_SEATS";
	
//echo $sql;die;
	$cp_course_array = db_request(db_execute($sql),array(),array('COURSE'));
	//echo "<pre>";print_r($cp_course_array);die;
	$mps_array = db_request(db_execute("SELECT SEMESTER_ID,SCHOOL_TERM_ID FROM SCHOOL_QUARTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"),array(),array('SEMESTER_ID','SCHOOL_TERM_ID'));
	//echo "<pre>";print_r($mps_array);die;
	// GET FILLED/LOCKED REQUESTS
	$sql = "SELECT s.STUDENT_ID,r.REQUEST_ID,s.COURSE_SECTION_ID,cp.PARENT_ID,s.COURSE_ID,s.COURSE_CREDIT_TITLE,cp.SCHOOL_PERIOD_ID 
			FROM STUDENT_SCHEDULE s LEFT OUTER JOIN STUDENT_SCHEDULE_REQUESTS r ON (r.SCHOOL_YEAR='".get_school_year()."' AND r.SCHOOL_ID='".get_school_id()."' AND s.SCHOOL_YEAR=r.SCHOOL_YEAR AND s.SCHOOL_ID=r.SCHOOL_ID
				AND s.COURSE_ID=r.COURSE_ID AND s.COURSE_CREDIT_TITLE=r.COURSE_CREDIT_TITLE AND r.STUDENT_ID = s.STUDENT_ID),COURSE_SECTIONS cp 
			WHERE 
				s.SCHOOL_YEAR=cp.SCHOOL_YEAR AND cp.SCHOOL_YEAR='".get_school_year()."' AND s.COURSE_SECTION_ID=cp.COURSE_SECTION_ID AND s.SCHOOL_TERM_ID IN (".$mps_extra.")";
	// AND cp.PARENT_ID=cp.COURSE_SECTION_ID
	if($_REQUEST['student_id'])
		$sql .= " AND s.STUDENT_ID='".$_REQUEST['student_id']."' ";
	$sql .= "
				AND ('".get_db_date()."' BETWEEN s.START_DATE AND s.END_DATE OR s.END_DATE IS NULL)"; 
	//echo $sql; die;

	$QI = db_execute($sql);
	$locked_array = db_request($QI,array(),array('STUDENT_ID','REQUEST_ID'));
	if(empty($locked_array)){
    	$sql = "select r.STUDENT_ID ,r.REQUEST_ID,r.COURSE_ID,r.COURSE_CREDIT_TITLE,cp.PARENT_ID,cp.SCHOOL_PERIOD_ID,cp.COURSE_SECTION_ID From STUDENT_SCHEDULE_REQUESTS r left join COURSE_SECTIONS cp on cp.COURSE_ID=r.COURSE_ID WHERE r.STUDENT_ID='".$_REQUEST['student_id']."' AND cp.PARENT_ID=cp.COURSE_SECTION_ID AND cp.SCHOOL_TERM_ID IN (".$mps_extra.")";
    	$new_QI = db_execute($sql);
   // echo $new_QI;die('cccc');
		$locked_array = db_request($new_QI,array(),array('STUDENT_ID','REQUEST_ID'));
    	$enrol_userType = "new";
    	//echo "<pre>";print_r($locked_array);
    	//die('new locked_Array');
    }  
	//die('testing locked_Array');
 	//echo "<pre>";print_r($_REQUEST);die;
 	//echo "<pre>";print_r($locked_array);die('ttttt');
	foreach($locked_array as $student_id=>$courses_all)
	{
   		// echo "student_id=".$student_id."<br>";
  		 // echo "<pre>";print_r($courses);die;	
		foreach($courses_all as $request_id=>$courses)
		{
     		// echo "request_idt_id=".$request_id."<br>";
    		//echo "<pre>";print_r($courses);die;	
			if($request_id)
			{
				$course = $courses[1];
				foreach($cp_parent_array[$course['PARENT_ID']] as $slice)
				{
					$schedule[$student_id][$slice['SCHOOL_PERIOD_ID']][] = $slice + array('REQUEST_ID'=>$request_id);
					$filled[$request_id] = true;
				}
			}
			else
			{
                //echo "<pre>";print_r($cp_parent_array);die('ttttt');
				foreach($courses as $course)
				{
			/* rakesh 
			 * 			foreach($cp_parent_array[$course['PARENT_ID']] as $slice)
					
					{
						$schedule[$student_id][$slice['SCHOOL_PERIOD_ID']][] = $slice + array('REQUEST_ID'=>'');
					} */
				}
			}
		}
    
    	/* =======================================   rakesh start  */ 
    	foreach($cp_parent_array as $key => $slice){
			$schedule[$student_id][$slice[1]['SCHOOL_PERIOD_ID']][] = $slice + array('REQUEST_ID'=>'');
		}    	/*   rakesh end  ======================================= */
	} 


	if(ob_get_level() == 0)
		ob_start();

	$last_percent = 0;
	$requests_count = count($requests_array);
//echo "<pre>";print_r($requests_array);die;
	foreach($requests_array as $request_id=>$request)
	{
		// EXISTING / LOCKED COURSE
	//rakesh 	if($locked_array[$request[1]['STUDENT_ID']][$request[1]['REQUEST_ID']])
		if($locked_array[$request[1]['STUDENT_ID']][''][$request[1]['REQUEST_ID']])
		{
			$completed++;
			continue;
		}

		$scheduled = _scheduleRequest($request[1]);

		if(!$scheduled)
		{
			$not_request = array();
			foreach($locked_array[$request[1]['STUDENT_ID']] as $request_id=>$requests)
				$not_request[] = $request_id;
			
			$moved = _moveRequest($request[1],$not_request);
			
			if(!$moved)
			{
				if($alternates_array[$request[1]['REQUEST_ID']])
					$alt_scheduled = _scheduleAlt($alternates_array[$request[1]['REQUEST_ID']]);
			}
			
			if(!$moved && !$alt_scheduled)
				$unfilled[] = $request[1];
			else
				$filled[$request[1]['REQUEST_ID']] = true;
		}
		else
			$filled[$request[1]['REQUEST_ID']] = true;

		$completed++;

		$percent = round($completed*100/$requests_count,0);
		if($percent>$last_percent)
		{
			echo '<script language="javascript">'."\r";
			for($i=$last_percent+1;$i<=$percent;$i++)
				echo 'cell'.$i.'.bgColor="#'.Preferences('HIGHLIGHT').'";'."\r";
			echo 'addHTML("'.$percent.'% '._('Done').'","percentDIV",true);'."\r";
			echo '</script>';
			ob_flush();
			flush();
			$last_percent = $percent;
		}
	}
	// MAKE SURE THAT THE PROGRESS BAR IS COMPLETELY FILLED
	echo '<script language="javascript">'."\r";
	for($i=$last_percent+1;$i<=100;$i++)
		echo 'cell'.$i.'.bgColor="#'.Preferences('HIGHLIGHT').'";'."\r";
	echo '</script>';
	
	echo '<!-- '.is_countable($unfilled).' -->';
	if ($unfilled) {
   // echo "<pre>";print_r($unfilled);die;
		foreach($unfilled as $key=>$request)
		{
//echo"<pre>";print_r($scheduled);die;
			$scheduled = _scheduleRequest($request[1]);
			if(!$scheduled)
			{
				$not_request = array();
           // echo "<pre>";print_r($request);die;
           
				// rakesh    foreach($locked_array[$request['STUDENT_ID']] as $request_id=>$requests)
            	if(!empty($locked_array[$request[1]['STUDENT_ID']] )){
					foreach($locked_array[$request[1]['STUDENT_ID']] as $request_id=>$requests){
						$not_request[] = $request_id;
            		}
                }
				$moved = _moveRequest($request[1],$not_request);

				if($moved)
					unset($unfilled[$key]);
			}
			else
				unset($unfilled[$key]);
		}
	}
	echo '<!-- '.is_countable($unfilled).' -->';
//var_dump($schedule);die;
	if($_REQUEST['test_mode']!='Y')
	{
		echo '<script language="javascript">'."\r";
		echo 'addHTML("<IMG SRC=images/spinning.gif> '._('Saving Schedules').' ... ","percentDIV",true);'."\r";
		echo '</script>';
		echo str_pad(' ',4096);
		ob_flush();
		flush();
		
		$connection = db_start();
		//db_trans_start($connection);
		if($DBType == 'mssql')
			db_execute("BEGIN TRANSACTION");
		else
			db_execute("BEGIN");
		
		db_request(db_execute("CREATE TEMP TABLE STUDENT_SCHEDULE_TEMPORARY (LIKE STUDENT_SCHEDULE)") );
		
		$date = get_db_date();
    //echo "<pre>";print_r($schedule);die;
    	$enroll_courses = array();
    //echo "<pre>";print_r($schedule);die('schedule');
		foreach($schedule as $student_id=>$periods)
		{
        	//echo "<pre>";print_r($periods);die('periods');
       		$enroll_student = $student_id;
        	//echo "student id is is ".$enrollment_Iomad['user_id'];die;
			foreach($periods as $course_sections)
			{
            	//echo "<pre>";print_r($course_sections);die('course_Section');
				foreach($course_sections as $school_period_id=>$course_period)
				{
                		//if( isset($enrol_userType) && $enrol_userType = "new"){
                        	 //$enroll_courses[] =  $course_period['COURSE_ID']; 
                       // }
                		//echo "coursid = ".$course_period['COURSE_ID'];echo "<br>";
     					//echo "<pre>";print_r($course_period);die('course_period')	; // ==========================
			// rakesh		if(!$locked_array[$student_id][$course_period['REQUEST_ID']])
					if(!empty($locked_array[$student_id][$course_period['REQUEST_ID']] ))
					{  
                   
                    		// rakesh modified query with conditions  : Start              
                    	// $enroll_courses[] =  $course_period[1]['COURSE_ID'];  
                   		if(isset($course_period[1])){
                      		 $enroll_courses[] =  $course_period[1]['COURSE_ID']; 
                        	db_execute("INSERT INTO STUDENT_SCHEDULE_TEMPORARY (ID,SCHOOL_YEAR,SCHOOL_ID,STUDENT_ID,START_DATE,COURSE_ID,COURSE_CREDIT_TITLE,COURSE_SECTION_ID,MP,SCHOOL_TERM_ID) values(".db_seq_nextval('STUDENT_SCHEDULE_SEQ').",'".get_school_year()."','".get_school_id()."','".$student_id."','".$date."','".$course_period[1]['COURSE_ID']."','".$course_period[1]['COURSE_CREDIT_TITLE']."','".$course_period[1]['COURSE_SECTION_ID']."','".$course_period[1]['MP']."','".$course_period[1]['SCHOOL_TERM_ID']."');");
                        } else {
                        	 $enroll_courses[] =  $course_period['COURSE_ID']; 
                        	 db_execute("INSERT INTO STUDENT_SCHEDULE_TEMPORARY (ID,SCHOOL_YEAR,SCHOOL_ID,STUDENT_ID,START_DATE,COURSE_ID,COURSE_CREDIT_TITLE,COURSE_SECTION_ID,MP,SCHOOL_TERM_ID) values(".db_seq_nextval('STUDENT_SCHEDULE_SEQ').",'".get_school_year()."','".get_school_id()."','".$student_id."','".$date."','".$course_period['COURSE_ID']."','".$course_period['COURSE_CREDIT_TITLE']."','".$course_period['COURSE_SECTION_ID']."','".$course_period['MP']."','".$course_period['SCHOOL_TERM_ID']."');");
		
                        }  
                  	 // rakesh modified query with conditions  : End 
                  	 // 
                 // echo "INSERT INTO STUDENT_SCHEDULE_TEMPORARY (ID,SCHOOL_YEAR,SCHOOL_ID,STUDENT_ID,START_DATE,COURSE_ID,COURSE_CREDIT_TITLE,COURSE_SECTION_ID,MP,SCHOOL_TERM_ID) values(".db_seq_nextval('STUDENT_SCHEDULE_SEQ').",'".get_school_year()."','".get_school_id()."','".$student_id."','".$date."','".$course_period['COURSE_ID']."','".$course_period['COURSE_CREDIT_TITLE']."','".$course_period['COURSE_SECTION_ID']."','".$course_period['MP']."','".$course_period['SCHOOL_TERM_ID']."');";die; 
        			
                    	if($course_period['COURSE_SECTION_ID']==$course_period['PARENT_ID'])
								$scount++;
					}
				}
			}
		}
//echo "userid is ".$enrollment_Iomad['user_id']; die;
/*
		$defaults_array = db_request(db_execute("SELECT cp.DAYS, cp.CFIELD_25, c.CFIELD_2, cp.CFIELD_3 FROM STUDENT_SCHEDULE INNER JOIN COURSE_SECTIONS cp ON (STUDENT_SCHEDULE.COURSE_SECTION_ID=cp.COURSE_SECTION_ID) INNER JOIN COURSES c ON (STUDENT_SCHEDULE.COURSE_ID=c.COURSE_ID) WHERE STUDENT_SCHEDULE.ID='".db_seq_currval('STUDENT_SCHEDULE_SEQ')."'"));
		if(count($defaults_array))
		{
			db_execute("UPDATE STUDENT_SCHEDULE SET DAYS = '".$defaults_array[1]["DAYS"]."', CFIELD_25='".$defaults_array[1]["CFIELD_25"]."',CFIELD_5='".$defaults_array[1]["CFIELD_2"]."',CFIELD_10='".$defaults_array[1]["CFIELD_3"]."' WHERE STUDENT_SCHEDULE.ID='".db_seq_currval('STUDENT_SCHEDULE_SEQ')."'");
		}
*/		
    	/*++++++++++++++++++++   rakesh approaval api :Start  ++++++++++++++++++++++++=+++*/
    	//echo "<pre>";print_r($enroll_courses);die;
      $enroll_student = $_REQUEST['student_id'];
      $enrolStudent_query = db_request(db_execute("Select * from students Where STUDENT_ID='".$enroll_student."'"));
      $enroll_student_Data = pg_fetch_all(pg_query($iomadDBconn, "Select * from mdl_user where username='".$enrolStudent_query[1]['USERNAME']."'"));
      $form2_data =   db_request(db_execute("select * from form2 where id='9'"));
      //echo "<pre>"; print_r($enrolStudent_query);die;
    		//check user existence in moodle
      if(empty($enroll_student_Data)){
      		$courseData_Iomad['domain'] = $form2_data[1]['URL'] ;
      		$courseData_Iomad['token'] = $form2_data[1]['TOKEN'] ;   
      		$courseData_Iomad['function'] = "core_user_create_users"; 
      		$courseData_Iomad['idnumber'] = $enrolStudent_query[1]['STUDENT_ID'];
      		$courseData_Iomad['USERNAME'] = $enrolStudent_query[1]['USERNAME'];
      		$courseData_Iomad['PASSWORD'] = $enrolStudent_query[1]['PASSWORD'];
      		$courseData_Iomad['FIRST_NAME'] = $enrolStudent_query[1]['FIRST_NAME'];
      		$courseData_Iomad['MIDDLE_NAME'] = (empty($enrolStudent_query[1]['MIDDLE_NAME']))?'Middle_Name':$enrolStudent_query[1]['MIDDLE_NAME'];
      		$courseData_Iomad['LAST_NAME'] = $enrolStudent_query[1]['LAST_NAME'];
      		$courseData_Iomad['EMAIL'] = $enrolStudent_query[1]['CFIELD_2'];
      			// create student in moodle
      		include($staticpath.'iomadAPI/client.php');
      }
    
      $form2_data =   db_request(db_execute("select * from form2 where id='9'"));
      $enrollment_Iomad = array();
      $enrollment_Iomad['domain'] = $form2_data[1]['URL'] ;
      $enrollment_Iomad['token'] = $form2_data[1]['TOKEN'] ;   
      $enrollment_Iomad['function'] = "enrol_manual_enrol_users"; 
      $enrollment_Iomad['user_id'] = $enroll_student_Data[0]['id']; 
      $enrollment_Iomad['role_id'] = 5; 
   // echo "<pre>";print_r($enrollment_Iomad);die;
      foreach ($enroll_courses as $course_id){
       		//echo "user id ".$enrollment_Iomad['user_id']. $course_id."<br>"; continue;
      		$checkIomadCourse_Query = pg_query($iomadDBconn, "SELECT * FROM mdl_course WHERE idnumber='".$course_id."'");
			$checkIomadCourse_Data = pg_fetch_all($checkIomadCourse_Query)[0];
      		if(empty($checkIomadCourse_Data)){
            	die("SORRY! course doesn't exist in moodle for idnumber ".$course_id."<br><br> PLEASE UPDATE REQUESTED COURSE FIRST.....");
            } else {
            
      			$enrollment_Iomad['course_id'] = $checkIomadCourse_Data['id'];
            	include($staticpath.'iomadAPI/enroll.php');
            }
      		 
      }
    //die('jejejej');
     // echo "<pre>";print_r($enrollment_Iomad);die;
	/*++++++++++++++++++++   rakesh approaval api :End  ++++++++++++++++++++++++=+++*/
    //die('testinggggg');
	db_execute("INSERT INTO STUDENT_SCHEDULE SELECT * FROM STUDENT_SCHEDULE_TEMPORARY ORDER BY STUDENT_ID,COURSE_ID,COURSE_CREDIT_TITLE,COURSE_SECTION_ID");
	  db_execute("DROP TABLE STUDENT_SCHEDULE_TEMPORARY");
    db_execute("DELETE FROM STUDENT_SCHEDULE_REQUESTS WHERE student_id='".$_REQUEST['student_id']."' ");   // added by rakesh
    // echo "<pre>";print_r($_REQUEST);die;
    //var_dump($schedule_query );
    //echo "<br>";
  //  echo "<pre>";print_r($schedule_query );die;

		$current_array = db_request(db_execute("SELECT COURSE_SECTION_ID,FILLED_SEATS,TITLE FROM COURSE_SECTIONS WHERE SCHOOL_YEAR='".get_school_year()."'"),null,array('COURSE_SECTION_ID'));
		$addition = array(
				'SELECT_ONLY'=>'COUNT(*) AS COUNT,s2.COURSE_SECTION_ID',
				'FROM'=>',STUDENT_SCHEDULE s2',
				'WHERE'=>" AND s2.STUDENT_ID=ssm.STUDENT_ID AND s2.SCHOOL_YEAR=ssm.SCHOOL_YEAR AND (s2.END_DATE IS NULL OR s2.END_DATE<'".get_db_date('postgres')."')",
				'GROUP'=>' s2.COURSE_SECTION_ID',
			);
			$scheduled_array = get_student_list($addition);
	
		$count = 0;
		foreach($scheduled_array as $section)
		{
			if($section['COUNT']!=$current_array[$section['COURSE_SECTION_ID']][1]['FILLED_SEATS'])
			{
				db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS='".$section['COUNT']."' WHERE COURSE_SECTION_ID='".$section['COURSE_SECTION_ID']."'");
				$count++;
			}
		}

		echo '<!-- Schedule Count() '.$scount.'-->';
		foreach($cp_parent_array as $parent_id=>$course_period)
		{
			$course_period = $course_period[1];
			db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=TOTAL_SEATS-'".$course_period['AVAILABLE_SEATS']."' WHERE PARENT_ID='".$parent_id."'");
		}
		db_execute("COMMIT");
	}
	else
	{
		foreach($schedule as $student_id=>$periods)
		{
			foreach($periods as $course_sections)
			{
				foreach($course_sections as $school_period_id=>$course_period)
				{
					//if(!$locked_array[$student_id][$course_period['REQUEST_ID']])
					if($course_period['COURSE_SECTION_ID']==$course_period['PARENT_ID'])
						$scount++;
				}
			}
		}
	}
	
	if($_REQUEST['test_mode']!='Y' || $_REQUEST['delete']=='Y')
	{
		echo '<script language="javascript">'."\r";
		echo 'addHTML("<IMG SRC=images/spinning.gif> '._('Optimizing').' ... ","percentDIV",true);'."\r";
		echo '</script>';
		echo str_pad(' ',4096);
		ob_flush();
		flush();
	}
	$_REQUEST['previous_test_mode'] = $_REQUEST['test_mode'];
	$_REQUEST['test_mode']='Y';
	unset($_REQUEST['delete']);

	if ($failed_to_schedule) {
		foreach($failed_to_schedule as $request_id=>$true)
		{
			if($true==true)
			{
				$failed_students[$requests_array[$request_id][1]['STUDENT_ID']]++;
				$failed_courses[$requests_array[$request_id][1]['COURSE_ID'].'-'.$requests_array[$request_id][1]['COURSE_CREDIT_TITLE']]++;
			}
		}
		if(count($failed_students) && !$_REQUEST['student_id'])
		{
			echo '<TABLE width=100%><TR><TD width=50% valign=top>';
			foreach($failed_students as $student_id=>$count)
			{
				if($student_id>0)
					$students_list .= ','.$student_id;
			}
			$students_list = substr($students_list,1);
			$students_array = db_request(db_execute("SELECT LAST_NAME".CCAT."', '".CCAT."FIRST_NAME AS FULL_NAME,STUDENT_ID,NULL AS COUNT FROM STUDENTS WHERE STUDENT_ID IN (".$students_list.")"),array('COUNT'=>'_makeCount'));
			$link = array('FULL_NAME'=>array('link'=>'modloader.php?servicemod=mod_curriculum/Curriculum.php&useontop=false','variables'=>array('student_id'=>'STUDENT_ID'),'js'=>true));
			Gridoutput($students_array,array('FULL_NAME'=>_('Student Name'),'STUDENT_ID'=>_('ID number'),'COUNT'=>_('Unfilled Requests')),_('Student with Unfilled Requests'),_('Students with Unfilled Requests'),$link,null,array('xscroll'=>false,'save'=>false,'search'=>false));
			echo '</TD><TD width=50% valign=top>';
			$courses_array = array();
			$courses_array[0] = '';
			$course_names_array = db_request(db_execute("SELECT SUBJECT_ID,TITLE,SHORT_NAME,COURSE_ID FROM COURSES WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."'"),array(),array('COURSE_ID'));
			foreach($failed_courses as $course=>$count)
			{
				$course_credits = substr($course,(strpos($course,'-')+1));
				$course_id = substr($course,0,strpos($course,'-'));
				if($course_names_array[$course_id])
					$courses_array[] = array('TITLE'=>$course_names_array[$course_id][1]['TITLE'],'SHORT_NAME'=>$course_names_array[$course_id][1]['SHORT_NAME'],'COUNT'=>$count,'COURSE_ID'=>$course_id,'COURSE_CREDIT_TITLE'=>$course_credits,'SUBJECT_ID'=>$course_names_array[$course_id][1]['SUBJECT_ID']);
				// .' - '.$course_credits
			}
			unset($courses_array[0]);
			$link['TITLE']['link'] = 'modloader.php?servicemod=mod_curriculum/ScdStudSchedReport.php&servicefunction=course_sections&useontop=false';
			$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID','course_id'=>'COURSE_ID','course_credits'=>'COURSE_CREDIT_TITLE');
			$link['TITLE']['js'] = true;

			Gridoutput($courses_array,array('TITLE'=>_('Course'),'SHORT_NAME'=>_('Course Number'),'COUNT'=>_('Unfilled Requests')),_('Course with Unfilled Requests'),_('Courses with Unfilled Requests'),$link,null,array('xscroll'=>false,'save'=>false,'search'=>false));
			echo '</TD></TR></TABLE>';
		}
		elseif(!$_REQUEST['student_id'])
		echo _('All Students have been scheduled completely.');
	}
	if($_REQUEST['previous_test_mode']!='Y')
	{
		if(!$_REQUEST['student_id'])
		{
			if($DBType!='mssql')
			{
				db_execute("VACUUM");
				db_execute("ANALYZE");
			}
			$addition['link']['FULL_NAME'] = false;
			$_REQUEST['servicemod'] = 'mod_curriculum/ScdReqUnActList.php';
			$_REQUEST['search_servicefunction']='list';
			include('modules/mod_curriculum/ScdReqUnActList.php');
		}
	}

	if($_REQUEST['student_id']){
		$str = sprintf(_('Finished in ').'%d'._(' minutes ').'%d'._(' seconds.').'<BR>%s'._(' of ').'%d'._(' requests filled.'),date('i',time()-$start_time),date('s',time()-$start_time),Percent($scount/$requests_count),($requests_count));
	}
	elseif(count($schedule) > 0 && $requests_count > 0){
		$str = sprintf(_('Finished in ').'%d'._(' minutes ').'%d'._(' seconds.').'<BR>%s'._(' of ').'%d'._(' requests filled.').'<BR>%d'._(' students completely scheduled.'),date('i',time()-$start_time),date('s',time()-$start_time),Percent($scount/$requests_count),($requests_count),((count($schedule)-count($failed_students))/count($schedule)));
	}
	
	echo '<script language="javascript">'."\r";
	echo 'addHTML("<IMG SRC=images/check.gif width=15> <B>'.$str.'</B>","percentDIV",true);'."\r";
	echo '</script>';
	ob_end_flush();
}
//die('hiiiiii');
function _scheduleRequest($request,$not_parent_id=false)
{	global $requests_array,$cp_parent_array,$cp_course_array,$mps_array,$schedule,$filled,$unfilled,$failed_to_schedule,$alternates_array;
/*if(count($cp_course_array[$request['COURSE_ID'].'-'.$request['COURSE_CREDIT_TITLE']])){
	die('helleleo');
}die('titititi');  */
	$possible = array();
 	if(is_array($cp_course_array[$request['COURSE_ID'].'-'.$request['COURSE_CREDIT_TITLE']]) && !empty($cp_course_array[$request['COURSE_ID'].'-'.$request['COURSE_CREDIT_TITLE']])){
 	if(count($cp_course_array[$request['COURSE_ID'].'-'.$request['COURSE_CREDIT_TITLE']]))
		{
   // echo "helllo ";
		foreach($cp_course_array[$request['COURSE_ID'].'-'.$request['COURSE_CREDIT_TITLE']] as $course_period)
		{
			foreach($cp_parent_array[$course_period['COURSE_SECTION_ID']] as $slice)
			{
				// ALREADY SCHEDULED HERE
				if($slice['PARENT_ID']==$not_parent_id)
					continue 2;

				// NO SEATS
				if($slice['AVAILABLE_SEATS']<=0)
					continue 2;
				
				// SLICE VIOLATES GENDER RESTRICTION
				if($slice['GENDER_RESTRICTION']!='N' && $slice['GENDER_RESTRICTION']!=substr($request['GENDER'],0,1))
					continue 2;

				// PARENT VIOLATES TEACHER / PERIOD REQUESTS
				if($slice['PARENT_ID']==$slice['COURSE_SECTION_ID'] && (($request['SCHOOL_TERM_ID']!='' && $slice['SCHOOL_TERM_ID']!=$request['SCHOOL_TERM_ID']) || ($request['WITH_TEACHER_ID']!='' && $slice['TEACHER_ID']!=$request['WITH_TEACHER_ID']) || ($request['WITH_SCHOOL_PERIOD_ID'] && $slice['SCHOOL_PERIOD_ID']!=$request['WITH_SCHOOL_PERIOD_ID']) || ($request['NOT_TEACHER_ID'] && $slice['TEACHER_ID']==$request['NOT_TEACHER_ID']) || ($request['NOT_SCHOOL_PERIOD_ID'] && $slice['SCHOOL_PERIOD_ID']==$request['NOT_SCHOOL_PERIOD_ID'])))
					continue 2;
				
				if(count($schedule[$request['STUDENT_ID']][$slice['SCHOOL_PERIOD_ID']]))
				{
					// SHOULD LOOK FOR COMPATIBLE CP's IF NOT THE COMPLETE WEEK/YEAR
					foreach($schedule[$request['STUDENT_ID']][$slice['SCHOOL_PERIOD_ID']] as $existing_slice)
					{						
						if($existing_slice['PARENT_ID']!=$not_parent_id && _isConflict($existing_slice,$slice))
							continue 3;
					}
				}
			}
			// No conflict
			$possible[] = $course_period;
		}
	}
	}
	if(count($possible))
	{
		// IF THIS COURSE IS BEING SCHEDULED A SECOND TIME, DELETE THE ORIGINAL ONE
		if($not_parent_id)
		{
			foreach($cp_parent_array[$not_parent_id] as $key=>$slice)
			{
				foreach($schedule[$request['STUDENT_ID']][$slice['SCHOOL_PERIOD_ID']] as $key2=>$item)
				{
					if($item['COURSE_SECTION_ID']==$slice['COURSE_SECTION_ID'])
					{
						$filled[$schedule[$request['STUDENT_ID']][$slice['SCHOOL_PERIOD_ID']][$key2]['REQUEST_ID']] = false;
						unset($schedule[$request['STUDENT_ID']][$slice['SCHOOL_PERIOD_ID']][$key2]);
						$cp_parent_array[$not_parent_id][$key]['AVAILABLE_SEATS']++;
					}
				}
			}
		}
		
		// CHOOSE THE BEST CP
		_scheduleBest($request,$possible);
		return true;
	}
	else
	{
		if($request['REQUEST_ID']) // (!$request['PRIORITY'] || $request['PRIORITY']==1)
			$failed_to_schedule[$request['REQUEST_ID']] = true;
		return false; // if this point is reached, the request could not be scheduled
	}
}

function _moveRequest($request,$not_request=false,$not_parent_id=false)
{	global $requests_array,$cp_parent_array,$cp_course_array,$mps_array,$schedule,$filled,$unfilled,$alternates_array;

	if(!$not_request && !is_array($not_request))
		$not_request = array();
 	if(is_array($cp_course_array[$request['COURSE_ID'].'-'.$request['COURSE_CREDIT_TITLE']]) && !empty($cp_course_array[$request['COURSE_ID'].'-'.$request['COURSE_CREDIT_TITLE']])){
		if(count($cp_course_array[$request['COURSE_ID'].'-'.$request['COURSE_CREDIT_TITLE']]))
		{
		foreach($cp_course_array[$request['COURSE_ID'].'-'.$request['COURSE_CREDIT_TITLE']] as $course_period)
		{
			// CLEAR OUT A SLOT FOR EACH $slice
			foreach($cp_parent_array[$course_period['PARENT_ID']] as $slice)
			{
				/* Don't bother to move courses around if request can't be scheduled here anyway. */
				// SEAT COUNTS
				if($slice['AVAILABLE_SEATS']<=0)
					continue 2;
				
				// SLICE VIOLATES GENDER RESTRICTION
				if($slice['GENDER_RESTRICTION']!='N' && $slice['GENDER_RESTRICTION']!=substr($request['GENDER'],0,1))
					continue 2;

				// PARENT VIOLATES TEACHER / PERIOD REQUESTS
				if($slice['PARENT_ID']==$slice['COURSE_SECTION_ID'] && (($request['SCHOOL_TERM_ID']!='' && $slice['SCHOOL_TERM_ID']!=$request['SCHOOL_TERM_ID']) || ($request['WITH_TEACHER_ID']!='' && $slice['TEACHER_ID']!=$request['WITH_TEACHER_ID']) || ($request['WITH_SCHOOL_PERIOD_ID'] && $slice['SCHOOL_PERIOD_ID']!=$request['WITH_SCHOOL_PERIOD_ID']) || ($request['NOT_TEACHER_ID'] && $slice['TEACHER_ID']==$request['NOT_TEACHER_ID']) || ($request['NOT_SCHOOL_PERIOD_ID'] && $slice['SCHOOL_PERIOD_ID']==$request['NOT_SCHOOL_PERIOD_ID'])))
					continue 2;

				if(count($schedule[$request['STUDENT_ID']][$slice['SCHOOL_PERIOD_ID']]))
				{
					foreach($schedule[$request['STUDENT_ID']][$slice['SCHOOL_PERIOD_ID']] as $existing_slice)
					{
						if(in_array($existing_slice['REQUEST_ID'],$not_request))
							continue 3;
						
						if(true)
						{
							$not_request_temp = $not_request;
							$not_request_temp[] = $existing_slice['REQUEST_ID'];
							if(!$scheduled = _scheduleRequest($requests_array[$existing_slice['REQUEST_ID']][1],$existing_slice['PARENT_ID']))
							{
								if(!$moved = _moveRequest($requests_array[$existing_slice['REQUEST_ID']][1],$not_request_temp,$existing_slice['PARENT_ID']))
									continue 3;
							}
						}
					}
				}
				else
				{
					// why is it empty?
				}
			}
			if(_scheduleRequest($request,$not_parent_id))
				return true;
		}		
	}
	}
	
	return false; // if this point is reached, the request could not be scheduled
}

function _isConflict($existing_slice,$slice)
{	global $requests_array,$cp_parent_array,$cp_course_array,$mps_array,$schedule,$filled,$unfilled;
	
	 $mp_conflict = $days_conflict = false;
	// LOOK FOR CONFLICT IN SCHEDULED SLICE -- CONFLICT == SEATS,MP,DAYS,PERIOD TIMES

	// school term CONFLICTS
	if($existing_slice['SCHOOL_TERM_ID']=='0' || ($slice['SCHOOL_TERM_ID']=='0' && (!$request['SCHOOL_TERM_ID'] || $request['SCHOOL_TERM_ID']==$slice['SCHOOL_TERM_ID'])))
		$mp_conflict = true; // if either course is full year
	elseif($existing_slice['SCHOOL_TERM_ID']==$slice['SCHOOL_TERM_ID'])
		$mp_conflict = true; // if both fall in the same QTR or SEM
	elseif($existing_slice['MP']==$slice['MP'])
		$mp_conflict = false; // both are SEM's or QTR's, but not the same
	elseif($existing_slice['MP']=='SEM' && $mps_array[$existing_slice['SCHOOL_TERM_ID']][$slice['SCHOOL_TERM_ID']])
		$mp_conflict = true; // the new course is a quarter in the existing semester
	elseif($mps_array[$slice['SCHOOL_TERM_ID']][$existing_slice['SCHOOL_TERM_ID']])
		$mp_conflict = true; // the existing course is a quarter in the new semester
	else
		$mp_conflict = false; // not the same MP, but no conflict
	
	if($mp_conflict) // only look for a day conflict if there's already an MP conflict
	{
		if(strlen($slice['DAYS'])+strlen($existing_slice['DAYS'])>21)
			$days_conflict = true;
		else
		{
			$days_len = strlen($slice['DAYS']);
			for($i=0;$i<$days_len;$i=+3)
			{
				if(strpos($existing_slice['DAYS'],substr($slice['DAYS'],$i,3))!==false)
				{
					$days_conflict = true;
					break;
				}
			}
		}
		if($days_conflict)
			return true; // Go to the next available section
	}

	return false; // There is no conflict
}

function _scheduleBest($request,$possible)
{	global $cp_parent_array,$schedule,$filled,$failed_to_schedule;

	$best = $possible[0];
	if(count($possible)>1)
	{
		foreach($possible as $course_period)
		{
			if($cp_parent_array[$course_period['COURSE_SECTION_ID']][1]['AVAILABLE_SEATS']>$cp_parent_array[$best['COURSE_SECTION_ID']][1]['AVAILABLE_SEATS'])
				$best = $course_period;
		}
	}
	foreach($cp_parent_array[$best['COURSE_SECTION_ID']] as $key=>$slice)
	{
		$schedule[$request['STUDENT_ID']][$slice['SCHOOL_PERIOD_ID']][] = $slice + array('REQUEST_ID'=>$request['REQUEST_ID']);
		$cp_parent_array[$best['COURSE_SECTION_ID']][$key]['AVAILABLE_SEATS']--;
	}
	unset($failed_to_schedule[$request['REQUEST_ID']]);
}

function _scheduleAlt($alt_request)
{	global $requests_array,$cp_parent_array,$cp_course_array,$mps_array,$schedule,$filled,$unfilled,$failed_to_schedule,$alternates_array,$locked_array;

	$scheduled = _scheduleRequest($alt_request[1]);
	if(!$scheduled)
	{
		unset($failed_to_schedule[$alt_request[1]['PRIORITY']]);

		$not_request = array();
		foreach($locked_array[$request[1]['STUDENT_ID']] as $request_id=>$requests)
			$not_request[] = $request_id;

		$moved = _moveRequest($alt_request[1],$not_request);
		unset($failed_to_schedule[$alt_request[1]['REQUEST_ID']]);
		unset($failed_to_schedule[$alt_request[1]['PRIORITY']]);
		
		if(!$moved)
		{
			if($alternates_array[$alt_request[1]])
				$alt_scheduled = _scheduleAlt($alternates_array[$alt_request[1]]);
			
			if($alt_scheduled)
			{
				unset($failed_to_schedule[$alt_request[1]['PRIORITY']]);
				unset($failed_to_schedule[$alt_request[1]['REQUEST_ID']]);
			}

			return $alt_scheduled;
		}
		else
		{
			$filled[$alt_request[1]['PRIORITY']] = true;
			unset($failed_to_schedule[$alt_request[1]['PRIORITY']]);
			return true;
		}
	}
	else
	{
		$filled[$alt_request[1]['PRIORITY']] = true;
		unset($failed_to_schedule[$alt_request[1]['PRIORITY']]);
		return true;
	}
}

function _returnTrue($arg1,$arg2='',$arg3='')
{
	return true;
}

function _makeCount($value,$column)
{	global $THIS_array,$failed_students;

	return $failed_students[$THIS_array['STUDENT_ID']];
}
?>