<?php
include_once($staticpath."/classes/Button.php");
$button = new Button();
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;
//echo "<pre>";print_r($_REQUEST);die;
echo GetBaseJavaFunc();
//echo "<pre>";print_r($_REQUEST);die;
//die('aaaaa');
unset($_SESSION['_REQUEST_vars']['subject_id']);unset($_SESSION['_REQUEST_vars']['course_id']);unset($_SESSION['_REQUEST_vars']['course_credits']);unset($_SESSION['_REQUEST_vars']['course_section_id']);

$display_additional_info = '';
$columns_to_update = $_SYSTEM['config']['SCHEDULE_UPDATE_COURSE'];


$date = get_db_date();
$user = get_user('USER_ID');
$last_updated_sql = "LAST_UPDATED_DATE='{$date}',LAST_UPDATED_USER='{$user}',";
$last_updated_ins_fields = ",LAST_UPDATED_DATE,LAST_UPDATED_USER";
$last_updated_ins_values = ",'{$date}','{$user}'";
// if only one course weight, auto-select it ... this is for choosing a parent
if(($_REQUEST['servicemod']=='mod_curriculum/ScdCourseProperties.php' || ($_REQUEST['servicemod']=='mod_evaluation/BncCourseProperties.php' && SystemPreferences('WEIGHTS')!=='Y')) && ($_REQUEST['servicefunction']=='choose_course' || SystemPreferences('WEIGHTS')!=='Y') && ($_REQUEST['course_id'] && $_REQUEST['course_id']!='new'))
     {   //die('hellloeeo');
	$weights_array = db_request(db_execute("SELECT COURSE_CREDIT_TITLE FROM COURSE_CREDITS WHERE COURSE_ID='$_REQUEST[course_id]'"));
//print_r($weights_array);die;


	if(count($weights_array)==1)
		$_REQUEST['course_credits'] = $weights_array[1]['COURSE_CREDIT_TITLE'];
	else
	    $_REQUEST['course_credits'] = '1';


     }
//die('dffgdhgfhfgj');

if($_REQUEST['servicefunction']!='delete' && !$_REQUEST['subject_id'])
     {   //die('test');
	
$subjects_array = db_request(db_execute("SELECT SUBJECT_ID,TITLE FROM COURSE_SUBJECTS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."'"));


if(count($subjects_array)==1)
		$_REQUEST['subject_id'] = $subjects_array[1]['SUBJECT_ID'];

     }

$affects_gpa_changed = false;
$credits_changed = false;

$new_course_fields = array('CREDITS','STUDENT_SCHEDULEABLE','STUDENT_REQUESTABLE','DOES_GPA_1','DOES_GPA_2','DOES_GPA_3','DOES_GPA_4','DOES_GPA_5','CW_CHECKBOX_SETTING_1','CW_CHECKBOX_SETTING_2','CW_CHECKBOX_SETTING_3','CW_CHECKBOX_SETTING_4','CW_CHECKBOX_SETTING_5');

if($_REQUEST['tables'] && $_POST['tables'] && AllowEdit())
{    //die('testtttiii'); 

	$where = array('COURSE_SUBJECTS'=>'SUBJECT_ID',
					'COURSES'=>'COURSE_ID',
					'COURSE_CREDITS'=>"COURSE_ID='".$_REQUEST['course_id']."' AND COURSE_CREDIT_TITLE",
					'COURSE_SECTIONS'=>'COURSE_SECTION_ID');


	if($_REQUEST['tables']['parent_id'])
		$_REQUEST['tables']['COURSE_SECTIONS'][$_REQUEST['course_section_id']]['PARENT_ID'] = $_REQUEST['tables']['parent_id'];
	if(SystemPreferences('USE_CREDITS')!='Y')
		$_REQUEST['tables']['COURSE_CREDITS']['new_course']['CREDITS'] = '1';
	if($_REQUEST['tables']['COURSE_CREDITS']['new_course'])
	{
		foreach($new_course_fields as $new_course_field)
		{
        
			if(isset($_REQUEST['tables']['COURSE_CREDITS']['new_course'][$new_course_field]))
				$new_course_data[$new_course_field] = $_REQUEST['tables']['COURSE_CREDITS']['new_course'][$new_course_field];
		}
		unset($_REQUEST['tables']['COURSE_CREDITS']);
	}
//echo "<pre>"; print_r($_REQUEST['tables']);die;
//die('sdgfhjbj');
$column=array();

	foreach($_REQUEST['tables'] as $table_name=>$tables)
	{
    //print_r($tables);
    
		foreach($tables as $id=>$columns)
        {
      //  print_r($columns);die;
        
			if($columns['TOTAL_SEATS'] && !is_numeric($columns['TOTAL_SEATS']))
				$columns['TOTAL_SEATS'] = ereg_replace('[^0-9]+','',$columns['TOTAL_SEATS']);
			if($columns['DAYS'])
			{
				foreach($columns['DAYS'] as $day=>$y)
				{
					if($y=='Y')
						$days .= $day;
				}
				$columns['DAYS'] = $days;
			}
        

			if($id!='new')
			{

				if($table_name=='COURSES' && $columns['SUBJECT_ID'] && $columns['SUBJECT_ID']!=$_REQUEST['subject_id'])
					$_REQUEST['subject_id'] = $columns['SUBJECT_ID'];
//die('ghvbhvhbgvhg');
            
				$sql = "UPDATE $table_name SET ";
           // print_r($sql);
            
				if($table_name=='COURSE_SECTIONS' && $id!='MERGE_ID')
				{
                    //die('llllllll');
					$current = db_request(db_execute("SELECT TEACHER_ID,SCHOOL_PERIOD_ID,SCHOOL_TERM_ID,DAYS,SHORT_NAME,DOES_GPA,WEEK FROM COURSE_SECTIONS WHERE ".$where[$table_name]."='$id'"));

                    
                
					if(isset($columns['DOES_GPA']) && $columns['DOES_GPA']!=$current[1]['DOES_GPA'])
					{
						if($columns['DOES_GPA']=='Y')
							$affects_gpa_changed = _('affect GPA');
						else
							$affects_gpa_changed = _('not affect GPA');
					}

                  //  print_r($columns['TEACHER_ID']);
					if($columns['TEACHER_ID'])
						$user_id = $columns['TEACHER_ID'];
					else
						$user_id = $current[1]['TEACHER_ID'];

					if($columns['SCHOOL_PERIOD_ID'])
						$school_period_id = $columns['SCHOOL_PERIOD_ID'];
					else
						$school_period_id = $current[1]['SCHOOL_PERIOD_ID'];
					if(isset($columns['SCHOOL_TERM_ID']))
						$school_term_id = $columns['SCHOOL_TERM_ID'];
					else
						$school_term_id = $current[1]['SCHOOL_TERM_ID'];
					if($columns['DAYS'])
						$days = $columns['DAYS'];
					else
						$days = $current[1]['DAYS'];
					if($columns['WEEK'])
					{
						$useweek = $columns['WEEK'];
						$week = $_SESSION['week_options'][$useweek];
						$columns['WEEK'] = $week;
					}
					else
					{
						$week = get_week($current[1]['WEEK']);
					}
					if($columns['SHORT_NAME'])
						$short_name = $columns['SHORT_NAME'];
					else
						$short_name = $current[1]['SHORT_NAME'];

					$teacher = db_request(db_execute("SELECT FIRST_NAME,LAST_NAME,MIDDLE_NAME FROM USERS WHERE USER_ID='$user_id'"));
                
//print_r($user_id); 
                //print_r($teacher);die('vvvvv');
					$period = db_request(db_execute("SELECT TITLE FROM SCHOOL_PERIODS WHERE SCHOOL_PERIOD_ID='$school_period_id' AND SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."'"));
				
                
      
                if($school_term_id!='0')
						$mp_title = get_school_term($school_term_id,'SHORT_NAME').' - ';
					if(strlen($days)<35)//the digit control length of line where days are showed
						$mp_title .= $days.' - ';
	                        	if(SystemPreferences('ODD_EVEN_WEEKS','system')=='Y')
			                {
			                	if($columns['WEEK'])
			                	{
							$soptions = array('A'=>_('Each'),'E'=>_('Even'),'O'=>_('Odd'));
							$sweek = $soptions[$week];
			                                $mp_title .= $sweek.' - ';
			                        }
			                        elseif($week)
			                    		$mp_title .= $week.' - ';
			                }

					if($short_name)
						$mp_title .= $short_name.' - ';

					$title = str_replace("'","''",$period[1]['TITLE'].' - '.$mp_title.$teacher[1]['FIRST_NAME'].' '.$teacher[1]['MIDDLE_NAME'].' '.$teacher[1]['LAST_NAME']);
					$sql .= "TITLE='$title',";

					if(isset($columns['SCHOOL_TERM_ID']))
					{
						if($columns['SCHOOL_TERM_ID']=='0')
							$columns['MP'] = 'FY';
						elseif(get_school_term($columns['SCHOOL_TERM_ID'],'MP_TABLE')=='SCHOOL_SEMESTERS')
							$columns['MP'] = 'SEM';
						else
							$columns['MP'] = 'QTR';
					}
				}
            
            
            
       		elseif($table_name=='COURSE_CREDITS')
				{
                 //die('kkkkkkkk');
	$current = db_request(db_execute("SELECT CREDITS FROM COURSE_CREDITS WHERE COURSE_ID='".$_REQUEST['course_id']."' AND ".$where[$table_name]."='$id'"));
	
                //print_r($current);die;
                
                if(isset($columns['CREDITS']) && $columns['CREDITS']!=$current[1]['CREDITS'])
                
					{
						$credits_changed = $columns['CREDITS'];
					}

                

					if(isset($columns['COURSE_CREDIT_TITLE']))
						$columns['COURSE_CREDIT_TITLE'] = str_replace(' ','_',$columns['COURSE_CREDIT_TITLE']);
				}
            //die('jjjjjjj');
				if($id=='MERGE_ID')
				{
					//die('kkkkkkkk');
                	$ms_cur = db_request(db_execute("SELECT MERGE_ID,COURSE_SECTION_ID,COURSE_ID FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='".$_REQUEST['course_section_id']."'"));

                
           
					if($ms_cur[1]['MERGE_ID'])
					{
						$merge_line = $ms_cur[1]['MERGE_ID'].',';
						$ms_cur_array = explode(",",$ms_cur[1]['MERGE_ID']);
						$orig_merge_line = $ms_cur[1]['MERGE_ID'].',';
					}
					else
					{
						unset($ms_cur_array);
						unset($merge_line);
						unset($orig_merge_line);
					}
					if(!$ms_single_array) $ms_single_array = array();
					$hms = $_REQUEST['hidden_merge_single'];
					foreach($columns as $count=>$merge_id)
					{

						if($hms[$count]=='Y')
						{

						    $ms_linked = db_request(db_execute("SELECT MERGE_ID,COURSE_SECTION_ID,COURSE_ID FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='".$merge_id."'"));

						    if($ms_linked[1]['MERGE_ID'])
						    {
							    $merge_line .= $ms_linked[1]['MERGE_ID'].',';
							    $ms_linked_array = explode(",",$ms_linked[1]['MERGE_ID']);

						    }
						    else
							    $merge_line .= $merge_id.',';
						}
						else
						{
						        $merge_line .= $merge_id.',';
							$ms_single_array[] = $merge_id;
						}

	    		
						
					}

					if(!$ms_cur[1]['MERGE_ID'])
					{
						$merge_line .= $_REQUEST['course_section_id'];
					}
					else
						$merge_line = substr($merge_line,0,strlen($merge_line)-1);

					$ms_sections = explode(",",$merge_line);
					unset($merge_line);
					$ms_sections = array_unique($ms_sections);
					foreach($ms_sections as $merge_id)
					{
						$merge_line .= $merge_id.',';
					}

					$merge_line = substr($merge_line,0,strlen($merge_line)-1);


					foreach($ms_sections as $merge_id)
					{

						if(!in_array($merge_id,$ms_single_array))
						{

							$ms_sql = "UPDATE COURSE_SECTIONS SET MERGE_ID='".$merge_line."' WHERE COURSE_SECTION_ID='".$merge_id."'";

                        
							db_execute($ms_sql);
						}

			
					}

					unset($ms_single_array);
					unset($table['MERGE_ID']);
					unset($_REQUEST['hidden_merge_single']);
				}
           // die('uuuuu');
				if($id!='MERGE_ID')
		                foreach($columns as $column=>$value)
		                {
                       // die('ffff');
                      //  print_r($column);
		                        $sql .= $column."='".str_replace("\'","''",$value)."',";
//echo $sql;die;
                        //print_r($value);
		                        if($columns_to_update && count($columns_to_update))
		                        {
			                      
                                if(array_key_exists($column, $columns_to_update) && $value != $current[1][$column])
			                        {
			                                db_execute("UPDATE STUDENT_SCHEDULE SET {$column}='{$value}' WHERE COURSE_SECTION_ID='{$id}' AND {$column}='".$current[1][$column]."'");
			                                $has_changes[$column] = $current[1][$column];
			                        }
		                        }
		                }
				if($id!='MERGE_ID')
				{

					$sql = substr($sql,0,-1)." WHERE ".$where[$table_name]."='$id'";
              // print_r($sql);die;
					db_execute($sql);
               // print_r($sql);
                 $var = $_POST['schoolallow']; 
                if(isset($var)) { 
                $schoolallow='Y';
                } 
                else{
                $schoolallow='N';
                }
                
                $update=db_execute("UPDATE COURSE_SUBJECTS SET CATEGORY_VISIBLE='".$schoolallow."' WHERE SUBJECT_ID='$id'");
               // print_r($update);die;
				}
            
  
               // die('rrrrrr');
      
				if($table_name=='COURSE_CREDITS' && isset($columns['COURSE_CREDIT_TITLE']))
				{
				
                         
                db_execute("UPDATE COURSE_SECTIONS SET COURSE_CREDIT_TITLE='".$columns['COURSE_CREDIT_TITLE']."' WHERE COURSE_ID='$_REQUEST[course_id]' AND COURSE_CREDIT_TITLE='$_REQUEST[course_credits]'");
					db_execute("UPDATE STUDENT_SCHEDULE SET COURSE_CREDIT_TITLE='".$columns['COURSE_CREDIT_TITLE']."' WHERE COURSE_ID='$_REQUEST[course_id]' AND COURSE_CREDIT_TITLE='$_REQUEST[course_credits]'");
					db_execute("UPDATE STUDENT_SCHEDULE_REQUESTS SET COURSE_CREDIT_TITLE='".$columns['COURSE_CREDIT_TITLE']."' WHERE COURSE_ID='$_REQUEST[course_id]' AND COURSE_CREDIT_TITLE='$_REQUEST[course_credits]'");

					unset($_REQUEST['course_credits']);
				}
			}
			else
			{
            
            //die('hhhhewww');
	                    if(!isset($columns['SCHOOL_PERIOD_ID']))
		                    $columns['SCHOOL_PERIOD_ID'] = array(1 => null);
            		    if(isset($columns['SCHOOL_PERIOD_ID']) && !is_array($columns['SCHOOL_PERIOD_ID']))
		                    $columns['SCHOOL_PERIOD_ID'] = array(1 => $columns['SCHOOL_PERIOD_ID']);
			    if(is_array($columns['SCHOOL_PERIOD_ID']))
			    {
				    $SCHOOL_PERIOD_ID_array = $columns['SCHOOL_PERIOD_ID'];
				    unset($columns['SCHOOL_PERIOD_ID']);
              		
                //echo "<pre>"; print_r($SCHOOL_PERIOD_ID_array);die;
				    foreach($SCHOOL_PERIOD_ID_array as $n=>$Period)
				    {
                   
                    
					    $columns['SCHOOL_PERIOD_ID'] = $Period;
                   // $user_id = $_REQUEST[];
                   // echo "<pre>"; print_r($_REQUEST);die;
                    
                    $coursesubjectquery=db_request(db_execute("SELECT subject_id  FROM course_subjects where title='".$columns['TITLE']."' "));
                     $coursetitlequery=db_request(db_execute("select title from courses where title='".$columns['TITLE']."'"));
                    if(empty($coursetitlequery)){
                    
                    if(empty($coursesubjectquery)){
                    
		                            $sql = "INSERT INTO $table_name ";
		                            if($table_name=='COURSE_SUBJECTS')
		                            {
                                    
                                      if(isset($_POST['btn_save'])) {
                    
                        $var = $_POST['schoolallow']; 
                   // print_r($var);
                    
                   
    if(isset($var)) { 
    $schoolallow='Y';
         
    } 
                    
                    else{
                    $schoolallow='N';
                    
                    }
                    
}
                                    

			                    //  print_r($schoolallow);die;
			                            $fields = 'SUBJECT_ID,SCHOOL_ID,SCHOOL_YEAR,CATEGORY_VISIBLE,';
                                    //print_r($fields);
                                    
                                    
			                          $values = "".db_seq_nextval('COURSE_SUBJECTS_SEQ').",'".get_school_id()."','".get_school_year()."','$schoolallow',";
                                   // print_r($values);

		                            }
                   
                    
		                            elseif($table_name=='COURSES')
		                            {
                                    	/*
			                            if(isset($_POST['btn_save'])) {
                    
                        $var = $_POST['allow']; 
                   // print_r($var);
                    
                   
    if(isset($var)) { 
    $allow='Y';
         
    } 
                    
                    else{
                    $allow='N';
                    
                    }
                    
}
*/
                                    
			                           // $fields = 'COURSE_ID,SUBJECT_ID,SCHOOL_ID,SCHOOL_YEAR,C_VISIBLE,';
                                     $fields = 'COURSE_ID,SUBJECT_ID,SCHOOL_ID,SCHOOL_YEAR,';
                                    
			                     // $values = "".db_seq_nextval('COURSES_SEQ').",'$_REQUEST[subject_id]','".get_school_id()."','".get_school_year()."','$allow',";
                    				
                                    
                                     $values = "".db_seq_nextval('COURSES_SEQ').",'$_REQUEST[subject_id]','".get_school_id()."','".get_school_year()."',";
                                    
                                    
		                            }
                			       elseif($table_name=='COURSE_CREDITS')
		                            {
			                            $fields = 'SCHOOL_YEAR,SCHOOL_ID,COURSE_ID,';
                                  
			                            $values = "'".get_school_year()."','".get_school_id()."','$_REQUEST[course_id]',";
			                            $columns['COURSE_CREDIT_TITLE'] = str_replace(' ','_',$columns['COURSE_CREDIT_TITLE']);
                    				    $_REQUEST['course_credits'] = $columns['COURSE_CREDIT_TITLE'];
		                            }
		                            elseif($table_name=='COURSE_SECTIONS')
		                            {    
			                           
			                            $fields = 'COURSE_SECTION_ID,SCHOOL_YEAR,SCHOOL_ID,COURSE_ID,COURSE_CREDIT_TITLE,TITLE,FILLED_SEATS,';
						    
                                   
			                            $teacher = db_request(db_execute("SELECT FIRST_NAME,LAST_NAME,MIDDLE_NAME FROM USERS WHERE USER_ID='$columns[TEACHER_ID]'"));
                    				    $period = db_request(db_execute("SELECT TITLE FROM SCHOOL_PERIODS WHERE SCHOOL_PERIOD_ID='$columns[SCHOOL_PERIOD_ID]' AND SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."'"));

			                           
			    			    if(isset($columns['SCHOOL_TERM_ID']))
						    {
							    if($columns['SCHOOL_TERM_ID']=='0')
			    					    $columns['MP'] = 'FY';
							    elseif(get_school_term($columns['SCHOOL_TERM_ID'],'MP_TABLE')=='SCHOOL_SEMESTERS')
			    					    $columns['MP'] = 'SEM';
							    else
							    	    $columns['MP'] = 'QTR';
						    }
					    	    if($columns['WEEK'])
						    {
							    $useweek = $columns['WEEK'];
							    $week = $_SESSION['week_options'][$useweek];
							    $columns['WEEK'] = $week;
						    }
//						
						    if(!isset($columns['TOTAL_SEATS'])) // && strval($columns['TOTAL_SEATS']) > 0)
						    {
							    $columns['TOTAL_SEATS'] = '0';
						    }
			                            if($columns['SCHOOL_TERM_ID']!='0')
		                                    $mp_title = get_school_term($columns['SCHOOL_TERM_ID'],'SHORT_NAME').' - ';
			                            if(strlen($columns['DAYS'])<35)
			                                    $mp_title .= $columns['DAYS'].' - ';
			                            if(SystemPreferences('ODD_EVEN_WEEKS','system')=='Y')
			                            {
			                        	if($columns['WEEK'])
			                        	{
							    $soptions = array('A'=>_('Each'),'E'=>_('Even'),'O'=>_('Odd'));
							    $sweek = $soptions[$week];
			                                    $mp_title .= $sweek.' - ';
			                                }
			                            }
			                            if($columns['SHORT_NAME'])
			                                    $mp_title .= $columns['SHORT_NAME'].' - ';
			                            
			                            $title = str_replace("'","''",$period[1]['TITLE'].' - '.$mp_title.$teacher[1]['FIRST_NAME'].' '.$teacher[1]['MIDDLE_NAME'].' '.$teacher[1]['LAST_NAME']);

						    $values = "".db_seq_nextval('COURSE_SECTIONS_SEQ').",'".get_school_year()."','".get_school_id()."','$_REQUEST[course_id]','$_REQUEST[course_credits]','$title','0',";
			
                                   
                                    //$schoolcourse=db_request(db_execute("SELECT * FROM COURSES WHERE SHORTNAME='".$columns['SHORT_NAME']."'"));
                                    //print_r($schoolcourse);
                                    
                                    if(StateFieldsSet("COURSE_SECTIONS"))
						    {
							    if(SystemPreferences('VARIABLE_PERIOD_LENGTH')=='Y')
								    $period_length = get_period($Period,'','LENGTH_SUN') + get_period($Period,'','LENGTH_MON') + get_period($Period,'','LENGTH_TUE') + get_period($Period,'','LENGTH_WED') + get_period($Period,'','LENGTH_THU') + get_period($Period,'','LENGTH_FRI') + get_period($Period,'','LENGTH_SAT');
							    else
							    	    $period_length = get_period($Period,'','LENGTH');
								   
						    }
                            	/***************** Enroll Teacher **************/

                                    $aeup_course_id = $_REQUEST['course_id']; //die;
                                    //echo "$aeup_course_id";die;
                                  	$aeup_course_name=  db_request(db_execute("select * from courses where course_id='".$aeup_course_id."'") )[1]['TITLE'];
                                   //echo $aeup_course_name;die;
                                    $imd_courseSQL = "SELECT * FROM mdl_course WHERE idnumber ='".$aeup_course_id ."' ";
                                    $IomadCourse = pg_query($iomadDBconn, $imd_courseSQL);
                					$imd_CourseID = pg_fetch_all($IomadCourse)[0]['id'];
                                    		//course check
                                    if(empty($imd_CourseID)){
                                    	die("This COURSE with idnumber '".$aeup_course_id."' doesn't exist in moodle....<br> UPDATE this course ");
                                    }
                                   // echo $imd_CourseID;die;
            						$aeup_teacher_id = $_REQUEST['tables']['COURSE_SECTIONS']['new']['TEACHER_ID'];
                                  	$aeup_teacher_name=  db_request(db_execute("select * from users where user_id='".$aeup_teacher_id."'") )[1]['USERNAME'];
                                    $imd_usersSQL = "SELECT * FROM mdl_user WHERE username ='".$aeup_teacher_name ."' "; 
                                    $IomadUser = pg_query($iomadDBconn, $imd_usersSQL);
                					$imd_UserID = pg_fetch_all($IomadUser)[0]['id'];
                                   			 //user check
                                    if(empty($imd_UserID)){
                                    	die("This USER with idnumber '".$aeup_teacher_id."'doesn't exists in moodle....");
                                    }
                                   	$enrol_sql = "select mue.id as mueID, me.id as enrolid, mc.id as courseid, mu.id as userid from mdl_user_enrolments mue 
                                    			  inner join mdl_enrol me on mue.enrolid=me.id inner join mdl_course mc on me.courseid = mc.id 
                                                  inner join mdl_user as mu on mu.id=mue.userid where me.enrol='manual' and me.courseid='".$imd_CourseID."' 
                                                  and mue.userid='".$imd_UserID."' " ;
                                    $enroled_query =   pg_query($iomadDBconn, $enrol_sql );
                                  
                                    if(!empty($enroled_user =  pg_fetch_all(  $enroled_query)[0]  ) ){
                                    		die("<strong>USER </strong> already enrolled in this course...");
                                    }
                                    
                					$enrollment_Iomad = array();
                					$form2_data =   db_request(db_execute("select * from form2 where id='9'"));
                					$enrollment_Iomad['domain'] = $form2_data[1]['URL'] ;
                					$enrollment_Iomad['token'] = $form2_data[1]['TOKEN'] ; 
                					$enrollment_Iomad['function'] = "enrol_manual_enrol_users"; 
                					$enrollment_Iomad['course_id'] =  $imd_CourseID ; 
                					$enrollment_Iomad['user_id'] = $imd_UserID ; 
                					$enrollment_Iomad['role_id'] = 3 ;   // teacher

                					include_once($staticpath.'iomadAPI/enroll.php');
                				/***************** Enroll  **************/     
                                    
					    }
					    $go = 0;
                  
                   

					    foreach($columns as $column=>$value)
					    {
                        //print_r($value);die;
                        	if($column == "SUBJECT_ID"){
                            		continue;
                            }
						    if(isset($value))
						    {
							    $fields .= $column.',';
                           
							    $values .= "'".str_replace("\'","''",$value)."',";
                            
                          
							    $go = true;
						    }
  
					     }
                    
                    }
                    else{
                    $titlemsg='<h3>Subject Title Already Exists</h3>';
                        $cat1=$columns['TITLE'];

                    echo $titlemsg.$cat1;
                    //echo "Subject Title Already exists";
                    }

                    
                    }
                     else{
                    
                     $coursemsg='<h3>Course Title Already Exists</h3>';
                        $course1=$columns['TITLE'];

                    echo $coursemsg.$course1;
                    
                   
                    
                    }
                    
                   // die('xsnbcasbdvkj');

					    if($go)
					    {
                        	
							
							// ========   rakesh course creation code: Start  =======//	
							if($table_name=='COURSES' && $_REQUEST['servicefunction'] != 'delete'){
                            		//die('hehehehe');
									$course_field_arr = array('SUBJECT_ID','TITLE','SHORT_NAME');
									$course_fldErr = array();
                           // print_r($course_fldErr);
									foreach ($course_field_arr as $val){
											if( !array_key_exists($val,$columns) || empty($columns[$val]) ){
												$course_fldErr[$val] = $val; 
											}
									}  
									if(!empty($course_fldErr)){
											foreach($course_fldErr as $val){
													if($val == "SUBJECT_ID"){
														echo "<strong>".$val."</strong> field is required...<br>";
														continue;
													}
													echo "<strong>".$val."</strong> field is required...<br>";
											 }
										unset($course_fldErr);die;
									}
						
									$form2_data =   db_request(db_execute("select * from form2 where id='9'"));
                           // print_r($form2_data);
									unset($Iomad_API_Data);
									$Iomad_API_Data = array();
									$Iomad_API_Data['domain'] = $form2_data[1]['URL'] ;
									$Iomad_API_Data['token'] = $form2_data[1]['TOKEN'] ; 
										//  ***** course category existence *****  //
									$imdcourse_categorySQL = "SELECT * FROM mdl_course_categories WHERE idnumber='".$columns['SUBJECT_ID']."' ";
					  // print_r($columns['SUBJECT_ID']);
									$imdcourse_categoryQuery = pg_query($iomadDBconn, $imdcourse_categorySQL);
									$imdcourse_category_Data = pg_fetch_all($imdcourse_categoryQuery)[0];
							  
                            //print_r($imdcourse_category_Data);
									$coursesubjects_Data_array = db_request(db_execute("SELECT * FROM course_subjects  WHERE subject_id='".$columns['SUBJECT_ID']."' "));
									$coursesubjects_Data = $coursesubjects_Data_array[1];
							  
									if(empty($imdcourse_category_Data)){
										//die("empty");
											//create course category in moodle   	
										$Iomad_API_Data['function'] = "core_course_create_categories";   // moodle_course_category function
										$Iomad_API_Data['name'] = $coursesubjects_Data['TITLE'];
										$Iomad_API_Data['parent'] = 1;   // make parent Miscellaneous Category
										$Iomad_API_Data['idnumber'] = $columns['SUBJECT_ID'];
										$Iomad_API_Data['description'] = "<p>New Category".$coursesubjects_Data['TITLE']."</p>";
										$Iomad_API_Data['descriptionformat'] = 1;   // enable HTML 
										include($staticpath.'iomadAPI/course_category.php');   
									} else {
						 				//die("not empty");
										if($imdcourse_category_Data['name'] != $coursesubjects_Data['TITLE'] ){
							   
											  $imdcourse_categoryUpdate = "Update mdl_course_categories set name='".$coursesubjects_Data['TITLE']."' Where idnumber='".$coursesubjects_Data['SUBJECT_ID']."' ";
											  pg_query($iomadDBconn, $imdcourse_categoryUpdate);
					
										 }
											
									}
											//  ***** course existence  *****  //
									$imdcourse_Query = pg_query($iomadDBconn, "SELECT * FROM mdl_course WHERE shortname='".$columns['SHORT_NAME']."'");
									$imdcourse_Data = pg_fetch_all($imdcourse_Query)[0];                
										//new created/updated category
									$imdCoursecategory_Query = pg_query($iomadDBconn, "SELECT * FROM mdl_course_categories WHERE idnumber='".$coursesubjects_Data['SUBJECT_ID']."'");
									$imdCoursecategory_Data = pg_fetch_all($imdCoursecategory_Query)[0];
									if(empty($imdcourse_Data)){
                                    	
											$Iomad_API_Data['function'] = "core_course_create_courses"; 
											$Iomad_API_Data['fullname'] = $columns['TITLE'];
											$Iomad_API_Data['shortname'] = $columns['SHORT_NAME'];
											$Iomad_API_Data['categoryid'] =$imdCoursecategory_Data['id'];
											$Iomad_API_Data['summaryformat'] = 1;
											$Iomad_API_Data['format'] = 'topics' ;
											$Iomad_API_Data['showgrades'] = 1;
											$Iomad_API_Data['newsitems'] = 5 ;
											$Iomad_API_Data['maxbytes'] = 100;
											$Iomad_API_Data['showreports'] = 1;
											$Iomad_API_Data['groupmode'] = 0;
											$Iomad_API_Data['groupmodeforce'] = 0;
											$Iomad_API_Data['defaultgroupingid'] = 0 ;
											$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
											$sql .= " RETURNING *";    // returns inserted data
									 } else {
											die("This <strong>shortname</strong> already exists in moodle");
											
									}														
									
									
									$course_create_data = db_request(db_execute($sql));	
									$inserted_CourseData = $course_create_data[1];
									$Iomad_API_Data['idnumber'] = $inserted_CourseData['COURSE_ID'];	
									if(!empty($Iomad_API_Data['idnumber'])) {
										// iomad course create api
										include_once($staticpath.'iomadAPI/client1.php');
									} 
									
							} else {
									//die("Other table");
									 $sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
                            
                           // echo $sql;die;
                            		 db_execute($sql);
                            
                           
							}
						  		//die('jjjjj');
                      		/* ===== rakesh course creation code: END  ====== */
                        
 // die('hsdgcfjhgjh');
						    if($table_name=='COURSE_SUBJECTS')
							    $_REQUEST['subject_id'] = db_seq_currval($table_name.'_SEQ');
                       
                       
						    elseif($table_name=='COURSES')
							    $_REQUEST['course_id'] = db_seq_currval($table_name.'_SEQ');
						    elseif($table_name=='COURSE_SECTIONS')
						    {
								$new_course_section_id = db_seq_currval($table_name.'_SEQ');
								if(!$_REQUEST['course_section_id'] || $_REQUEST['course_section_id']=='new')
									$_REQUEST['course_section_id'] = $new_course_section_id;
								db_execute("UPDATE COURSE_SECTIONS SET PARENT_ID='".$_REQUEST['course_section_id']."' WHERE COURSE_SECTION_ID='".$new_course_section_id."' AND PARENT_ID IS NULL");


						    }

					    }

             // die('mmmmmmmmm');
						if($table_name=='COURSES' && SystemPreferences('WEIGHTS')!=='Y')
						{
                        	
							$addition_cw_cols = "";
                        //print_r($addition_cw_cols);die;
							$addition_cw_values = "";
							if(count($new_course_data))
							{
								foreach($new_course_data as $elem=>$val)
								{
                                //print_r($val);
									$addition_cw_cols .= ','.$elem;
									$addition_cw_values .= ",'".str_replace("\'","''",$val)."'";
                                
                                
								}
							}
							db_execute("INSERT INTO COURSE_CREDITS (SCHOOL_YEAR,SCHOOL_ID,COURSE_ID,COURSE_CREDIT_TITLE".$addition_cw_cols.") values('".get_school_year()."','".get_school_id()."','".$_REQUEST['course_id']."','1'".$addition_cw_values.")");
							$_REQUEST['course_credits'] = '1';
                        
                        //print_r($addition_cw_cols);
						}
					}
				}
			}
		}
	}

//die('nnnnnnnnnn');
	unset($_REQUEST['tables']);

    if($has_changes && $columns_to_update && count($columns_to_update))
    {
        $msg = '';
        foreach($has_changes as $column=>$value)
            $msg .= $columns_to_update[$column].' is set to "'.$value.'", ';

        $display_additional_info .= '<DIV id=plugin_notice style="padding:50px;position:absolute;display:block;left:50%;top:150px;height:100px;width:400px;margin-left:-200px;border:2px solid #04316C;">';
        $display_additional_info .= 'This change has also changed all students in this section where '.substr($msg,0,-2);
        $display_additional_info .= '<BR><BR><CENTER><input type=button onclick="document.getElementById(\'plugin_notice\').style.display=\'none\';" value="OK"></CENTER>';
        $display_additional_info .= '</DIV>';
    }
}
 //die('helllolo');
if($_REQUEST['servicefunction']!='choose_course')
	DisplayHeader(".:".ProgramTitle().":.");

if($display_additional_info)
    echo $display_additional_info;

//die('%%%%%%%%%');

if($_REQUEST['course_servicefunction']=='search')
{    //die('test');  
	echo '<BR>';
	PopTable('header','<B>'._('Search').'</B>');
	echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]&course_servicefunction=search&useontop=".$_REQUEST['useontop']." method=POST>";
	echo '<TABLE><TR><TD><INPUT type=text name=search_term value="'.$_REQUEST['search_term'].'"></TD><TD><B><INPUT type=submit value='._('Search').'></B></TD></TR></TABLE>';
	echo '</FORM>';
	PopTable('footer');
//die('^^^^^^');
	if($_REQUEST['search_term'])
	{
		$subjects_array = db_request(db_execute("SELECT SUBJECT_ID,TITLE FROM COURSE_SUBJECTS WHERE (UPPER(TITLE) LIKE '%".strtoupper($_REQUEST['search_term'])."%' OR UPPER(SHORT_NAME) = '".strtoupper($_REQUEST['search_term'])."') AND SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY TITLE"));
		$courses_array = db_request(db_execute("SELECT SUBJECT_ID,COURSE_ID,TITLE FROM COURSES WHERE (UPPER(TITLE) LIKE '%".strtoupper($_REQUEST['search_term'])."%' OR UPPER(SHORT_NAME) = '".strtoupper($_REQUEST['search_term'])."') AND SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY TITLE"));
		$periods_array = db_request(db_execute("SELECT c.SUBJECT_ID,cp.COURSE_ID,cp.COURSE_CREDIT_TITLE,cp.COURSE_SECTION_ID,cp.TITLE FROM COURSE_SECTIONS cp,COURSES c WHERE cp.COURSE_ID=c.COURSE_ID AND (UPPER(cp.TITLE) LIKE '%".strtoupper($_REQUEST['search_term'])."%' OR UPPER(cp.SHORT_NAME) = '".strtoupper($_REQUEST['search_term'])."') AND cp.SCHOOL_YEAR='".get_school_year()."' AND cp.SCHOOL_ID='".get_school_id()."' ORDER BY cp.TITLE"));

 
		echo '<TABLE><TR><TD valign=top>';
		$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]&useontop=".$_REQUEST['useontop'];
		$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID');
		Gridoutput($subjects_array,array('TITLE'=>_('Subject')),_('Subject'),_('Subjects'),$link);
		echo '</TD><TD valign=top>';
		$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]&useontop=".$_REQUEST['useontop'];
		$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID','course_id'=>'COURSE_ID');
		Gridoutput($courses_array,array('TITLE'=>_('Course')),_('Course'),_('Amount of Courses'),$link);
    
  //  print_r($courses_array);die;
		echo '</TD><TD valign=top>';
		$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]&useontop=".$_REQUEST['useontop'];
		$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID','course_id'=>'COURSE_ID','course_credits'=>'COURSE_CREDIT_TITLE','course_section_id'=>'COURSE_SECTION_ID');
		Gridoutput($periods_array,array('TITLE'=>_('Section')),_('Course Section'),_('Amount of Course Sections'),$link);
		echo '</TD></TR></TABLE>';
	}
}
//die('######');
if($_REQUEST['servicefunction']=='change_grades')
{  //die('test');      
	if($_REQUEST['new_affects_gpa'])
	{
		if(Prompt(_('GPA change Confirmation'),_('Do you want to change the "Has an effect on GPA" setting for grades given in that course section?')))
		{
			db_execute("UPDATE STUDENT_GRADES_CARD SET {$last_updated_sql}AFFECTS_GPA='".$_REQUEST['new_affects_gpa']."' WHERE COURSE_SECTION_ID='".$_REQUEST['course_section_id']."'");
			unset($_REQUEST['servicefunction']);
			unset($_SESSION['_REQUEST_vars']['servicefunction']);
		}
	}
	elseif(isset($_REQUEST['new_credits'])) //need isset to accept zero values
	{
   // die('!!!!!!!');
		if(Prompt(_('Credits change Confirmtion'),_('Do you want to change the Credits for this course?')))
		{
            $_REQUEST['new_credits']+=0;
			$sections_array = db_request(db_execute("SELECT COURSE_SECTION_ID FROM COURSE_SECTIONS WHERE COURSE_ID='".$_REQUEST['course_id']."'"));
			if(count($sections_array))
			{
				foreach($sections_array as $section)
					$course_sections_list .= ",'".$section['COURSE_SECTION_ID']."'";
				$course_sections_list = substr($course_sections_list,1);

				db_execute("UPDATE STUDENT_GRADES_CARD SET {$last_updated_sql}CREDITS='".$_REQUEST['new_credits']."' WHERE COURSE_SECTION_ID IN(".$course_sections_list.")");
			}
			unset($_REQUEST['servicefunction']);
			unset($_SESSION['_REQUEST_vars']['servicefunction']);
		}
	}
}
//die('kkkkkkkk');
if($_REQUEST['servicefunction']=='delete' && AllowEdit())
{   //die('test');  
	if($_REQUEST['course_section_id'])
	{
		$table = _('course section');
		$sql[] = "DELETE FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='$_REQUEST[course_section_id]'";
		$sql[] = "DELETE FROM STUDENT_SCHEDULE WHERE COURSE_SECTION_ID='$_REQUEST[course_section_id]'";
		$ms_cur = db_request(db_execute("SELECT MERGE_ID,COURSE_SECTION_ID,COURSE_ID FROM COURSE_SECTIONS WHERE MERGE_ID LIKE '".$_REQUEST['course_section_id'].",%' OR MERGE_ID LIKE '%,".$_REQUEST['course_section_id'].",%' OR MERGE_ID LIKE '%,".$_REQUEST['course_section_id']."'"));
		unset($dml);
		foreach($ms_cur as $merge_id)
		{
			if($merge_id['COURSE_SECTION_ID'] != $_REQUEST['course_section_id'])
				$dml .= $merge_id['COURSE_SECTION_ID'].',';
		}
		$dml = substr($dml,0,strlen($dml)-1);
		$dml_array = explode(",",$dml);
		foreach($dml_array as $merge_id)
			$sql[] = "UPDATE COURSE_SECTIONS SET MERGE_ID='".$dml."' WHERE COURSE_SECTION_ID='".$merge_id."'";

		$id_var = 'course_section_id';
	}
	elseif(isset($_REQUEST['course_credits']) && $_REQUEST['course_credits']!='' && SystemPreferences('WEIGHTS')=='Y')
	{
		$table = _('course weight');
		$sql[] = "DELETE FROM COURSE_CREDITS WHERE COURSE_ID='$_REQUEST[course_id]' AND COURSE_CREDIT_TITLE='$_REQUEST[course_credits]'";
		$sql[] = "DELETE FROM COURSE_SECTIONS WHERE COURSE_ID='$_REQUEST[course_id]' AND COURSE_CREDIT_TITLE='$_REQUEST[course_credits]'";
		$sql[] = "DELETE FROM STUDENT_SCHEDULE WHERE COURSE_ID='$_REQUEST[course_id]' AND COURSE_CREDIT_TITLE='$_REQUEST[course_credits]'";
		$sql[] = "DELETE FROM STUDENT_SCHEDULE_REQUESTS WHERE COURSE_ID='$_REQUEST[course_id]' AND COURSE_CREDIT_TITLE='$_REQUEST[course_credits]'";
		$id_var = 'course_credits';
	}
	elseif($_REQUEST['course_id'])
	{
		$table = _('course');
		$sql[] = "DELETE FROM COURSES WHERE COURSE_ID='$_REQUEST[course_id]'";
		$sql[] = "DELETE FROM COURSE_CREDITS WHERE COURSE_ID='$_REQUEST[course_id]'";
		$sql[] = "DELETE FROM COURSE_SECTIONS WHERE COURSE_ID='$_REQUEST[course_id]'";
		$sql[] = "DELETE FROM STUDENT_SCHEDULE WHERE COURSE_ID='$_REQUEST[course_id]'";
		$sql[] = "DELETE FROM STUDENT_SCHEDULE_REQUESTS WHERE COURSE_ID='$_REQUEST[course_id]'";
		$id_var = 'course_id';
	}
	elseif($_REQUEST['subject_id'])
	{
		$table = _('subject');
		$sql[] = "DELETE FROM COURSE_SUBJECTS WHERE SUBJECT_ID='$_REQUEST[subject_id]'";
		$courses = db_request(db_execute("SELECT COURSE_ID FROM COURSES WHERE SUBJECT_ID='$_REQUEST[subject_id]'"));
  
  
		if(count($courses))
		{
			foreach($courses as $course)
			{
				$sql[] = "DELETE FROM COURSES WHERE COURSE_ID='$course[COURSE_ID]'";
				$sql[] = "DELETE FROM COURSE_CREDITS WHERE COURSE_ID='$course[COURSE_ID]'";
				$sql[] = "DELETE FROM COURSE_SECTIONS WHERE COURSE_ID='$course[COURSE_ID]'";
				$sql[] = "DELETE FROM STUDENT_SCHEDULE WHERE COURSE_ID='$course[COURSE_ID]'";
				$sql[] = "DELETE FROM STUDENT_SCHEDULE_REQUESTS WHERE COURSE_ID='$course[COURSE_ID]'";
			}
		}
		$id_var = 'subject_id';
	}

//die('^^^^^^^^^^');  for clicking on delete button
	if(DeletePrompt($table))
	{
		foreach($sql as $query)
			db_execute($query);
		unset($_REQUEST['servicefunction']);
		unset($_REQUEST[$id_var]);
	}

}
//die('dddddddddddd');
if((!$_REQUEST['servicefunction'] || $_REQUEST['servicefunction']=='choose_course') && !$_REQUEST['course_servicefunction'])
{    //die('test'); 
	  $sql = "SELECT SUBJECT_ID,school_id, TITLE,CATEGORY_VISIBLE FROM COURSE_SUBJECTS WHERE (SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."') OR
     (CATEGORY_VISIBLE='Y')  ORDER BY TITLE";

//print_r($sql);
	$QI = db_execute($sql);
	$subjects_array = db_request($QI);

//echo "<pre>";
//print_r($subjects_array);
	if($_REQUEST['servicemod']!='mod_evaluation/BncCourseProperties.php')
	{
		$search_header = '';
    		$current_URL = urlencode(SetRequestOptions(null,array('subject_id','course_id','course_credits','course_section_id','values')));
    		$search_link =  "<B><A HREF=modloader.php?servicemod=mod_curriculum/ScdMSReport.php&servicefunction=search&CoursesURL=".$current_URL."&useontop=".$_REQUEST['useontop'].">"._('Search')."</A></B>";
		if(AllowUse('mod_curriculum/ScdStudSchedReport.php') && $_REQUEST['course_id'] && $_REQUEST['course_id']!='new' && $_REQUEST['course_section_id']!='new' && $_REQUEST['course_credits']!='new')
		{  
        	//die('hhiiii');
			$header2 = "modloader.php?servicemod=mod_curriculum/ScdStudSchedReport.php&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&useontop=".$_REQUEST['useontop'];
//		$courses_link = "modloader.php?servicemod=mod_curriculum/ScdCourseProperties.php&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&addition_option=$_REQUEST[addition_option]&useontop=".$_REQUEST['useontop'];
			$courses_link = "modloader.php?servicemod=mod_curriculum/ScdCourseProperties.php&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&useontop=".$_REQUEST['useontop'];
			$location = 'courses';
			$location_title = _('Course ');
			if(isset($_REQUEST['course_credits']))
			{
				$header2 .= "&course_credits=$_REQUEST[course_credits]";
				$courses_link .= "&course_credits=$_REQUEST[course_credits]";
				if(SystemPreferences('WEIGHTS')=='Y')
				{
					$location = 'course_credits';
					$location_title = _('Course Weight ');
				}
				if($_REQUEST['course_section_id'])
				{
					$header2 .= "&course_section_id=$_REQUEST[course_section_id]";
					$courses_link .= "&course_section_id=$_REQUEST[course_section_id]";
					$location = 'course_sections';
					$location_title = _('Course Section ');
				}
			}
			//$header .= '<TD width=10></TD><TD>'.DrawTab(sprintf(_('List Unscheduled Requests in this %s'),$location_title),$header2."&unscheduled=true&students=$location&servicefunction=$location",'CCCCCC','000000','_circle',array('tabcolor'=>'CCCCCC','textcolor'=>'000000')).'</TD>';
			//$header .= '<TD width=10></TD><TD><A HREF='.$courses_link.' style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'.sprintf(_('View/Edit this %s'),$location_title).'</A></TD>';
			$search_header .= '<TABLE><TR>';
        
        
     //  die('$$$$$$$');
			if($_REQUEST['servicefunction']=='choose_course' && AllowUse('mod_curriculum/ScdCourseProperties.php'))
			{
				if($location == 'courses')
				{
					$location_title = _('Course');
					$search_header .= '<TD width=10></TD><TD><A HREF='.$courses_link.' style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'.sprintf(_('View or Edit this %s'),$location_title).'</A></TD>';
				}
				elseif($location == 'course_credits')
                                {
                                         $location_title = _('Course Weight');
                                         $search_header .= '<TD width=10></TD><TD><A HREF='.$courses_link.' style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'.sprintf(_('View or Edit this %s'),$location_title).'</A></TD>';
                                         $location_title = _('Course Weight ');
                    		}
				else
					$search_header .= '<TD width=10></TD><TD><A HREF='.$courses_link.' style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'.sprintf(_('View or Edit this %s'),$location_title).'</A></TD>';
			}
				if($location == 'courses')
				{
					$location_title = _(' Course');
		                        $search_header .= '<TD width=10></TD><TD><A HREF='.$header2."&students=$location&servicefunction=$location".' style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'.sprintf(_(' Display List of Students in this %s'),$location_title).'</A></TD>';
		                }
		                else
					$search_header .= '<TD width=10></TD><TD><A HREF='.$header2."&students=$location&servicefunction=$location".' style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'.sprintf(_(' Display List of Students in this %s'),$location_title).'</A></TD>';
                        if(SystemPreferences('USE_REQUESTS')=='Y')
				if($location == 'courses')
			    	{
					$location_title = _('Course');
					$search_header .= '<TD width=10></TD><TD><A HREF='.$header2."&unscheduled=true&students=$location&servicefunction=$location".' style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'.sprintf(_('Display  List of Unfilled Requests in this %s'),$location_title).'</A></TD>';
				}
				else
				{
//					$location_title = _('Course');
					$search_header .= '<TD width=10></TD><TD><A HREF='.$header2."&unscheduled=true&students=$location&servicefunction=$location".' style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'.sprintf(_('Display  List of Unfilled Requests in this %s'),$location_title).'</A></TD>';
				}
                        $search_header .= "<TD width=50></TD><TD>$search_link &nbsp; &nbsp;</TD>";
			$search_header .= '</TR></TABLE>';
		}
		else
    		{
	                $search_header =  $search_link;
			//$search_header = "<A HREF=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]&course_servicefunction=search&useontop=".$_REQUEST['useontop'].">"._('Search')."</A> &nbsp; &nbsp;";
	        }
	}
	if($_REQUEST['servicefunction']!='choose_course')
	{
    	$sql = "SELECT USER_ID,LAST_NAME,FIRST_NAME,MIDDLE_NAME,CFIELD_40003 FROM USERS WHERE PROFILE='teacher'";
    	if(!empty( get_school_id() ) )
        {
        	$sql .= "AND SCHOOLS LIKE '%,".get_school_id().",%'";
        }
    	$sql .= "";
    	
    	$query = "";
    	
		//$teachers_array = db_request(db_execute("SELECT USER_ID,LAST_NAME,FIRST_NAME,MIDDLE_NAME,CFIELD_40003 FROM USERS WHERE SCHOOLS LIKE '%,".get_school_id().",%' AND PROFILE='teacher' ORDER BY LAST_NAME,FIRST_NAME"));
		$teachers_array = db_request(db_execute("SELECT username, USER_ID,LAST_NAME,FIRST_NAME,MIDDLE_NAME,CFIELD_40003 FROM USERS WHERE PROFILE='teacher' ORDER BY LAST_NAME,FIRST_NAME"));
 /* echo "<pre>";
    print_r($teachers_array);
    echo "</pre>"; die; 
  */
    echo '<script language=javascript>
			teachers = new Array;
		';
		foreach($teachers_array as $teacher)
		{
			if($teacher['CFIELD_40003'])
				echo 'teachers['.$teacher['USER_ID'].'] = "'.$teacher['CFIELD_40003'].'";';
			else
				echo 'teachers['.$teacher['USER_ID'].'] = false;';
		}

		$i = 0;

		echo '
		function selectRoom(teacher_id)
		{
			if(teachers[teacher_id])
			{
				if(document.getElementById(\'innerdivtables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][ROOM]\'))
					document.getElementById(\'innerdivtables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][ROOM]\').onclick();

				document.getElementById(\'inputtables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][ROOM]\').value = teachers[teacher_id];
			}
		}
		</script>';
		if(AllowEdit() && $_REQUEST['servicemod']!='mod_curriculum/Curriculum.php')
			$delete_button = "<INPUT type=button value="._('Delete')." onClick='javascript:window.location=\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_credits=$_REQUEST[course_credits]&course_section_id=$_REQUEST[course_section_id]&useontop=".$_REQUEST['useontop']."\"'> &nbsp; &nbsp; ";
		// ADDING & EDITING FORM
		if(Preferences('CALENDAR') == 'Mon')
			$days = array('Mon','Tue','Wed','Thu','Fri','Sat','Sun');
		else
			$days = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

		if($_REQUEST['course_section_id'])
		{ //die('if 1');
			if($_REQUEST['course_section_id']!='new')
			{
				$sql = "SELECT cp.*,c.TITLE AS COURSE_TITLE
						FROM COURSE_SECTIONS cp,COURSES c
						WHERE c.COURSE_ID=cp.COURSE_ID AND cp.COURSE_SECTION_ID='$_REQUEST[course_section_id]'";
				$QI = db_execute($sql);
				$array = db_request($QI);
            
          //  print_r($array);die('fdgdfhsh');
				$array = $array[1];
				foreach($days as $day)
				{
					if(strpos($array['TITLE'],$day)!==false)
					{
						$array['TITLE'] = str_replace($day,_($day).' ',$array['TITLE']);
					}
				}

				$title = '<b>'.$array['COURSE_TITLE'].'</b>: '.$array['TITLE'];
            
            //print_r($title);die('sdgdfsgdf');
				$new = false;
				$div = 'force';

            			$array_data["COURSE_SECTIONS"] = $array;
		                $array_data["COURSES"] = db_request(db_execute("SELECT * FROM COURSES WHERE COURSE_ID='{$_REQUEST['course_id']}'")); $array_data['COURSES'] = $array_data['COURSES'][1];
			
            
            
            }
			else
			{
				$sql = "SELECT TITLE
						FROM COURSES
						WHERE COURSE_ID='$_REQUEST[course_id]'";
				$QI = db_execute($sql);
				$array = db_request($QI);
				$title = $array[1]['TITLE'].' - '._('New Section');
				unset($delete_button);
				unset($array);
				$array['DOES_ATTENDANCE'] = $array['DOES_GRADES'] = $array['DOES_GPA'] = 'Y';
				if(function_exists('_set_cp_defaults'))
				{
				    $array = _set_cp_defaults($array, $_REQUEST['course_id']);
				}
				$new = true;
				$div = false;
			}

			if($affects_gpa_changed!==false)
			{
				if($affects_gpa_changed==_('affect GPA'))
				{
					$new_affects_gpa = 'Y';
					$grades_array = db_request(db_execute("SELECT ID FROM STUDENT_GRADES_CARD WHERE SCHOOL_YEAR='".get_school_year()."' AND COURSE_SECTION_ID='".$_REQUEST['course_section_id']."' AND (AFFECTS_GPA!='Y' OR AFFECTS_GPA IS NULL)"));
				}
				else
				{
					$new_affects_gpa = 'N';
					$grades_array = db_request(db_execute("SELECT ID FROM STUDENT_GRADES_CARD WHERE SCHOOL_YEAR='".get_school_year()."' AND COURSE_SECTION_ID='".$_REQUEST['course_section_id']."' AND AFFECTS_GPA='Y'"));
				}

				if(count($grades_array))
				{
					echo '<DIV id=affects_gpa_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;">';
					echo _('You just changed ').$title.' '._('to').' '.$affects_gpa_changed.'.  <BR><BR>'._('Some grades have already been entered for this course in the current school year.  Would you like to change these grades to ').$affects_gpa_changed.'?';
					echo '<BR><BR><INPUT type=button value="'._("Don't Change Grades").'" onclick="document.getElementById(\'affects_gpa_confirm\').style.display=\'none\';"> &nbsp; &nbsp; &nbsp; <INPUT type=button value="'._('Change Grades to ').$affects_gpa_changed.'" onclick="document.location.href=\'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction=change_grades&new_affects_gpa='.$new_affects_gpa.'&course_section_id='.$_REQUEST['course_section_id'].'&subject_id='.$_REQUEST['subject_id'].'&course_id='.$_REQUEST['course_id'].'&course_credits='.$_REQUEST['course_credits'].'\';">';
					echo '</DIV>';
				}
			}

		//www
			echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_credits=$_REQUEST[course_credits]&course_section_id=$_REQUEST[course_section_id]&useontop=".$_REQUEST['useontop']." method=POST>";
			DisplayHeader($title,'<table><tr><td>'.$search_header.'</td><td>'.$delete_button.$submitButton->createSButton(_('Save')).'</td></tr></table>');
			$header .= '<TABLE  cellpadding="0" width=100% cellspacing="0">';
			$header .= '<TR background=themes/'.Preferences('HIGHLIGHT_FRAME').'/bottom_shadow.png height=15><TD colspan= 9></TD></TR>';
			$header .= '<TR>';
        	//periods

			$periods_array = db_request(db_execute("SELECT SCHOOL_PERIOD_ID,TITLE FROM SCHOOL_PERIODS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."' ORDER BY SORT_ORDER"));
//print_r($periods_array);die;
			if(count($periods_array))
			{
				foreach($periods_array as $period)
					$periods[$period['SCHOOL_PERIOD_ID']] = $period['TITLE'];
			}
			$header.=(($_REQUEST['course_section_id']=='new')&&($_Config['scheduling_multiple_periods']))?'<TD>'.SelectMultipleInput('','tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][SCHOOL_PERIOD_ID]','Periods',$periods,'','',false,5).'</TD>':'<TD>'.SelectInput($array['SCHOOL_PERIOD_ID'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][SCHOOL_PERIOD_ID]',_('School Period'),$periods).'</TD>';
		//room
			$header .= '<TD>'.TextInput($array['ROOM'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][ROOM]',_('Class-room'),'maxlength=10',$div)."<A HREF=# onclick='window.open(\"modloader.php?servicemod=mod_ssetup/SchInventoryCenter.php&choose_room=true&course_section_id=".$_REQUEST['course_section_id']."&useontop=false&course_manage=true\",\"\",\"scrollbars=yes,resizable=yes,width=1200,height=550\");'>".'<IMG SRC=images/add_button.gif height=15 width=15 border=0></A></TD>';
    		//Grading Scale
			$options_array = db_request(db_execute("SELECT TITLE,ID FROM GRADES_CARD_TYPES WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY DEFAULT_SCALE,TITLE"));
			if(count($options_array))
			{
				$options = array();
				foreach($options_array as $option)
					$options[$option['ID']] = $option['TITLE'];
			}
			else
				$options = array();
			$header .= '<TD width=200>' . SelectInput($array['GRADE_TYPE_ID'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][GRADE_TYPE_ID]',_('Grading Scale'),$options,false) . '</TD>';

                //Meeting Days
			if(SystemPreferences('ODD_EVEN_WEEKS','system')!='Y')
				$header .= '<TD colspan=2 align=center width=300>';
			else
				$header .= '<TD align=center width=300>';
			if($new==false)
				$header .= '<DIV id=days>'.'<div onclick=\'addHTML("';
			$days_str = '';
			$header .= '<TABLE><TR><TD>'._('Meeting Days').':'.'</TD>';

			foreach($days as $day)
			{
				if(strpos($array['DAYS'],$day)!==false || (($new && $day!='Sat' && $day!='Sun')))
				{
					$days_str .= _($day).' ';
					$value = 'Y';
				}else{
					$value = '';
				}

				$header .= '<TD>'.str_replace('"','\"',CheckboxInput($value,'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][DAYS]['.$day.']',_($day),$checked,false,'','',false)).'</TD>';
			}
			$header .= '</TR></TABLE>';

			if($new==false)
				$header .= '","days",true);\' style="border-bottom-style:dotted;border-bottom-width:1;border-bottom-color:#0033CC;">'._('Meeting Days').': '.$days_str.'</div></DIV>'.'';
			$header .= '</TD>';
		// Odd/Even Weeks
			$week = $array['WEEK'];
			$soptions = array('A'=>_('Each'),'E'=>_('Even'),'O'=>_('Odd'));
			$rsoptions = array(_('Each')=>'A',_('Even')=>'E',_('Odd')=>'O');
			if(SystemPreferences('ODD_EVEN_WEEKS','system')=='Y')
			{
				if(!$week) $week = _('Each');
				else
					$week = $soptions[$week];
				if($new==false)
					$wdiv = 'force';
				else
					$wdiv = false;
				$_SESSION['week_options'] = $rsoptions;
				$header .= '<TD align=center>';
				$header .= '<TABLE><TR><TD>'._('Week').':'.'</TD>';
				$header .= '<TD>'.make_radiobutton($week,'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][WEEK]','',$soptions,'','',$wdiv,false).'</TD>';
				$header .= '</TR></TABLE>';
				$header .= '</TD>';
			}
			$header .= '</TR>';
			$header .= '<TR>';
		//teacher
        
       // echo "<pre>"; print_r($teachers_array);die;
       //die('******************');
			if(count($teachers_array))
			{
				foreach($teachers_array as $teacher)
					$teachers[$teacher['USER_ID']] = $teacher['LAST_NAME'].', '.$teacher['FIRST_NAME'].' '.$teacher['MIDDLE_NAME'];
					//$teachers[$teacher['USER_ID']] = $teacher['USERNAME'];
			}
			$header .= '<TD width=400>' . SelectInput($array['TEACHER_ID'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][TEACHER_ID]',_('Teacher Name'),$teachers,null,'onchange="selectRoom(this.options[this.selectedIndex].value);"') . '</TD>';
	        //seats
			$header .= '<TD>'.TextInput($array['TOTAL_SEATS'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][TOTAL_SEATS]',_('Amount of Seats'),'size=4',$div) . '</TD>';
      		//grades
			$header .= '<TD>'.CheckboxInput($array['DOES_GRADES'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][DOES_GRADES]',_('Makes the Grade'),$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>') . '</TD>';
		//Calendar
			$options_array = db_request(db_execute("SELECT TITLE,CALENDAR_ID FROM SCHOOL_CALENDARS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
			if(count($options_array))
			{
				$options = array();
				foreach($options_array as $option)
					$options[$option['CALENDAR_ID']] = $option['TITLE'];
			}
			else
				$options = array();

			$header .= '<TD width=250>'.SelectInput($array['CALENDAR_ID'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CALENDAR_ID]',_('Calendar'),$options,false) . '</TD>';
		//Parent Section
			if($_REQUEST['course_section_id']!='new' && $array['PARENT_ID']!=$_REQUEST['course_section_id'])
			{
				$parent = db_request(db_execute("SELECT cp.TITLE as CP_TITLE,c.TITLE AS C_TITLE,cp.COURSE_CREDIT_TITLE FROM COURSE_SECTIONS cp,COURSES c WHERE c.COURSE_ID=cp.COURSE_ID AND cp.COURSE_SECTION_ID='".$array['PARENT_ID']."'"));
				
           // print_r($parent);die;
            if(SystemPreferences('WEIGHTS')=='Y')
					$weights_extra = ' - '.$parent[1]['COURSE_CREDIT_TITLE'];
				else
					$weights_extra = '';

				$parent = $parent[1]['C_TITLE'].$weights_extra.': '.$parent[1]['CP_TITLE'];
			}
			elseif($_REQUEST['course_section_id']!='new')
			{
				//$children = db_request(db_execute("SELECT COURSE_SECTION_ID FROM COURSE_SECTIONS WHERE PARENT_ID='".$_REQUEST['course_section_id']."' AND COURSE_SECTION_ID!='".$_REQUEST['course_section_id']."'"));
				// THIS SHOULD SHOW A MESSAGE INDICATING THAT IT'S THE CHILD OF A DIFFERENT SECTION (and which one)
				$children = db_request(db_execute("SELECT cp.COURSE_SECTION_ID,cp.TITLE,c.TITLE AS COURSE_TITLE,cp.COURSE_ID,cp.COURSE_CREDIT_TITLE,c.SUBJECT_ID FROM COURSE_SECTIONS cp,COURSES c,SCHOOL_PERIODS p WHERE cp.COURSE_ID=c.COURSE_ID AND p.SCHOOL_PERIOD_ID=cp.SCHOOL_PERIOD_ID AND cp.PARENT_ID='".$_REQUEST['course_section_id']."' AND cp.COURSE_SECTION_ID!='".$_REQUEST['course_section_id']."' ORDER BY cp.SCHOOL_TERM_ID,p.SORT_ORDER"));
				if(count($children))
					$parent = '';
				else
					$parent = _('No Parent Section is chosen');
			}
			else
				$parent = ' ';
			$header .= "<TD><DIV id=course_div>".$parent."</DIV> ";
			if($parent)
				$header .= "<A HREF=# onclick='window.open(\"modloader.php?servicemod=".$_REQUEST['servicemod']."&servicefunction=choose_course&has_parent=".$_REQUEST['course_section_id']."\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'><IMG SRC=images/add_button.gif height=15 width=15 border=0></A>  <small>"._('Parent Section').'</small>';
			else
			{
				$header .= '<small>'._('This section is the parent of');
				foreach($children as $child)
					$header .= ProgramLink('mod_curriculum/ScdCourseProperties.php',wordwrap($child['COURSE_TITLE'].': '.$child['TITLE'],40),'&subject_id='.$child['SUBJECT_ID'].'&course_id='.$child['COURSE_ID'].'&course_credits='.$child['COURSE_CREDIT_TITLE'].'&course_section_id='.$child['COURSE_SECTION_ID'],true);
			}
			$header .= '</small></TD>';
			$header .= '</TR>';
			$header .= '<TR>';
    		//school term
                     	$mp_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,SHORT_NAME,TITLE,'2' AS MP_TABLE,
                     				 SORT_ORDER FROM SCHOOL_QUARTERS WHERE SCHOOL_ID='".
                     				 get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."' UNION
                     				 SELECT SCHOOL_TERM_ID,SHORT_NAME,TITLE,'1' AS MP_TABLE,
                     				 SORT_ORDER FROM SCHOOL_SEMESTERS WHERE SCHOOL_ID='".
                     				 get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."'
                     				 ORDER BY 3,4"));
			unset($options);
			$options['0'] = _('Full Year');

			if(count($mp_array))
			{
				foreach($mp_array as $mp)
					$options[$mp['SCHOOL_TERM_ID']] = $mp['TITLE'];
			}

			$header .= '<TD>'.SelectInput($array['SCHOOL_TERM_ID'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][SCHOOL_TERM_ID]',_('School Term'),$options,false) . '</TD>';
    		//attendace
			$header .= '<TD>'.CheckboxInput($array['DOES_ATTENDANCE'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][DOES_ATTENDANCE]',_('Has an effect on Attendance'),$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>') . '</TD>';
		//gpa
			$header .= '<TD>'.CheckboxInput($array['DOES_GPA'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][DOES_GPA]',_('Has an effect on GPA'),$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>') . '</TD>';
		//Gender Restriction
			$header .= '<TD>'.SelectInput($array['GENDER_RESTRICTION'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][GENDER_RESTRICTION]',_('Gender Restriction'),array('N'=>_('None'),'M'=>_('Male'),'F'=>_('Female')),false) . '</TD>';
			//short name
			$header .= '<TD width=200>'.TextInput($array['SHORT_NAME'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][SHORT_NAME]',_('Short Name'),null,$div) . '</TD>';

 			// COURSE_CREDIT_TITLE
			//$header .= '<TD>' . CheckboxInput($array['HOUSE_RESTRICTION'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][HOUSE_RESTRICTION]','Restricts House','',$new) . '</TD>';
			$header .= '</TR>';

		//Merge Sections
			$header .= '<TR></TD><TD COLSPAN=5>';
			if($_REQUEST['course_section_id']!='new' && $array['MERGE_ID'])//!=$_REQUEST['course_section_id'])
			{
//				$merge_cs = db_request(db_execute("SELECT cp.TITLE as CP_TITLE,c.TITLE AS C_TITLE,cp.COURSE_CREDIT_TITLE FROM COURSE_SECTIONS cp,COURSES c WHERE c.COURSE_ID=cp.COURSE_ID AND cp.COURSE_SECTION_ID='".$array['MERGE_ID']."'"));
				if($array['MERGE_ID'])
					$merge_in = $array['MERGE_ID'];
				else
					$merge_in = 'NULL';
				$merge_cs = db_request(db_execute("SELECT cp.TITLE as CP_TITLE,cp.COURSE_SECTION_ID,c.TITLE AS C_TITLE,cp.COURSE_CREDIT_TITLE FROM COURSE_SECTIONS cp,COURSES c WHERE c.COURSE_ID=cp.COURSE_ID AND cp.COURSE_SECTION_ID IN (".$merge_in.") AND COURSE_SECTION_ID != '".$_REQUEST['course_section_id']."'"));
	//			var_dump($merge_cs);
				$ms_sections = _('Linked course sections').':<BR>';


				foreach($merge_cs as $msection)
				{
				if(SystemPreferences('WEIGHTS')=='Y')
					$weights_extra = ' - '.$merge_cs[1]['COURSE_CREDIT_TITLE'];
				else
					$weights_extra = '';
//echo $msection;
				$days = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
				foreach($days as $day)
				{
					if(strpos($msection['CP_TITLE'],$day)!==false)
						$msection['CP_TITLE'] = str_replace($day,_($day).' ',$msection['CP_TITLE']);
				}
                                echo '<DIV id="conf" style="display:none;"></div>';
        			$ms_delete_link = "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF=\"#\" onclick=\"delete_confirm(&quot;".$_REQUEST['course_section_id']."&quot;,&quot;".$msection['COURSE_SECTION_ID']."&quot;); return false;\"><IMG SRC=images/remove_button.gif height=15 width=15 border=0></A> ";
                                //$ms_delete_link = "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF=\"#\" id=\"delete_confirm\" \"><IMG SRC=images/remove_button.gif height=15 width=15 border=0></A> ";
				$ms_sections .= '<DIV ID="MERGE_'.$_REQUEST['course_section_id'].'_'.$msection['COURSE_SECTION_ID'].'">'.$ms_delete_link.' '.$msection['C_TITLE'].$weights_extra.': '.$msection['CP_TITLE'].'</DIV>';
				}
			}
			elseif($_REQUEST['course_section_id']!='new' && !$array['MERGE_ID'])
			{
				$ms_sections = '<DIV id=no_ms_div>'._('No linked course sections were found').'</DIV>';
			}
//			$header .="<A HREF=# onclick='window.open(\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=choose_course&addition_option=merge_sections\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'><DIV id=choose_course_div>"._('Choose a Course')."</DIV></A>";
			$temp_servicemod = 'mod_curriculum/ScdMajorAddSchedule.php';
        
       
//<INPUT type=HIDDEN name=hidden_merge_single id=hidden_merge_single />
                        /*закоментированна линковка секций*/
			//$header .= "<DIV id=merge_sections_div> ".$ms_sections."</DIV>";
			//$header .="<A HREF=# onclick='window.open(\"modloader.php?servicemod=$temp_servicemod&servicefunction=choose_course&addition_option=merge_sections&orig_course_id=$_REQUEST[course_id]&orig_course_section_id=$_REQUEST[course_section_id]\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'><DIV id=choose_course_div><IMG SRC=images/add_button.gif height=15 width=15 border=0><SMALL>"._('Add a Course Section')."</SMALL></DIV></A>";
                        /*закоментированна линковка секций конец*/
/*			if($_REQUEST['course_section_id']!='new' && $array['MERGE_ID']!=$_REQUEST['course_section_id'])
			{
			echo "vvv";
//				$merge_cs = db_request(db_execute("SELECT cp.TITLE as CP_TITLE,c.TITLE AS C_TITLE,cp.COURSE_CREDIT_TITLE FROM COURSE_SECTIONS cp,COURSES c WHERE c.COURSE_ID=cp.COURSE_ID AND cp.COURSE_SECTION_ID='".$array['MERGE_ID']."'"));
				$merge_cs = db_request(db_execute("SELECT cp.TITLE as CP_TITLE,c.TITLE AS C_TITLE,cp.COURSE_CREDIT_TITLE FROM COURSE_SECTIONS cp,COURSES c WHERE c.COURSE_ID=cp.COURSE_ID AND cp.MERGE_ID IS NOT NULL"));
				var_dump($merge_cs);
				if(SystemPreferences('WEIGHTS')=='Y')
					$weights_extra = ' - '.$merge_cs[1]['COURSE_CREDIT_TITLE'];
				else
					$weights_extra = '';

				$merge_cs = $merge_cs[1]['C_TITLE'].$weights_extra.': '.$merge_cs[1]['CP_TITLE'];
			}
			elseif($_REQUEST['course_section_id']!='new')
			{
			echo "xxx";
				//$children = db_request(db_execute("SELECT COURSE_SECTION_ID FROM COURSE_SECTIONS WHERE PARENT_ID='".$_REQUEST['course_section_id']."' AND COURSE_SECTION_ID!='".$_REQUEST['course_section_id']."'"));
				// THIS SHOULD SHOW A MESSAGE INDICATING THAT IT'S THE CHILD OF A DIFFERENT SECTION (and which one)
				$merged_cs = db_request(db_execute("SELECT cp.COURSE_SECTION_ID,cp.TITLE,c.TITLE AS COURSE_TITLE,cp.COURSE_ID,cp.COURSE_CREDIT_TITLE,c.SUBJECT_ID FROM COURSE_SECTIONS cp,COURSES c,SCHOOL_PERIODS p WHERE cp.COURSE_ID=c.COURSE_ID AND p.SCHOOL_PERIOD_ID=cp.SCHOOL_PERIOD_ID AND cp.PARENT_ID='".$_REQUEST['course_section_id']."' AND cp.COURSE_SECTION_ID!='".$_REQUEST['course_section_id']."' ORDER BY cp.SCHOOL_TERM_ID,p.SORT_ORDER"));
				if(count($merged_cs))
					$merge_cs = '';
				else
					$merge_cs = _('No Sections were added');
			}
			else
				$merge_cs = ' ';
			$header .= "<TR><TD><DIV id=course_div>".$merge_cs."</DIV> ";
			if($merge_cs)
				$header .= "<A HREF=# onclick='window.open(\"modloader.php?servicemod=".$_REQUEST['servicemod']."&servicefunction=choose_course&has_parent=".$_REQUEST['course_section_id']."\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'><IMG SRC=images/add_button.gif height=15 width=15 border=0></A>  <small>"._('Add a course section').'</small>';
			else
			{
				$header .= '<small>'._('These sections are for the same course');
				foreach($merged_cs as $msection)
					$header .= ProgramLink('mod_curriculum/ScdCourseProperties.php',wordwrap($msection['COURSE_TITLE'].': '.$msection['TITLE'],40),'&subject_id='.$msection['SUBJECT_ID'].'&course_id='.$msection['COURSE_ID'].'&course_credits='.$msection['COURSE_CREDIT_TITLE'].'&course_section_id='.$msection['COURSE_SECTION_ID'],true);
			}
			$header .= '</small></TD>';
*/
			$header .= '</TD></TR>';

			$header .= '<TR background=themes/'.Preferences('HIGHLIGHT_FRAME').'/bottom_shadow.png height=15><TD colspan= 9></TD></TR>';
	                $header .= '</TABLE>';
	                $tabs = array();
            if($_SYSTEM['config']['CO_TEACHER_CUSTOM1'] || $_SYSTEM['config']['CO_TEACHING'])
                $tabs['coteacher'] = array('title'=>'Co-Teachers','link'=>'# onclick="_selectTab(\'Co-Teachers\');"'); ////if($_SYSTEM['config']['CO_TEACHER_CUSTOM1']&&$_SYSTEM['config']['CO_TEACHER_CUSTOM2']&&$_SYSTEM['config']['CO_TEACHER_CHECKBOX1'])
			if(StateFieldsSet('COURSE_SECTIONS'))
                $tabs['state'] = array('title'=>($_SYSTEM['config']['state_name']?$_SYSTEM['config']['state_name']:"State"),'link'=>'# onclick="_selectTab(\''.($_SYSTEM['config']['state_name']?$_SYSTEM['config']['state_name']:"State").'\');"');
			if(count($tabs))
            {
                echo '
                <script language=javascript>
                    function _selectTab(tab)
                    {
                        ';
                        foreach($tabs as $tab)
                        {
                            echo 'document.getElementById(\''.$tab['title'].'_content\').style.display=\'none\';document.getElementById(\'tab[__onclick=__selectTab(_'.$tab['title'].'_)__]\').style.backgroundColor=\'#DDDDDD\';document.getElementById(\'tab[__onclick=__selectTab(_'.$tab['title'].'_)__]\').style.color=\'#000000\';';
                        }
                echo '
                        document.getElementById(tab+\'_content\').style.display=\'block\';document.getElementById(\'tab[__onclick=__selectTab(_\'+tab+\'_)__]\').style.backgroundColor=\'#'.Preferences('HIGHLIGHT').'\';this.style.color=\'#FFFFFF\';
                    }
                </script>
                ';
                if(!$_SYSTEM['selected_tab'])
                {
                    if($tabs['state'])
                        $_SYSTEM['selected_tab'] = '# onclick="_selectTab(\''.($_SYSTEM['config']['state_name']?$_SYSTEM['config']['state_name']:"State").'\');"';
                    else
                        $_SYSTEM['selected_tab'] = '# onclick="_selectTab(\'Co-Teachers\');"';
                }
                $header .= PopTable('header',$tabs,null,null,'',true);
                if($tabs['state'])
                {
                    $div = $_REQUEST['course_section_id']=='new'?false:'force';
                    $header .= '<IMG SRC=images/pixel_trans.gif wid`th=500 height=1>';
                    $header .= '<TABLE cellpadding=3 width=100%  style="" id="'.($_SYSTEM['config']['state_name']?$_SYSTEM['config']['state_name']:"State").'_content"><TR>';
//                    $state_fields_programs = array(/*"COURSES",*/ "COURSE_SECTIONS");
                    $state_fields_programs = array("COURSE_SECTIONS");
                    $state_fields_request_id = array("COURSES"=>'course_id', "COURSE_SECTIONS"=>'course_section_id');
                    $i = 0;
                    foreach($state_fields_programs as $program)
                    {
                        if(StateFieldsSet($program))
                        {
                            $fields = StateFieldsArray($program);
                            foreach($fields as $field=>$title)
                            {
                                $value = $array_data[$program][$field];
                                $name = 'tables['.$program.']['.$_REQUEST[$state_fields_request_id[$program]].']['.$field.']';
                                $title = $_SYSTEM['config'][$program][$field];

                                if(isset($_SYSTEM['config']['checkbox'][$program][$field]) || strpos($field, "CHECKBOX")!==false)
                                    $control = CheckboxInput($value, $name, $title, $checked, false,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>', $div);
                                elseif(isset($_SYSTEM['config']['select_options'][$program][$field])||isset($_SYSTEM['config']['custom_select_options'][$program][$field]))
                                    $control = SelectInput($value, $name, $title, $_SYSTEM['config']['select_options'][$program][$field], false, '', $div, null, false);
                                elseif(isset($_SYSTEM['config']['date'][$program][$field]))
                                    $control = DateInput($value, $name, $title, $div, $false);
                                else
                                    $control = TextInput($value, $name, $title, '', $div);

                                if(($i%3)==0)
                                    $header .= "</tr><tr>";

                                $i++;

                                $header .= '<TD>'.$control.'</TD>';
                            }
                        }
                    }
                    $header .= '</TR>';
                    $header .= '</TABLE>';
                }
            
            
         //die('zzzzzzzz');
                if($tabs['coteacher'])
                {
                    $coteacher_count = isset($_SYSTEM['config']['CO_TEACHING']) && is_numeric($_SYSTEM['config']['CO_TEACHING']) ? $_SYSTEM['config']['CO_TEACHING'] : 10;

                    $header .= '<TABLE cellpadding=3 width=100% '.($_SYSTEM['selected_tab'] != '# onclick="_selectTab(\'Co-Teachers\');"'?'style="display:none;"':'').' id="Co-Teachers_content"><TR><TD>';
                    $coteacher_array = array();
                    $coteacher_cols = array('CO_TEACHER_ID'=>_('Co-Teacher'));

                    if($_SYSTEM['config']['CO_TEACHER_PERMISSIONS'])
                        $coteacher_cols['CO_TEACHER_PERMISSIONS'] = $_SYSTEM['config']['CO_TEACHER_PERMISSIONS'];
                    if($_SYSTEM['config']['CO_TEACHER_CUSTOM1'])
                        $coteacher_cols['CO_TEACHER_CUSTOM1'] = $_SYSTEM['config']['CO_TEACHER_CUSTOM1'];
                    if($_SYSTEM['config']['CO_TEACHER_CUSTOM2'])
                        $coteacher_cols['CO_TEACHER_CUSTOM2'] = $_SYSTEM['config']['CO_TEACHER_CUSTOM2'];
                    if($_SYSTEM['config']['CO_TEACHER_CHECKBOX1'])
                        $coteacher_cols['CO_TEACHER_CHECKBOX1'] = $_SYSTEM['config']['CO_TEACHER_CHECKBOX1'];
                    if($_SYSTEM['config']['CO_TEACHER_REPORT_DOE'])
                        $coteacher_cols['CO_TEACHER_REPORT_DOE'] = $_SYSTEM['config']['CO_TEACHER_REPORT_DOE'];

                    for($i = 1; $i <= $coteacher_count; $i++)
                    {
                        $coteacher_array[$i]['CO_TEACHER_ID'] = SelectInput($array['CO_TEACHER_ID'.$i],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CO_TEACHER_ID'.$i.']',null,$teachers,null);
                        if($_SYSTEM['config']['CO_TEACHER_CUSTOM1'])
                        {
                            if($_SYSTEM['config']['select_options']['CO_TEACHER_CUSTOM1'])
                                $coteacher_array[$i]['CO_TEACHER_CUSTOM1'] = SelectInput($array['CO_TEACHER'.$i.'_CUSTOM1'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CO_TEACHER'.$i.'_CUSTOM1]',null,$_SYSTEM['config']['select_options']['CO_TEACHER_CUSTOM1'],null,'style="max-width:300px;"');
                            else
                                $coteacher_array[$i]['CO_TEACHER_CUSTOM1'] = TextInput($array['CO_TEACHER'.$i.'_CUSTOM1'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CO_TEACHER'.$i.'_CUSTOM1]');
                        }
                        if($_SYSTEM['config']['CO_TEACHER_CUSTOM2'])
                        {
                            if($_SYSTEM['config']['select_options']['CO_TEACHER_CUSTOM2'])
                                $coteacher_array[$i]['CO_TEACHER_CUSTOM2'] = SelectInput($array['CO_TEACHER'.$i.'_CUSTOM2'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CO_TEACHER'.$i.'_CUSTOM2]',null,$_SYSTEM['config']['select_options']['CO_TEACHER_CUSTOM2'],null,'style="max-width:300px;"');
                            else
                                $coteacher_array[$i]['CO_TEACHER_CUSTOM2'] = TextInput($array['CO_TEACHER'.$i.'_CUSTOM2'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CO_TEACHER'.$i.'_CUSTOM2]');
                        }
                        if($_SYSTEM['config']['CO_TEACHER_CHECKBOX1'])
                        {
                            if($_SYSTEM['config']['select_options']['CO_TEACHER_CHECKBOX1'])
                                $coteacher_array[$i]['CO_TEACHER_CHECKBOX1'] = SelectInput($array['CO_TEACHER'.$i.'_CUSTOM3'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CO_TEACHER'.$i.'_CUSTOM3]',null,$_SYSTEM['config']['select_options']['CO_TEACHER_CHECKBOX1'],null,'style="max-width:300px;"');
                            else
                                $coteacher_array[$i]['CO_TEACHER_CHECKBOX1'] = CheckboxInput($array['CO_TEACHER'.$i.'_CHECKBOX1'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CO_TEACHER'.$i.'_CHECKBOX1]');
                        }
                        if($_SYSTEM['config']['CO_TEACHER_PERMISSIONS'])
                        {
                            $coteacher_array[$i]['CO_TEACHER_PERMISSIONS'] = SelectInput($array['CO_TEACHER'.$i.'_PERMISSIONS'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CO_TEACHER'.$i.'_PERMISSIONS]',null,$_SYSTEM['config']['select_options']['CO_TEACHER_PERMISSIONS'],null,'style="max-width:300px;"');
                        }
                        if($_SYSTEM['config']['CO_TEACHER_REPORT_DOE'])
                        {
                            $coteacher_array[$i]['CO_TEACHER_REPORT_DOE'] = CheckboxInput($array['CO_TEACHER'.$i.'_REPORT_DOE'],'tables[COURSE_SECTIONS]['.$_REQUEST['course_section_id'].'][CO_TEACHER'.$i.'_REPORT_DOE]');
                        }
                    }
                    $header .= GridoutputBuffered($coteacher_array,$coteacher_cols,'','',null,null,array('xscroll'=>false, 'save'=>false, 'search'=>false));
                    $header .= '</TD></TR></TABLE>';
                }
                $header .= PopTable('footer',null,null,null,null,true);
            }
            DisplayHeader($header);
			//echo '</FORM>';
		}
		elseif((isset($_REQUEST['course_credits']) && SystemPreferences('WEIGHTS')=='Y') || $_REQUEST['course_credits']=='new')
		{  //die('else if 1');
			$sql = "SELECT TITLE
					FROM COURSES
					WHERE COURSE_ID='$_REQUEST[course_id]'";
			$QI = db_execute($sql);
			$array = db_request($QI);
			$array = $array[1];

			$title = $array['TITLE'].' - '.$_REQUEST['course_credits'];

        
        //print_r($title);die('bvbvbv');
        
			if($_REQUEST['course_credits']=='new')
			{
				$title = $array['TITLE'].' - '._('New Course Weight');
				unset($delete_button);
				$array = array('CREDITS'=>SystemPreferences('DEFAULT_CREDITS'));
            //print_r($array);die;
				$div = false;
				$new = true;
				$array['DOES_GPA_1'] = 'Y';
			}
			else
			{
				$array = db_request(db_execute("SELECT COURSE_CREDIT_TITLE,CREDITS,STUDENT_SCHEDULEABLE,STUDENT_REQUESTABLE,DOES_GPA_1,CW_CHECKBOX_SETTING_1,CW_CHECKBOX_SETTING_2,CW_CHECKBOX_SETTING_3,CW_CHECKBOX_SETTING_4,CW_CHECKBOX_SETTING_5 FROM COURSE_CREDITS WHERE COURSE_ID='$_REQUEST[course_id]' AND COURSE_CREDIT_TITLE='$_REQUEST[course_credits]'"));
				$array = $array[1];
				$div = true;
				$new = false;
			}
        
        
     //   die('mnmnmn');

			if($credits_changed!==false)
			{
				$new_credits = $credits_changed;
				$grades_array = db_request(db_execute("SELECT ID FROM STUDENT_GRADES_CARD g,COURSE_SECTIONS cp WHERE g.SCHOOL_YEAR=cp.SCHOOL_YEAR AND g.SCHOOL_YEAR='".get_school_year()."' AND g.COURSE_SECTION_ID=cp.COURSE_SECTION_ID AND cp.COURSE_ID='".$_REQUEST['course_id']."' AND g.CREDITS!='$new_credits'"));
				// COURSE_CREDITS

				if(true)//count($grades_array))
				{
					echo '<DIV id=credits_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;">';
					if($new_credits!=1)
						echo sprintf(_('You just changed %s to %01.2f credits.<BR><BR> Some grades have already been entered for this course in the current school year.  Would you like to change these grades to %01.2f credits?'),$title,$new_credits,$new_credits);
					else
						echo sprintf(_('You just changed %s to 1 credit.<BR><BR> Some grades have already been entered for this course in the current school year.  Would you like to change these grades to 1 credit?'),$title);

					echo '<BR><BR><INPUT type=button value="'._("Don't Change Grades").'" onclick="document.getElementById(\'credits_confirm\').style.display=\'none\';"> &nbsp; &nbsp; &nbsp; <INPUT type=button value="';
					if($new_credits!=1)
						echo sprintf(_('Change Grades to %01.2f credits'),$new_credits);
					else
						echo sprintf(_('Change Grades to 1 credit'),$new_credits);

					echo '" onclick="document.location.href=\'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction=change_grades&new_credits='.$new_credits.'&course_id='.$_REQUEST['course_id'].'&subject_id='.$_REQUEST['subject_id'].'&course_credits='.$_REQUEST['course_credits'].'\';">';

					echo '</DIV>';
				}
			}

			echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_credits=$_REQUEST[course_credits]&useontop=".$_REQUEST['useontop']." method=POST>";
			DisplayHeader($title,'<table><tr><td>'.$search_header.'</td><td>'.$delete_button.$submitButton->createSButton(_('Save')).'</td></tr></table>');
			if((SystemPreferences('STUDENTS_CAN_SCHEDULE')=='Y') || (SystemPreferences('STUDENTS_CAN_REQUEST')=='Y') || isset($_SYSTEM['config']['DOES_GPA_1']))
				$table_width = '100%';
			else
				$table_width = '50%';
			$header .= '<TABLE cellpadding=3 width='.$table_width.'>';
			$header .= '<TR>';


			$header .= '<TD>' . TextInput($array['COURSE_CREDIT_TITLE'],'tables[COURSE_CREDITS]['.$_REQUEST['course_credits'].'][COURSE_CREDIT_TITLE]',_('Course Weight Title'),'maxlength=10') . '</TD>';
			if(SystemPreferences('USE_CREDITS')=='Y')
				$header .= '<TD>' . TextInput($array['CREDITS'],'tables[COURSE_CREDITS]['.$_REQUEST['course_credits'].'][CREDITS]',_('Credits'),'',$div) . '</TD>';
			else
				$header .= '<TD>'._('Credits').'&nbsp;'._('Not Used').'</TD>';

			if(SystemPreferences('STUDENTS_CAN_REQUEST')=='Y')
				$header .= '<TD valign=bottom>' . CheckboxInput($array['STUDENT_REQUESTABLE'],'tables[COURSE_CREDITS]['.$_REQUEST['course_credits'].'][STUDENT_REQUESTABLE]',_('Allow Students to Request this Course'),$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>') . '</TD>';
			if(SystemPreferences('STUDENTS_CAN_SCHEDULE')=='Y')
				$header .= '<TD valign=bottom>' . CheckboxInput($array['STUDENT_SCHEDULEABLE'],'tables[COURSE_CREDITS]['.$_REQUEST['course_credits'].'][STUDENT_SCHEDULEABLE]',_('Allow Students to Enroll themselves in this Course'),$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>') . '</TD>';
  
            if(isset($_SYSTEM['config']['DOES_GPA_1']))
				$header .= '<TD valign=bottom>' . CheckboxInput($array['DOES_GPA_1'],'tables[COURSE_CREDITS]['.$_REQUEST['course_credits'].'][DOES_GPA_1]',$_SYSTEM['config']['DOES_GPA_1'],$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>') . '</TD>';

			$header .= '</TR>';
			$header .= '</TABLE>';
			DisplayHeader($header);
			echo '</FORM>';
		}
		elseif($_REQUEST['course_id'])
		{   //die('heheheh');
       // echo "<pre>";print_r($_REQUEST);die;
            $state_sql = "";
            if(StateFieldsSet("COURSES"))
            { 
                $fields = StateFieldsArray("COURSES");
                if(array_key_exists("CFIELD_2", $fields))
                {
                    $state_sql = ",CFIELD_2";
                }
            }
			if($_REQUEST['course_id']!='new')
			{  
				//$sql = "SELECT TITLE,SHORT_NAME,COMMENTS,GRADE_LEVEL,GRAD_SUBJECT_ID,PREREQUISITES{$state_sql}{$cp_def_fields},C_VISIBLE
                
                $sql = "SELECT TITLE,SHORT_NAME,COMMENTS,GRADE_LEVEL,GRAD_SUBJECT_ID,PREREQUISITES{$state_sql}{$cp_def_fields}
						FROM COURSES
						WHERE COURSE_ID='$_REQUEST[course_id]'";
				$QI = db_execute($sql);
				$array = db_request($QI);
           // echo "<pre>";print_r($array);die;
            
            //print_r($c);
				$array = $array[1];
            //$c= $array['C_VISIBLE'];
            //print_r($c);die;
				$title = $array['TITLE'];
				$div = 'force';
				$new = false;
			}
			else
			{ 
				$sql = "SELECT TITLE
						FROM COURSE_SUBJECTS
						WHERE SUBJECT_ID='$_REQUEST[subject_id]'";
				$QI = db_execute($sql);
				$array = db_request($QI);
				$title = $array[1]['TITLE'].' - '._('New Course');
				unset($delete_button);
				unset($array);
				$div = false;
				$new = true;
				$array['DOES_GPA_1'] = 'Y';
			}
  
        
        //die('iiiiiiii');
			if($credits_changed!==false)
			{//print "CC!=2";
				$new_credits = $credits_changed;
				$grades_array = db_request(db_execute("SELECT ID FROM STUDENT_GRADES_CARD g,COURSE_SECTIONS cp WHERE g.SCHOOL_YEAR=cp.SCHOOL_YEAR AND g.SCHOOL_YEAR='".get_school_year()."' AND g.COURSE_SECTION_ID=cp.COURSE_SECTION_ID AND cp.COURSE_ID='".$_REQUEST['course_id']."' AND g.CREDITS!='$new_credits'"));
				// COURSE_CREDIT_TITLE
//print_r($grades_array);die('dgsdgs');
				if(count($grades_array))
				{
					echo '<DIV id=credits_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;">';
					if($new_credits!=1)
						echo sprintf(_('You just changed %s to %01.2f credits.<BR><BR> Some grades have already been entered for this course in the current school year.  Would you like to change these grades to %01.2f credits?'),$title,$new_credits,$new_credits);
					else
						echo sprintf(_('You just changed %s to 1 credit.<BR><BR> Some grades have already been entered for this course in the current school year.  Would you like to change these grades to 1 credit?'),$title);

					echo '<BR><BR><INPUT type=button value="'._("Don't Change Grades").'" onclick="document.getElementById(\'credits_confirm\').style.display=\'none\';"> &nbsp; &nbsp; &nbsp; <INPUT type=button value="';
					if($new_credits!=1)
						echo sprintf(_('Change Grades to %01.2f credits'),$new_credits);
					else
						echo sprintf(_('Change Grades to 1 credit'),$new_credits);

					echo '" onclick="document.location.href=\'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction=change_grades&new_credits='.$new_credits.'&course_id='.$_REQUEST['course_id'].'&subject_id='.$_REQUEST['subject_id'].'&course_credits='.$_REQUEST['course_credits'].'\';">';

					echo '</DIV>';
				}
			}
			echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&useontop=".$_REQUEST['useontop']." method=POST>";
			DisplayHeader($title,'<table><tr><td>'.$search_header.'</td><td>'.$delete_button.$submitButton->createSButton(_('Save')).'</td></tr></table>');
			$header .= '<TABLE cellpadding=3 width=100% border=0>';
/*			$header .= '<TR><TD colspan=2 background=themes/'.Preferences('HIGHLIGHT_FRAME').'/bottom_shadow.png height=15></TD></TR><TR>';*/

			$header .= '<TD valign=bottom>'.TextInput($array['TITLE'],'tables[COURSES]['.$_REQUEST['course_id'].'][TITLE]',_('Course Title'),null,$div).'</TD>';
                        $header .= '<TD rowspan=5>'.TextAreaInput($array['PREREQUISITES'],'tables[COURSES]['.$_REQUEST['course_id'].'][PREREQUISITES]',_('List of Required Courses')."<A HREF=# onclick='window.open(\"modloader.php?servicemod=".$_REQUEST['servicemod']."&servicefunction=choose_course&reason=prereq&old_id=".$_REQUEST['course_id']."\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'>".'<IMG SRC=images/comment_button.gif border=0 width=20></A>&nbsp;<BR><small>'._('* one Course Number per line'),' id=prereq_field',$div) . '</small></TD>';

//die('uuuuuuuu');

            if(StateFieldsSet("COURSES"))
            {
                $fields = StateFieldsArray("COURSES");
            
                if(array_key_exists("CFIELD_2", $fields))
                {
                    $header .= '<TD valign=bottom>'.TextInput($array['CFIELD_2'],'tables[COURSES]['.$_REQUEST['course_id'].'][CFIELD_2]',$_SYSTEM['config']['COURSES']['CFIELD_2'],null,$div).'</TD>';
                }
            }

//die('dhghsgfhdsgfhhbvh');

            if($_REQUEST['servicefunction']!='choose_course')
			{
				$options = array();
				foreach($subjects_array as $type)
            //                print_r($type);
            
					$options[$type['SUBJECT_ID']] = $type['TITLE'];

				$header .= '</tr><tr><TD valign=bottom>'.SelectInput($array['SUBJECT_ID']?$array['SUBJECT_ID']:$_REQUEST['subject_id'],'tables[COURSES]['.$_REQUEST['course_id'].'][SUBJECT_ID]',_('Subject Title'),$options,false).'</TD>';
			}

			$header .= '</TR><TR><TD valign=bottom>'.TextInput($array['SHORT_NAME'],'tables[COURSES]['.$_REQUEST['course_id'].'][SHORT_NAME]',_('Course Number'),null,$div).'</TD>';
 
        /*
        if($c=='Y'){
        $header .='School'.'<input type="checkbox" name="allow" value=Y checked>';
        }
        
        else{
        $header .='School'.'<input type="checkbox" name="allow" value=Y unchecked>';
        
        }
        */
        // ======= rakesh sharma iomad course cat select box appended for course api (start) ======================//
      
				/*	$cat_query = "SELECT * FROM mdl_course_categories WHERE visible ='1' ";
					$IomadCategories = pg_query($iomadDBconn, $cat_query);
					if (!$IomadCategories) {
  						  echo "An error occurred.\n";
  						  exit;
					}

					$IomadCategories = pg_fetch_all($IomadCategories);
        
       
        $header .= '</tr><tr><TD valign=bottom><label>Course Category</label><select name="iomad_cat_id">';
			foreach($IomadCategories as $key => $val){
			
			$header .=	'<option value="'.$val['id'].'">'.$val['name'].'</option>';
			}
			
		$header .= '</select></TD>';
         */
       // ======= rakesh sharma iomad course cat select box appended for course api ( End ) ======================// 
        
        
			$grad_subjects_array = db_request(db_execute("SELECT ID,TITLE FROM GRADUATION_REQ_SUBJECTS WHERE SCHOOL_ID='".get_school_id()."'"));
        
        
			foreach($grad_subjects_array as $type)
				$options[$type['ID']] = $type['TITLE'];

			$header .= '</TR><TR><TD valign=bottom>'.SelectInput($array['GRAD_SUBJECT_ID'],'tables[COURSES]['.$_REQUEST['course_id'].'][GRAD_SUBJECT_ID]',_('Graduation Requirements Subject'),$options,_('N/A'),null,$div).'</TD>';
			if(SystemPreferences('WEIGHTS')!=='Y')
			{
				if($_REQUEST['course_id']=='new')
				{
					$weight_array[1]['CREDITS'] = SystemPreferences('DEFAULT_CREDITS');
					$_REQUEST['course_credits'] = 'new_course';
				}
				else
				{
					$addition_cw_select = '';
					foreach($new_course_fields as $new_course_field)
					{
						$addition_cw_select .= ','.$new_course_field;
					}
					$weight_array = db_request(db_execute("SELECT CREDITS".$addition_cw_select." FROM COURSE_CREDITS WHERE COURSE_ID='".$_REQUEST['course_id']."'"));
          
                
               // print_r($weight_array);die;
				}
				if(SystemPreferences('USE_CREDITS')=='Y')
					$header .= '</TR><TR><TD valign=bottom>'.TextInput($weight_array[1]['CREDITS'],'tables[COURSE_CREDITS]['.$_REQUEST['course_credits'].'][CREDITS]',_('Credits'),null,$div).'</TD>';
				else
				{
					$header .= '</TR><TR><TD valign=bottom>'._('Credits').'&nbsp;'._('Not Used').'</TD>';
//					$_REQUEST['tables']['COURSE_CREDITS'] = '1';
				}
				if(SystemPreferences('STUDENTS_CAN_REQUEST')=='Y')
					$header .= '</TR><TR><TD valign=bottom>'.CheckboxInput($weight_array[1]['STUDENT_REQUESTABLE'],'tables[COURSE_CREDITS]['.$_REQUEST['course_credits'].'][STUDENT_REQUESTABLE]',_('Allow Students to Request this Course'),$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>').'</TD>';
				if(SystemPreferences('STUDENTS_CAN_SCHEDULE')=='Y')
					$header .= '</TR><TR><TD valign=bottom>' . CheckboxInput($weight_array[1]['STUDENT_SCHEDULEABLE'],'tables[COURSE_CREDITS]['.$_REQUEST['course_credits'].'][STUDENT_SCHEDULEABLE]',_('Allow Students to Enroll themselves in this Course'),$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>').'</TD>';
					
					//die('fgeeeeeeeehwgfhghwg');
					
				if(isset($_SYSTEM['config']['DOES_GPA_1']))
					$header .= '</TR><TR><TD valign=bottom>'.CheckboxInput($weight_array[1]['DOES_GPA_1'],'tables[COURSE_CREDITS]['.$_REQUEST['course_credits'].'][DOES_GPA_1]',$_SYSTEM['config']['DOES_GPA_1'],$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>').'</TD>';
			}

			$header .= '</TR><TR><TD valign=bottom>'.TextInput($array['COMMENTS'],'tables[COURSES]['.$_REQUEST['course_id'].'][COMMENTS]',_('Course Comment'),'size=30',$div).'</TD>';
	
			$header .= '</TR>';

			if(function_exists("_make_cp_course_defaults"))
			{
				$header .= _make_cp_course_defaults();
			}

			$header .= '</TABLE>';
			DisplayHeader($header);
			echo '</FORM>';
		}
		elseif($_REQUEST['subject_id'])
		{   //die('elseif 3');
			if($_REQUEST['subject_id']!='new')
			{
				$sql = "SELECT TITLE,CATEGORY_VISIBLE
						FROM COURSE_SUBJECTS
						WHERE SUBJECT_ID='$_REQUEST[subject_id]'";
				$QI = db_execute($sql);
				$array = db_request($QI);
				$array = $array[1];
            $cat= $array['CATEGORY_VISIBLE'];
           // print_r($cat);
				$title = $array['TITLE'];
			}
			else
			{
				$title = _('New Subject');
				unset($delete_button);
			}

			echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&subject_id=$_REQUEST[subject_id]&useontop=".$_REQUEST['useontop']." method=POST>";
			DisplayHeader($title,'<table><tr><td>'.$search_header.'</td><td>'.$delete_button.$submitButton->createSButton(_('Save')).'</td></tr></table>');
			$header .= '<TABLE cellpadding=3 width=100%>';
			$header .= '<TR>';

			$header .= '<TD>' . TextInput($array['TITLE'],'tables[COURSE_SUBJECTS]['.$_REQUEST['subject_id'].'][TITLE]',_('Title')) . '</TD>';
        
       // print_r($_REQUEST['subject_id']);
       // $header .= '<TD>' . CheckboxInput($array['ALL SCHOOLS'],'tables[COURSE_SUBJECTS]['.$_REQUEST['subject_id'].'][ALL SCHOOLS]',_(' Display in All schools')) . '</TD>';
      
        if($cat=='Y'){
        $header .= 'Allow school'.'<input type="checkbox" name="schoolallow" value=Y checked/>';
        }
        
        else{
        $header .= 'Allow school'.'<input type="checkbox" name="schoolallow" value=Y unchecked/>';
        
        }
        //$header .='Email'.'<input type="email" name="email" value="">';
        
        // print_r($_REQUEST['category_visible']);
      //  print_r($_REQUEST['subject_id']);
        //$v="<InputType=checkbox>";
        
       // print_r($array);
      //  print_r($header);
        /*
   	$header .= '<TD valign=bottom>' . CheckboxInput($array['CATEGORY_VISIBLE'],'tables[COURSE_SUBJECTS]['.$_REQUEST['course_subjects'].']
                [CATEGORY_VISIBLE]',_('Allow category to visible  under all schools'),$checked,$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>'
                                 ,'<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>') . '</TD>';

*/
       
			$header .= '</TR>';
			$header .= '</TABLE>';
			DisplayHeader($header);
			echo '</FORM>';
		}
	}
//die('no if');
	// DISPLAY THE MENU
	$Gridoutput_options = array('save'=>false,'search'=>false,'xscroll'=>false);
	echo "
	<script>
	function viewboxes() {
            var obj=document.getElementById('merge_single');
            if(document.getElementById('merge_single').checked)
            {
        	opener.document.getElementById('hidden_merge_single".$_SESSION['ScdMajorAddSchedule.php']['count']."').value='Y';
        	alert('"._('All course sections which are linked to the already existing course section will be merged with chosen section and its linked course sections!')."');
    	    }
            else
            {
            	opener.document.getElementById('hidden_merge_single".$_SESSION['ScdMajorAddSchedule.php']['count']."').value='N';
        	alert('"._('The chosen only course section will be linked with already existing course sections!')."');
        	//document.getElementById('hidden_merge_single').value='N';
    	    }
//            alert(opener.document.getElementById('hidden_merge_single".$_SESSION['ScdMajorAddSchedule.php']['count']."').value);
        }
	</script>";
	if($_REQUEST['servicemod']!='mod_evaluation/BncCourseProperties.php')
	{
		if($_REQUEST['addition_option']=='merge_sections')
		{
			$orig_cs = _('Original course section').': ';
			$course_title = db_request(db_execute("SELECT TITLE FROM COURSES WHERE COURSE_ID='".$_REQUEST['orig_course_id']."'"));
        
       
	                $course_title = $course_title[1]['TITLE'];
                        $period_title = db_request(db_execute("SELECT TITLE FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='".$_REQUEST['orig_course_section_id']."'"));
                        $period_title = $period_title[1]['TITLE'];
                        $days = array('Mon','Tue','Wed','Thu','Fri','Sat','Sun');
                        foreach($days as $day)
                        {
                                if(strpos($period_title,$day)!==false)
    	                        {
                                        $period_title = str_replace($day,_($day).' ', $period_title);
        	                }
                        }
                        $orig_cs .= $course_title.': '.$period_title;
		}
    
   //die('##########');
		if($_REQUEST['servicefunction']=='choose_course')
			DisplayHeader(_('Courses'));
		if($_REQUEST['has_parent'])
			$left_arg = '<BUTTON onclick="document.location.href=\'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction=choose_course&has_parent='.$_REQUEST['has_parent'].'&course_section_id='.$_REQUEST['has_parent'].'\';">'._('Remove the Parent').'</BUTTON>';
		else
			$left_arg = '';
		if($_REQUEST['addition_option']=='merge_sections' && $_REQUEST['course_id'])
		$left_arg .= _('Allow to merge all course sections').': <INPUT type=checkbox name=merge_single id=merge_single '.$checked.' value=Y onclick="viewboxes()">';
//					$left_arg .= _('Allow to merge all sections within the linking course section and existing course sections').': <INPUT type=checkbox name=merge_single id=merge_single '.$checked.' value=Y onchange="viewboxes()">';

		if(!$_REQUEST['subject_id'] || $_REQUEST['servicefunction']=='choose_course')
			DisplayHeader($left_arg,$search_header);
	}


//die('ddddddddddd');
	if(SystemPreferences('WEIGHTS')=='Y')
		$cell_width = '25%';
	else
		$cell_width = '33%';

	echo '<TABLE width=100% cellspacing=0><TR>';
	if($_REQUEST['addition_option']=='merge_sections')
		echo '<TD COLSPAN=4>'.$orig_cs.'<BR><HR></TD></TR><TR>';

	if(count($subjects_array))
	{
		if($_REQUEST['subject_id'])
		{
			foreach($subjects_array as $key=>$value)
			{
				if($value['SUBJECT_ID']==$_REQUEST['subject_id'])
					$subjects_array[$key]['row_color'] = Preferences('HIGHLIGHT');
			}
		}
	}
//die('lklkkkaaaaa');
	echo '<TD valign=top width='.$cell_width.'>';
	$columns = array('TITLE'=>_('Subject Title'));
//print_r($columns); die;
	$link = array();
	unset($orig_css);
	$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&useontop=".$_REQUEST['useontop'];
	$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID');
//die('ooooooo');
	if($_REQUEST['servicefunction']=='choose_course' && $_REQUEST['addition_option']=='merge_sections')
		$orig_css = "&orig_course_id=$_REQUEST[orig_course_id]&orig_course_section_id=$_REQUEST[orig_course_section_id]";

//die('mmmmmmmm');
	if($_REQUEST['servicefunction']!='choose_course')
		$link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&subject_id=new";
	else
	$link['TITLE']['link'] .= "&servicefunction=$_REQUEST[servicefunction]&merge_single=$_REQUEST[merge_single]&addition_option=$_REQUEST[addition_option]&reason=$_REQUEST[reason]&old_id=$_REQUEST[old_id]$orig_css";

	Gridoutput($subjects_array,$columns,_('Subjects'),_('Amount of Subjects'),$link,array(),$Gridoutput_options);
/*
echo "<pre>";
print_r($subjects_array);
echo "</pre>"; die('llklkkkhgghg'); 
*/
//print_r($columns); die;

//print_r($link);

//die;
	echo '</TD>';

	if($_REQUEST['subject_id'] && $_REQUEST['subject_id']!='new')
	{
		//$sql = "SELECT COURSE_ID,TITLE,SHORT_NAME, C_VISIBLE,COMMENTS FROM COURSES WHERE SUBJECT_ID='$_REQUEST[subject_id]' AND C_VISIBLE='Y' ORDER BY TITLE";
    
    $sql = "SELECT COURSE_ID,TITLE,SHORT_NAME, COMMENTS FROM COURSES WHERE SUBJECT_ID='$_REQUEST[subject_id]'  ORDER BY TITLE";
		$QI = db_execute($sql);
		$courses_array = db_request($QI);
   // echo "<pre>";
    //print_r($courses_array);die;
    /* $courses_array this array printing all the courses under particular subject title **/
   /* 
    echo "<pre>";
    print_r($courses_array);
echo "</pre>"; die('nnnnnnn'); 
*/
		if(count($courses_array))
		{
			if($_REQUEST['course_id'])
			{
				foreach($courses_array as $key=>$value)
				{
					if($value['COURSE_ID']==$_REQUEST['course_id'])
						$courses_array[$key]['row_color'] = Preferences('HIGHLIGHT');
				}
			}
		}

		echo '<TD valign=top width='.$cell_width.'>';
		$columns = array('TITLE'=>_('Course Title'),'SHORT_NAME'=>_('Course Number'),'COMMENTS'=>_('Comments'));
		$link = array();
		$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&subject_id=$_REQUEST[subject_id]$orig_css&useontop=".$_REQUEST['useontop'];
		$link['TITLE']['variables'] = array('course_id'=>'COURSE_ID');
		if($_REQUEST['servicefunction']!='choose_course')
			$link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&subject_id=$_REQUEST[subject_id]&course_id=new";
		else
			$link['TITLE']['link'] .= "&servicefunction=$_REQUEST[servicefunction]&addition_option=$_REQUEST[addition_option]&reason=$_REQUEST[reason]&old_id=$_REQUEST[old_id]";

		Gridoutput($courses_array,$columns,_('Courses'),_('Amount of Courses'),$link,array(),$Gridoutput_options);
		echo '</TD>';
    
//die('jjjjjj');
    
		if($_REQUEST['course_id'] && $_REQUEST['course_id']!='new')
		{

			$sql = "SELECT COURSE_CREDIT_TITLE FROM COURSE_CREDITS WHERE COURSE_ID='$_REQUEST[course_id]'";
       // print_r($sql);
			$QI = db_execute($sql);
        //print_r($QI);
			if(SystemPreferences('WEIGHTS')=='Y')
				$weights_array = db_request($QI);
       //print_r($weights_array);
			if(SystemPreferences('WEIGHTS')=='Y' || count($weights_array)==0)
			{
				$sql = "SELECT COURSE_CREDIT_TITLE FROM COURSE_CREDITS WHERE COURSE_ID='$_REQUEST[course_id]'";
           				$QI = db_execute($sql);
				$weights_array = db_request($QI);
            
           // print_r($weights_array);
				if(count($weights_array))
				{
					if(isset($_REQUEST['course_credits']))
					{
						foreach($weights_array as $key=>$value)
						{
							if($value['COURSE_CREDIT_TITLE']==$_REQUEST['course_credits'])
								$weights_array[$key]['row_color'] = Preferences('HIGHLIGHT');
						}
					}
				}
            
           // die('ccccccc');
				if(SystemPreferences('WEIGHTS')=='Y')
				{
					echo '<TD valign=top width='.$cell_width.'>';
					$columns = array('COURSE_CREDIT_TITLE'=>_('Weight'));
					$link = array();
					$link['COURSE_CREDIT_TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&addition_option=$_REQUEST[addition_option]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]$orig_css&useontop=".$_REQUEST['useontop'];
					$link['COURSE_CREDIT_TITLE']['variables'] = array('course_credits'=>'COURSE_CREDIT_TITLE');
					if($_REQUEST['servicefunction']!='choose_course')
						$link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_credits=new";
					else
						$link['COURSE_CREDIT_TITLE']['link'] .= "&servicefunction=$_REQUEST[servicefunction]";

					Gridoutput($weights_array,$columns,_('Course Weights'),_('Amount of Course Weights'),$link,array(),$Gridoutput_options);
					echo '</TD>';
				}
			}
        
        //die('vvvvvvv');
			if(isset($_REQUEST['course_credits']) && $_REQUEST['course_credits']!='new' && $_REQUEST['servicemod']!='mod_evaluation/BncCourseProperties.php')
			{
				if($_Config['scheduling_multiple_periods']===true && !$_REQUEST['show_children'])
					$sections_extra = ' AND (COURSE_SECTION_ID=PARENT_ID OR PARENT_ID IS NULL) ';
				else
					$sections_extra = '';
				if(Preferences('CALENDAR') == 'Mon')
					$days = array('Mon','Tue','Wed','Thu','Fri','Sat','Sun');
				else
					$days = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

				$sql = "SELECT COURSE_SECTION_ID,TITLE,COALESCE((TOTAL_SEATS-FILLED_SEATS),0) AS AVAILABLE_SEATS FROM COURSE_SECTIONS WHERE COURSE_ID='$_REQUEST[course_id]' AND COURSE_CREDIT_TITLE='$_REQUEST[course_credits]'".$sections_extra." ORDER BY TITLE";
				$QI = db_execute($sql);
				$periods_array = db_request($QI);

				if(count($periods_array))
				{
					foreach($periods_array as $key=>$value)
					{
						if($_REQUEST['course_section_id'])
							if($value['COURSE_SECTION_ID']==$_REQUEST['course_section_id'])
								$periods_array[$key]['row_color'] = Preferences('HIGHLIGHT');
						foreach($days as $day)
						{
							if(strpos($value['TITLE'],$day)!==false)
							{
								$periods_array[$key]['TITLE'] = str_replace($day,_($day).' ',$periods_array[$key]['TITLE']);
							}
						}
					}
				}

          //die('123456');
				echo '<TD valign=top width='.$cell_width.'>';
				$columns = array('TITLE'=>_('Section Title'));
				if($_REQUEST['servicemod']=='mod_curriculum/Curriculum.php')
					$columns += array('AVAILABLE_SEATS'=>_('Available Seats'));
				$link = array();
				$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&addition_option=$_REQUEST[addition_option]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_credits=$_REQUEST[course_credits]&useontop=".$_REQUEST['useontop'];
				$link['TITLE']['variables'] = array('course_section_id'=>'COURSE_SECTION_ID');
				if($_REQUEST['servicefunction']!='choose_course')
					$link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_credits=$_REQUEST[course_credits]&course_section_id=new&useontop=".$_REQUEST['useontop'];
				else
					$link['TITLE']['link'] .= "&servicefunction=$_REQUEST[servicefunction]&reason=$_REQUEST[reason]";

				if($_Config['scheduling_multiple_periods']==true)
					$checkoc_extra = CheckboxOnClick('show_children','Show Children Sections');

				Gridoutput($periods_array,$columns,_('Course Sections').$checkoc_extra,_('Amount of Course Sections').' '.$checkoc_extra,$link,array(),$Gridoutput_options);
				echo '</TD>';
			}
			elseif($_REQUEST['servicemod']!='mod_evaluation/BncCourseProperties.php')
				echo '<TD width='.$cell_width.'></TD>';
		}
		else
			echo '<TD width='.$cell_width.'></TD><TD width='.$cell_width.'></TD>';
	}
	else
		echo '<TD width='.$cell_width.'></TD><TD width='.$cell_width.'></TD><TD width='.$cell_width.'></TD>';

	if($_REQUEST['servicemod']!='mod_evaluation/BncCourseProperties.php')
		echo '</TR></TABLE>';
}
//die('jjjj');

if($_REQUEST['servicemod']=='mod_curriculum/ScdCourseProperties.php' && $_REQUEST['servicefunction']=='choose_course' && $_REQUEST['reason']=='prereq' && $_REQUEST['course_id'])
{
	$course_num_array = db_request(db_execute("SELECT SHORT_NAME,TITLE FROM COURSES WHERE COURSE_ID='".$_REQUEST['course_id']."'"));
	if(!$course_num_array[1]['SHORT_NAME'])
		echo "<script language=javascript>alert(\"".str_replace('"','\"',$course_num_array[1]['TITLE'])._(" does not have a course number.")."\");window.close();</script>";
	else
	{
		echo "<script language=javascript>
		if(opener.document.getElementById(\"innerdivtables[COURSES][".$_REQUEST['old_id']."][PREREQUISITES]\"))
			opener.document.getElementById(\"innerdivtables[COURSES][".$_REQUEST['old_id']."][PREREQUISITES]\").onclick();
		curr_val = opener.document.getElementById(\"textareatables[COURSES][".$_REQUEST['old_id']."][PREREQUISITES]\").value.replace(\"\\r\\n\",\"\\n\").replace(\"\\r\",\"\\n\");
		if(curr_val.length>0 && curr_val.substr((curr_val.length-1),curr_val.length)!=\"\\n\")
			curr_val = curr_val + \"\\n\";

		opener.document.getElementById(\"textareatables[COURSES][".$_REQUEST['old_id']."][PREREQUISITES]\").value = curr_val + \"".$course_num_array[1]['SHORT_NAME']."\\n\";
		window.close();
		</script>";
	}
}
//die('fffffff');
if($_REQUEST['servicemod']=='mod_curriculum/ScdCourseProperties.php' && $_REQUEST['servicefunction']=='choose_course' && $_REQUEST['course_section_id'])
{
	// THIS CANNOT USE $_REQUEST['course_id'] since the "Remove Parent" button doesn't pass course id
	$course_title = db_request(db_execute("SELECT c.TITLE".CCAT."': '".CCAT."cp.TITLE AS TITLE FROM COURSE_SECTIONS cp, COURSES c WHERE c.COURSE_ID=cp.COURSE_ID AND cp.COURSE_SECTION_ID='".$_REQUEST['course_section_id']."'"));
	// COURSE_CREDIT_TITLE
	if($_REQUEST['has_parent']==$_REQUEST['course_section_id'])
		$course_title = _('None').'<INPUT type=hidden name=tables[parent_id] value='.$_REQUEST['course_section_id'].'>';
	else
		$course_title = $course_title[1]['TITLE'].'<INPUT type=hidden name=tables[parent_id] value='.$_REQUEST['course_section_id'].'>';

	echo "<script language=javascript>opener.document.getElementById(\"course_div\").innerHTML = \"$course_title</small>\"; window.close();</script>";
}

/*********************** rakesh course creation in moodle on course updation:  START *********************/
//echo "<pre>";print_r($_REQUEST);die;
if(isset($_REQUEST['course_id']) && $_REQUEST['course_id']!='new' && !empty($_REQUEST['subject_id'])  && $_REQUEST['servicefunction'] != "delete" ){
	$courses_Data_array =	db_request(db_execute("SELECT * FROM COURSES WHERE course_id='".$_REQUEST['course_id']."' and subject_id='".$_REQUEST['subject_id']."'"));
	$courses_Data = $courses_Data_array[1];
			// course_subjects
	$coursesubjects_Data_array =	db_request(db_execute("SELECT * FROM COURSE_SUBJECTS	 WHERE subject_id='".$courses_Data['SUBJECT_ID']."' and school_id='".$courses_Data['SCHOOL_ID']."'"));
	$coursesubjects_Data = $coursesubjects_Data_array[1];
	
			//  ***** course category existence *****  //
	$imdcourse_categorySQL = "SELECT * FROM mdl_course_categories WHERE idnumber='".$coursesubjects_Data['SUBJECT_ID']."' ";
	$imdcourse_categoryQuery = pg_query($iomadDBconn, $imdcourse_categorySQL);
	$imdcourse_category_Data = pg_fetch_all($imdcourse_categoryQuery)[0];
	//db_request(db_execute("UPDATE form2 SET  token='3b4467a551a25ea59f2fc377f2c2a85c' where id='9'"));
	$form2_data =   db_request(db_execute("select * from form2 where id='9'"));
//echo "<pre>";print_r($form2_data);
    $Iomad_API_Data = array();
    $Iomad_API_Data['domain'] = $form2_data[1]['URL'] ;
    $Iomad_API_Data['token'] = $form2_data[1]['TOKEN'] ;  
	if(empty($imdcourse_category_Data)){
    			//create course category in moodle   	
    	 $Iomad_API_Data['function'] = "core_course_create_categories";   // moodle_course_category function
    	 $Iomad_API_Data['name'] = $coursesubjects_Data['TITLE'];
    	 $Iomad_API_Data['parent'] = 1;   // make parent Miscellaneous Category
    	 $Iomad_API_Data['idnumber'] = $coursesubjects_Data['SUBJECT_ID'];
    	 $Iomad_API_Data['description'] = "<p>New Category".$coursesubjects_Data['TITLE']."</p>";
    	 $Iomad_API_Data['descriptionformat'] = 1;   // enable HTML 
  		 include_once($staticpath.'iomadAPI/course_category.php');   
    } else {
    		// check and update course category in moodle
    	if($imdcourse_category_Data['name'] != $coursesubjects_Data['TITLE'] ){
    		$imdcourse_categoryUpdate = "Update mdl_course_categories set name='".$coursesubjects_Data['TITLE']."' Where idnumber='".$coursesubjects_Data['SUBJECT_ID']."' ";
			pg_query($iomadDBconn, $imdcourse_categoryUpdate);
        
        }
	
    }
		//  ***** course existence  *****  //
	$imdcourse_Query = pg_query($iomadDBconn, "SELECT * FROM mdl_course WHERE idnumber='".$courses_Data['COURSE_ID']."'");
	$imdcourse_Data = pg_fetch_all($imdcourse_Query)[0];
		//new created/updated category
	$imdCoursecategory_Query = pg_query($iomadDBconn, "SELECT * FROM mdl_course_categories WHERE idnumber='".$courses_Data['SUBJECT_ID']."'");
	$imdCoursecategory_Data = pg_fetch_all($imdCoursecategory_Query)[0];

    	
	if(empty($imdcourse_Data)){
    	//echo "empty";die;
    	$Iomad_API_Data['function'] = "core_course_create_courses"; 
    	$Iomad_API_Data['fullname'] = $courses_Data['TITLE'];
    	$Iomad_API_Data['shortname'] = $courses_Data['SHORT_NAME'];
    	$Iomad_API_Data['categoryid'] =$imdCoursecategory_Data['id'];
    	$Iomad_API_Data['idnumber'] =$courses_Data['COURSE_ID'] ;
    	$Iomad_API_Data['summaryformat'] = 1;
    	$Iomad_API_Data['format'] = 'topics' ;
    	$Iomad_API_Data['showgrades'] = 1;
    	$Iomad_API_Data['newsitems'] = 5 ;
    	$Iomad_API_Data['maxbytes'] = 100;
    	$Iomad_API_Data['showreports'] = 1;
    	$Iomad_API_Data['groupmode'] = 0;
    	$Iomad_API_Data['groupmodeforce'] = 0;
    	$Iomad_API_Data['defaultgroupingid'] = 0 ;
   // echo "<pre>";print_r($Iomad_API_Data);die;
    			//echo "create course";
    	 include_once($staticpath.'iomadAPI/client1.php'); 
    
    	
    } else {
		//echo "<pre>";print_r($imdcourse_Data);die;
      			//check and update
    	if($imdcourse_Data['fullname'] != $courses_Data['TITLE']  || $imdcourse_Data['shortname'] != $courses_Data['SHORT_NAME'] || $imdcourse_Data['category'] != $imdCoursecategory_Data['id']){
        	$iomad_courseUpdateQuery = "UPDATE mdl_course  SET fullname='".$courses_Data['TITLE']."', category='".$imdCoursecategory_Data['id']."', shortname='".$courses_Data['SHORT_NAME']."'   WHERE idnumber='".$imdcourse_Data['idnumber']."'  ";
			$iomad_userUpdateData = pg_query($iomadDBconn, $iomad_courseUpdateQuery); 
        }  
    }

}
/*********************** rakesh course creation in moodle on course updation:  END*********************/
?>
