<?php

require_once($staticpath.'functions/extra/StudentsFunctional.fnc.php');
include_once($staticpath.'classes/InputButton.php');
include_once($staticpath.'classes/Students.class.php');
include_once($staticpath.'classes/Fields.class.php');
include_once($staticpath.'classes/NumToText.class.php');
include_once($staticpath.'classes/DataElem.class.php');
$DBFields = new DBFields;
$NumToText = new NumToText;
$submitButton = new InputButton;
$Student = new Students;
$DataElements = new DataElements;
$aeupe_url = $_SERVER['HTTP_ORIGIN'].'/acis/ais/';
//die('jii');
if($_REQUEST['write_sess']){
    $_REQUEST['student_id'] = $_SESSION['_REQUEST_vars']['student_id'] = $tmp_REQUEST['student_id'] = $_REQUEST['write_sess'];
    //$_SESSION['_REQUEST_vars']['get_student_id'] = $_SESSION['_REQUEST_vars']['student_id']  = $tmp_REQUEST['student_id'] = $tmp_REQUEST['get_student_id'] = $_SESSION['get_student_id'] = $_REQUEST['STUDENT_ID'] = $_REQUEST['student_id'] = $_REQUEST['write_sess'];
}
//var_dump($tmp_REQUEST);
//var_dump($_SESSION);

//var_dump($_SESSION['tmp_REQUEST']);

//die('dsjbfjsdbfkj');
if(get_student_id() && get_user('PROFILE') == 'applicant')
{
   $verif = db_request(db_execute("select APPLICANT_VERIFIED from app_identify where student_id = '".get_student_id()."'"));
    if($verif[1]['APPLICANT_VERIFIED'] == 'N')
        $_SYSTEM['allow_edit'] = true;
}
//die('hh');
if(!$_REQUEST['include'])
{   
	switch(Preferences('DEFAULT_TAB'))
	{
		case 1:
			$_REQUEST['include'] = 'stugeneralinfotab';
			$_REQUEST['category_id'] = 1;

		break;

		case 2:
			$_REQUEST['include'] = 'stuaddlinfo';
			$_REQUEST['category_id'] = 2;

		break;

		case 3:
			$_REQUEST['include'] = 'stuaddresstab';
			$_REQUEST['category_id'] = 3;
 
		break;

		default:
			$_REQUEST['include'] = 'stuaddlinfo';
			$_REQUEST['category_id'] = Preferences('DEFAULT_TAB');
  
			if (get_user('PROFILE') == 'student')
			{
				$_REQUEST['include'] = 'stugeneralinfotab';
				$_REQUEST['category_id'] = 1;	
			}
		break;
	}
}
//die('gfdfh');
if(!$_REQUEST['category_id'] && $_REQUEST['include']=='stuaddresstab')
	$_REQUEST['category_id'] = 3;
    

if(get_user('PROFILE')=='teacher')
{  
	$can_edit = db_request(db_execute("SELECT ALLOW_TEACHER_MODIFY FROM STUDENT_FIELD_CATEGORIES WHERE ID='".$_REQUEST['category_id']."'"));
	if($can_edit[1]['ALLOW_TEACHER_MODIFY']=='Y')
		$_SYSTEM['allow_edit'] = true;
}
if(get_user('PROFILE')=='student')
{ 
	$can_edit = db_request(db_execute("SELECT ALLOW_STUDENT_MODIFY FROM STUDENT_FIELD_CATEGORIES WHERE ID='".$_REQUEST['category_id']."'"));
	if($can_edit[1]['ALLOW_STUDENT_MODIFY']=='Y')
		$_SYSTEM['allow_edit'] = true;
}
if(get_user('PROFILE')=='applicant')
{ 
//	$can_edit = db_request(db_execute("SELECT ALLOW_STUDENT_MODIFY FROM STUDENT_FIELD_CATEGORIES WHERE ID='".$_REQUEST['category_id']."'"));
//	if($can_edit[1]['ALLOW_STUDENT_MODIFY']=='Y')
//		$_SYSTEM['allow_edit'] = true;
}


if($_REQUEST['servicefunction']=='update' && AllowEdit() && !$_REQUEST['btn_verify'] && !$_REQUEST['btn_refuse'] && !$_REQUEST['btn_copy'])
{  
	if($_REQUEST['month_students'])
	{
		foreach($_REQUEST['month_students'] as $column=>$value)
		{
        
       
			$_REQUEST['students'][$column] = $_REQUEST['year_students'][$column].'-'.$_REQUEST['month_students'][$column].'-'.$_REQUEST['day_students'][$column];
        
			if($_REQUEST['students'][$column]=='--')
				$_REQUEST['students'][$column] = '';
			elseif(!VerifyDate($_REQUEST['students'][$column]))
			{
				unset($_REQUEST['students'][$column]);
				$note = _("The invalid date could not be saved.");
			}
		}
	}
	unset($_REQUEST['day_students']); unset($_REQUEST['month_students']); unset($_REQUEST['year_students']);
	if(($_REQUEST['students'] || $_REQUEST['values']) && AllowEdit())
	{
		if($_REQUEST['student_id'] && $_REQUEST['student_id']!='new')
			$students_extra = " AND STUDENT_ID!='".$_REQUEST['student_id']."'";

 
		if($_REQUEST['students']['USERNAME'])
		{
			$username = $_REQUEST['students']['USERNAME'];
			$i = '';
			do
			{
				$_REQUEST['students']['USERNAME'] = $username.$i;
				$i++;
			}
			while(count(db_request(db_execute("SELECT STUDENT_ID FROM STUDENTS WHERE USERNAME='".$_REQUEST['students']['USERNAME']."'".$students_extra))) || count(db_request(db_execute("SELECT '' FROM ADDRESS WHERE USERNAME='".$_REQUEST['students']['USERNAME']."'"))) || count(db_request(db_execute("SELECT '' FROM USERS WHERE USERNAME='".$_REQUEST['students']['USERNAME']."'"))));
		}
		if($_REQUEST['student_id'] && $_REQUEST['student_id']!='new')
		{
			$go = true;
			if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php' && count($_REQUEST['students']))
			{
				if($_REQUEST['students'][$Student->getAIDfield()])
				{
					$aid_check_array = db_request(db_execute("SELECT ID_TITLE,STUDENT_ID,APPLICANT_ID FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' AND ID_TITLE = '".$_REQUEST['students'][$Student->getAIDfield()]."'"),array(),array());

					if($aid_check_array[1]['ID_TITLE'] == $_REQUEST['students'][$Student->getAIDfield()] && get_student_id() == $aid_check_array[1]['STUDENT_ID'])
					{
					}
					elseif(count($aid_check_array))
					{
						$error_aid = _('Applicant Unique ID could not be saved, this ID already present in the system.');
						unset($_REQUEST['students'][$Student->getAIDfield()]);
					}
					else
					{
						$app_id = substr($_REQUEST['students'][$Student->getAIDfield()],-3);
						$app_id = intval($app_id);
						if($app_id > 0)
							db_execute("UPDATE APP_IDENTIFY SET ID_TITLE = '".$_REQUEST['students'][$Student->getAIDfield()]."', APPLICANT_ID = '$app_id' WHERE STUDENT_ID = '".get_student_id()."'");
						else
						{
							$error_aid = _('Invalid AID counter');
							unset($_REQUEST['students'][$Student->getAIDfield()]);
						}
					}
				}
			}
			if($_REQUEST['students'])
			{
		                $date = get_db_date();
                		$user = get_user('USER_ID');
		                $last_updated_sql = "LAST_UPDATED_DATE='{$date}',LAST_UPDATED_USER='{$user}',";

				$sql = "UPDATE STUDENTS SET $last_updated_sql";

				/* ---------- Edit Rules Block start ---------------*/
				/*
					already, we have this array with the old values. If user changed one of it
					we will add its new value into the array
				*/
				foreach($_REQUEST['students'] as $column_name=>$value)
				{
					$_SESSION['customValues'][$column_name] = $value;
					$fieldId = explode('CFIELD_',$column_name);
					$fieldIdArr[] = $fieldId[1];
				}
				/*
					now we have the array with field id's, we will use it for search the Edit Rules
				*/
				$resWithEdits = _getAllEditsRules($fieldIdArr, 2);

				$border = array();
				$go = true;
				/* check user values using Edits Rules when we try to add a new student */
				$errorArr = _executeEditRulesAndGetMsg($_REQUEST['students'], 'students', $resWithEdits);
				/* ---------- Edit Rules Block end ---------------*/
				foreach($_REQUEST['students'] as $column_name=>$value)
				{
                                        if($column_name == 'PASSWORD' && $_Config['EncriptPassword'] == true)
                                            $value = Encript($value);
					if(!is_array($value))
						$sql .= "$column_name='".str_replace("\'","''",str_replace('``','"',$value))."',";
					else
					{
						$sql .= $column_name."='||";
						foreach($value as $val)
						{
							if($val)
								$sql .= str_replace("\'","''",str_replace('``','"',$val)).'||';
						}
						$sql .= "',";
					}
				}

				/*
					if there are some errors, in this part, we will just return $go = false
				*/
				$go = _showErrorWarningMsg($errorArr);
				if($_REQUEST['override'] == true AND $_SESSION['overrideDisabled'])
				{
					/*
						if user click on the 'Override' button, we will unset all
						override error messages and a red border for this field
					*/
					unset($_SESSION['overrideDisabled']);
					unset($errorArr['override_error']);
					unset($forceFieldName);
					unset($border);
					$go = true;
				}

				$sql = substr($sql,0,-1) . " WHERE STUDENT_ID='$_REQUEST[student_id]'";
            //echo $sql;die;
				if($go)
					db_execute($sql);
			}
                        if($_REQUEST['values']['STUDENT_REGISTRATION'][get_student_id()])
			{
				$sql = "UPDATE STUDENT_REGISTRATION SET ";
				foreach($_REQUEST['values']['STUDENT_REGISTRATION'][get_student_id()] as $column_name=>$value)
					$sql .= "$column_name='".str_replace("\'","''",str_replace("&rsquo;","''",$value))."',";
				$sql = substr($sql,0,-1) . " WHERE STUDENT_ID='$_REQUEST[student_id]' AND SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'";
				db_execute($sql);
			}
		}
		else
		{
			if(SystemPreferences('AUTO_STUDENT_USERNAMES')=='Y' && !$_REQUEST['students']['USERNAME'])
			{
	//			$username = substr($_REQUEST['students']['FIRST_NAME'],0,1).substr($_REQUEST['students']['LAST_NAME'],0,4);
				mb_internal_encoding("UTF-8");
				$username = mb_substr($_REQUEST['students']['FIRST_NAME'],0,1).mb_substr($_REQUEST['students']['LAST_NAME'],0,40);
				$i = '';
				do
				{
					$_REQUEST['students']['USERNAME'] = $username.$i;
					$i++;
				}
				while(count(db_request(db_execute("SELECT STUDENT_ID FROM STUDENTS WHERE USERNAME='".$_REQUEST['students']['USERNAME']."'"))) || count(db_request(db_execute("SELECT '' FROM ADDRESS WHERE USERNAME='".$_REQUEST['students']['USERNAME']."'"))) || count(db_request(db_execute("SELECT '' FROM USERS WHERE USERNAME='".$_REQUEST['students']['USERNAME']."'"))));

			}
			if(!$_SESSION['temp_file']) $_SESSION['temp_file'] = array();
                        foreach($_SESSION['temp_file'] as $field_name=>$value)
                            $_REQUEST['students'][$field_name] = $value;
                        $_SESSION['temp_file'] = array();
			/* ---------- Edit Rules Block start ---------------*/
			/*
			   we need this array, because admin (user) can use in the Edits rule
			   condition with the field name. So, we will make a foreach and will have
			   the required for us values
			*/

			$_SESSION['customValues'] = _makeInternalArrayWithCustomFields($_REQUEST['students']);
			/*
				save all user values into the $_SYSTEM
			*/
			_saveStudentEnteredValues($_REQUEST);

			$fieldIdArr = _getIDsForEditRules($_REQUEST['students'], 'students');
			/*
				now we have the array with field id's, we will use it for search the Edit Rules
			*/
			$resWithEdits = _getAllEditsRules($fieldIdArr, 2);

			$go = true;
			/* check user values using Edits Rules when we try to add a new student */
			$errorArr = _executeEditRulesAndGetMsg($_REQUEST['students'], 'students', $resWithEdits);
			/* ---------- Edit Rules Block end ---------------*/

			$required_violation = 0;
			if(!$_REQUEST['students']['LAST_NAME'])
			{
				$required_violation++;
				$required_text .= _('Last Name').', ';
			}
			if(!$_REQUEST['students']['FIRST_NAME'])
			{
				$required_violation++;
				$required_text .= _('First Name').', ';
			}
     //   die('kkkk');
			if(!$_REQUEST['values']['STUDENT_REGISTRATION']['new']['CLASSLEVEL_ID'] && $_REQUEST['servicemod']!=='mod_apply/AddApp.php' && $_REQUEST['servicemod']!=='mod_apply/Applicants.php')
			{
				$required_violation++;
				$required_text .= _('Class Level').', ';
			}
			if(!$_REQUEST['values']['STUDENT_REGISTRATION']['new']['CALENDAR_ID'] && $_REQUEST['servicemod']!=='mod_apply/AddApp.php' && $_REQUEST['servicemod']!=='mod_apply/Applicants.php')
			{
				$cal_array = db_request(db_execute("SELECT TITLE FROM SCHOOL_CALENDARS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
				if(count($cal_array))
				{
					$required_violation++;
					$required_text .= _('School Calendar').', ';
				}
			}

        
        
      //  die('sdbhfdgh');
			/*
				we may have the required fields from other categories
			*/
			$required_fields_array = db_request(db_execute("SELECT ID,TYPE,TITLE,REQUIRED FROM STUDENT_FIELDS cf LEFT JOIN STUDENT_FIELDS_IN_CATS sfjc
								ON sfjc.field_id = cf.ID AND sfjc.category_id = cf.category_id WHERE TYPE!='radio' AND REQUIRED='Y' OR cf.ID IN (sfjc.field_id)"));

                        
			foreach($required_fields_array as $field)
			{
				if($field['REQUIRED'] && $_Config['app_exclude_fields'])
				{
					if($field['ID'] && !in_array($field['ID'], $_Config['app_exclude_fields']))// && $_REQUEST['servicemod']=='mod_apply/AddApp.php' && $_REQUEST['servicemod']=='mod_apply/Applicants.php')
						if(!$_REQUEST['students']['CFIELD_'.$field['ID']] && $field['TYPE']<>'faculty')
						{
							$required_violation++;
							$required_text .= $field['TITLE'].', ';
						}
				}
			}
			
			if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
			{
				$rv_msg1 = _('The applicant was not added because ');
				$rv_msg2 = _('The applicant was not added because the required fields are not filled: ');
				$rv_msg3 = _('That Applicant ID number is already taken. Select a different one.');
			}
			else
			{
				$rv_msg1 = _('The student was not added because ');
				$rv_msg2 = _('The student was not added because the required fields are not filled: ');
				$rv_msg3 = _('That Student ID number is already taken. Select a different one.');
			}
			if($required_violation==1)
			{
				$errorArr['err'][] = $rv_msg1.substr($required_text,0,-2)._(' is a required field. You have to fill this field in and try again.');
				$go = false;
			}
			elseif($required_violation)
			{
				$errorArr['err'][] = $rv_msg2.substr($required_text,0,-2).'. '._('You have to fill these fields in and try again.');
				$go = false;
			}

			if($_REQUEST['assign_student_id'])
			{
				$student_id = $_REQUEST['assign_student_id']+0;
				if(count(db_request(db_execute("SELECT STUDENT_ID FROM STUDENTS WHERE STUDENT_ID='$student_id'"))))

					$errorArr['err'][] = $rv_msg3;
			}
			elseif($go)
			{
				/*do
				{
					$student_id = db_request(db_execute('SELECT '.db_seq_nextval('STUDENTS_SEQ').' AS STUDENT_ID '.FROM_DUAL));
					$student_id = $student_id[1]['STUDENT_ID'];
				}
				while(count(db_request(db_execute("SELECT STUDENT_ID FROM STUDENTS WHERE STUDENT_ID='$student_id'"))));
                                 * 
                                 */
                            $student_id = db_request(db_execute('SELECT '.db_seq_nextval('STUDENTS_SEQ').' AS STUDENT_ID '.FROM_DUAL));
                            if($DBType == 'mssql')
                        	    $student_id = $student_id[1]['STUDENT_ID'];
                            else
                        	    $student_id = $student_id[1]['STUDENT_ID']+1;
			}
			/*
				if there are some errors, in this part, we will just return $go = false,
				but will setup $show as true, because we need to show the additional message
				'The record was not added. Please, correct...'
			*/
			$go = _showErrorWarningMsg($errorArr);

			$show = true;
			if($_REQUEST['override'] == true AND $_SESSION['overrideDisabled'])
			{
				unset($_SESSION['overrideDisabled']);
				$go = true;
			}
                        $sql = "INSERT INTO STUDENTS ";
			$fields = 'STUDENT_ID,';
			$values = "'$student_id',";
                        if($DBType == 'mssql')
                        {
                            $id_corrector = $Student->getIdCorrector();
                            $fields .= 'ID_CORRECTOR,';
                            $values .= "'$id_corrector',";
                        }
                        
                        $fields = ($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?$fields.'PROFILE,':$fields;
                        $values = ($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?$values."'applicant',":$values;
                        $fields = ($_REQUEST['servicemod']=='mod_students/AddStud.php' || $_REQUEST['servicemod']=='mod_students/Students.php')?$fields.'PROFILE,':$fields;
                        $values = ($_REQUEST['servicemod']=='mod_students/AddStud.php' || $_REQUEST['servicemod']=='mod_students/Students.php')?$values."'student',":$values;
        
        
      //  print_r($values);die;
			if(empty($_REQUEST['students']['FORCE_PASSWORD_CHANGE']))
				$_REQUEST['students']['FORCE_PASSWORD_CHANGE'] = 'N';

			foreach($_REQUEST['students'] as $column=>$value)
			{
				if($value)
				{
					$fields .= $column.',';
					if(!is_array($value))
						$values .= "'".str_replace("\'","''",$value)."',";
					else
					{
						$values .= "'||";
						foreach($value as $val)
						{
							if($column=="STUDENT_ID")
								$value += 0;
							if($val)
								$values .= $val.'||';
						}
						$values .= "',";
					}
				}
			}

			$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
	       
        	   //=========== rakesh user create api  ( START )   ============//
        	$form2_data =   db_request(db_execute("select * from form2 where id='9'"));
      		//print_r($_REQUEST['students']);die;
        	$courseData_Iomad = array();
        	$courseData_Iomad['domain'] = $form2_data[1]['URL'] ;
            $courseData_Iomad['token'] = $form2_data[1]['TOKEN'] ;  
            $courseData_Iomad['function'] = "core_user_create_users"; 
        	$required_fields = array('STUDENT_ID','USERNAME','PASSWORD','FIRST_NAME','MIDDLE_NAME','LAST_NAME','CFIELD_2');
        	foreach($_REQUEST['students'] as $key =>$val){
            	if(in_array($key,$required_fields)){
                	if($key == 'CFIELD_2'){
                    $courseData_Iomad['EMAIL'] = $val;
                    	continue;
                    }
            		$courseData_Iomad[$key] = $val;
                }
            }
        
        	$courseData_Iomad['idnumber'] =$courseData_Iomad['EMAIL'];
         	//echo "<pre>";print_r();echo "</pre>";
        	
  		// echo "<pre>";print_r($courseData_Iomad);die;
         //=========== rakesh user create api  ( End )   ============//
       
			if($go)
			{
            
            	if(empty($_REQUEST['student_id']) && !empty($_REQUEST['students'])){ 
                		$stdsReqFlds = array();
                		//$_REQUEST['EMAIL'] = $_REQUEST
                   		 $req_fileds = array('FIRST_NAME','LAST_NAME','USERNAME','CFIELD_2','PASSWORD');
                		foreach($_REQUEST['students'] as $key => $val){
                          	 if(empty($val) && in_array($key,$req_fileds)){
                           		  if($key == "CFIELD_2"){
                                  		$userReqFlds['EMAIL'] = "EMAIL";
                                  		continue;
                                  }
                                  $userReqFlds[$key] = $key;
                           	 }
                        }
                		if(!empty($userReqFlds)){
                          	foreach($userReqFlds as $key => $val){
                             	 echo "<strong>".$val."<strong> field is required..<br>";
                           	}
                          	 unset($userReqFlds);
                          	 die;
                   		 }
                		$sql .= " RETURNING *";
                		//echo $sql;die;
                		$new_stdData = db_request(db_execute($sql));
                		$iomad_userDataQuery = "SELECT * FROM mdl_user WHERE username ='".$new_stdData[1]['USERNAME']."' OR email='".$new_stdData[1]['CFIELD_2']."' ";
              			$iomad_userData = pg_query($iomadDBconn, $iomad_userDataQuery);
		      			$iomad_userDetials = pg_fetch_all($iomad_userData);
           					// user doesn't exist in moodle
            			if(empty($iomad_userDetials)) {
            		  		include_once($staticpath.'iomadAPI/newUser.php');   //   moodle user create api                  
               			 } else {
                        	db_execute("Delete from students where student_id='". $new_stdData[1]['student_id']."' ");
                        	die("STUDENT already exists...");
                        }
                	
               	 } else {
                		db_execute($sql);
                 }
               
            	//die('hehhehe');
			}
            //die('helelleleo');
                        //$id_corrector
                        if($DBType == 'mssql')
                            $student_id = $Student->FixStudentID($student_id,$id_corrector);

                        $_SESSION['get_student_id'] = $student_id;
                        $_SESSION['student_id'] = $student_id;
                        
			$idnt_new = false;
                        if($_REQUEST['servicemod']=='mod_students/Students.php')
                        {
                            $sql_add="INSERT INTO student_lf_data(student_field_id,student_id,school_id,log_field1)
                                                                VALUES('999999','".get_student_id()."','".get_school_id()."','1')";
                            db_execute($sql_add);
                        }
			if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
			{
			        $school_id =($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?get_apply_school_id():get_school_id();
			        if($_Config['aid_spec'] === true)
			        {
			    		foreach($_REQUEST['faculty']['new'] as $fcount=>$finfo)
			    		{
			    			if($finfo['PRIORITY'] == '1')
					    		$nspecialty_id = $finfo['SPECIALTY_ID'];
			    		}
				        $spec_id = "AND CFIELD_1 = '$nspecialty_id'";
				        $uaid_field = 'CFIELD_1,';
				        $uaid_value = "'".$nspecialty_id."',";
				}
				if($_Config['AID']['SCHOOL_UNIQUE'] === true)
					$su_sql = "AND SCHOOL_ID = '".$school_id."'";
				$app_max_id = db_request(db_execute("SELECT MAX(APPLICANT_ID) AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' $su_sql $spec_id"));
//				var_dump($app_max_id);
				$app_max_id = $app_max_id[1]['MAX'];
				if(!$app_max_id || $app_max_id == '')
					$app_max_id = 1;
				else
					$app_max_id = $app_max_id+1;
//				echo "===>".$app_max_id;
				$sql = "INSERT INTO APP_IDENTIFY ";
				$fields = 'ID,STUDENT_ID,SCHOOL_YEAR,SCHOOL_ID,APPLICANT_ID,APPLICANT_VERIFIED,VFD_USER_ID,VFD_USER_NAME,REG_DATE,'.$uaid_field;
				$values = "".db_seq_nextval('APP_IDENTIFY_SEQ').",'$student_id','".get_school_year()."','".$school_id."','$app_max_id','Y','".get_user('USER_ID')."','".get_teacher_fullname(get_user('USER_ID'),'','FULL_NAME','true')."','".get_db_date()."',$uaid_value";
		//	print_r($values);die;
            
            $sql .= '('.substr($fields,0,-1).') values('.substr($values,0,-1).')';
		//		echo $sql;
				$idnt_new = true;
				if($go)
					db_execute($sql);
                                $sql_add_newlog="INSERT INTO student_lf_data(student_field_id,student_id,school_id,log_field1)
                                        VALUES('999999','".get_student_id()."','".get_school_id()."','1')";
                                        db_execute($sql_add_newlog);
				$enr_codes = db_request(db_execute("SELECT VALUE,TITLE FROM SYSTEM_CONFIG WHERE PROGRAM = 'applicants' AND SCHOOL_ID = '".get_school_id()."'"),
                                        array(),array('TITLE'));
				
            //print_r($enr_codes);die;
            
            if($enr_codes['DEF_ADM_ENR_ID'][1]['VALUE'])
				{
					$enr_code = "'".$enr_codes['DEF_ADM_ENR_ID'][1]['VALUE']."',";
					$enr_field = 'ENROLLMENT_CODE,';
            
            
           // print_r($enr_field);die;
				}
			}

			$sql = "INSERT INTO STUDENT_REGISTRATION ";
			$fields = 'ID,STUDENT_ID,SCHOOL_YEAR,SCHOOL_ID,'.$enr_field;
			$values = "";
                        $fields = ($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?$fields.'CFIELD_15,':$fields;
                        $fields = ($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?$fields.'CFIELD_16,':$fields;
                        $school_id =($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?get_apply_school_id():get_school_id();
			if($go)
                        {
				$values = "".db_seq_nextval('STUDENT_REGISTRATION_SEQ').",'$student_id','".get_school_year()."','".$school_id."',$enr_code";
                                $values = ($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?$values."'byoperator',":$values;
                                $values = ($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?$values."'".get_user('USER_ID')."',":$values;
                        }

	                //Replaced $_REQUEST in the left side of equation whith the $_POST - (Whith the $_REQUEST - doesn't work) //$_REQUEST['values']['STUDENT_REGISTRATION']['new']['START_DATE'] = $_POST['day_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$_POST['month_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$_POST['year_values']['STUDENT_REGISTRATION']['new']['START_DATE'];
			//$_REQUEST['values']['STUDENT_REGISTRATION']['new']['START_DATE'] = get_db_date($DBType, strtotime($_POST['year_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$_POST['month_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$_POST['day_values']['STUDENT_REGISTRATION']['new']['START_DATE']));
                        if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
                        	$_REQUEST['values']['STUDENT_REGISTRATION']['new']['START_DATE'] = date("Y-m-d");
                        else
                        	$_REQUEST['values']['STUDENT_REGISTRATION']['new']['START_DATE'] = $_POST['year_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$_POST['month_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$_POST['day_values']['STUDENT_REGISTRATION']['new']['START_DATE'];

			foreach($_REQUEST['values']['STUDENT_REGISTRATION']['new'] as $column=>$value)
			{
            
            //print_r($value);die;
				if($value)
				{
					$fields .= $column.',';
					$values .= "'".str_replace("\'","''",$value)."',";
				}
			}
			$sql .= '('.substr($fields,0,-1).') values('.substr($values,0,-1).')';
        
        
       // print_r($sql);die;

			if($go)
			{
				db_execute($sql);
				$_REQUEST['student_id'] = $student_id;
				$_SESSION['student_id'] = $student_id;
	                        if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
					$_SESSION['is_applicant'] = 'applicant';
				$_REQUEST['category_id'] = Preferences('DEFAULT_TAB');
				if(Preferences('DEFAULT_TAB')!=3)
				{
					$address_dont_display = true;
					include($staticpath.'modules/mod_students/includes/stuaddresstab.inc.php');
					$address_dont_display = false;
				}
			}
			else
			{
				$_REQUEST['student_id'] = 'new';
				$_SESSION['student_id'] = $student_id;
				/*
					if we don't do it, we will get the sql error from the stuaddresstab.inc.php
					(Additional Information:
						ERROR: null value in column "student_id" violates not-null constraint)
					Before we used the js alert, and it worked well, but now we need this
				*/
				unset($_REQUEST['address_id']);
				unset($_REQUEST['existing_address_id']);
				unset($_REQUEST['values']['STUDENT_RELATIONS']);
			}
			$new_student = true;
			if(Preferences('DEFAULT_TAB')!=1 && !$errorArr)
			{
				switch(Preferences('DEFAULT_TAB'))
				{
					case 2:
						$_REQUEST['include'] = 'stuaddlinfo';
						$_REQUEST['category_id'] = 2;
					break;

					case 3:
						$_REQUEST['include'] = 'stuaddresstab';
						$_REQUEST['category_id'] = 3;
					break;

					default:
						$_REQUEST['include'] = 'stuaddlinfo';
						$_REQUEST['category_id'] = Preferences('DEFAULT_TAB');
					break;
				}
			}
		}
	}



//die('sdgarhereh');
        /*
		has added the $_REQUEST['..._faculty'] because if we have only the data fields, they will not be
		saved
	*/
        //$_REQEST['prev_servicemod']
        if($_REQUEST['servicemod']=='mod_apply/Applicants.php' && $_REQUEST['student_id']!='new')
        {
	        $spec_cnt = db_request(db_execute("SELECT COUNT(*) AS CNT FROM STUDENT_SPEC_FIELDS WHERE STUDENT_ID = '".get_student_id()."'"),array(),array());
	}
	$nspec = false;
        if($_REQUEST['prev_servicemod']=='mod_apply/AddApp.php')
        	$_REQUEST['faculty'] = $_REQUEST['faculty']['new'];
        if($_REQUEST['faculty'] && $_POST['faculty'])
	{
            unset($columns);
            foreach ($_REQUEST['faculty'] as $id=>$columns)
            {
        	$spec_new = $id;
                if(substr($id,0,3)!='new' && $_REQUEST['prev_servicemod']!=='mod_apply/AddApp.php' || $_REQUEST['servicemod']!=='mod_apply/Applicants.php')
                {
                    $sql = "UPDATE STUDENT_SPEC_FIELDS SET ";
                    if(count($columns) && $columns['GROUP_ID']<>'')
                    {
                        $go = false;
                        unset($fields);
                        unset($values);
			foreach($columns as $column=>$value)
			{
                            if($column == 'TYPE_OF_STUDY')
                            {
                            //    $value = ','.implode(',',$value).',';
                                $go = true;
                            }
                            if($column == 'EDU_FORM_ID' && $columns['GROUP_ID']<>'' && $value<>'')
                            {
                                $SQL=db_execute("SELECT ID,EDU_FORM_ID FROM EDU_FORMS_IN_GROUPS WHERE STUDENT_ID='".get_student_id()."' AND GROUP_ID='".$columns['GROUP_ID']."' AND SCHOOL_YEAR='".get_school_year()."'");
                                $RESULT = db_request($SQL,array(),array());
                                if($RESULT[1]['ID']<>'')
                                {
                                    db_execute("UPDATE EDU_FORMS_IN_GROUPS SET EDU_FORM_ID = '".$value."' WHERE ID = '".$RESULT[1]['ID']."'");
                                    db_execute("UPDATE STUDENT_SPEC_FIELDS SET EDU_FORM_ID = '".$value."' WHERE STUDENT_ID = '".get_student_id()."' AND GROUP_ID = '".$columns['GROUP_ID']."' AND SCHOOL_YEAR='".get_school_year()."'");//ID = '".$RESULT[1]['ID']."'
                                }
                                else
                                {
                                    db_execute("INSERT INTO EDU_FORMS_IN_GROUPS (ID,STUDENT_ID,EDU_FORM_ID,GROUP_ID,SCHOOL_YEAR) VALUES(".  db_seq_nextval('EDU_FORMS_IN_GROUPS_seq').",'".get_student_id()."','".$value."','".$columns['GROUP_ID']."','".get_school_year()."')");
                                    db_execute("UPDATE STUDENT_SPEC_FIELDS SET EDU_FORM_ID = '".$value."' WHERE STUDENT_ID = '".get_student_id()."' AND GROUP_ID = '".$columns['GROUP_ID']."' AND SCHOOL_YEAR='".get_school_year()."'");//ID = '".$RESULT[1]['ID']."'
                                }
                                continue;
                            }
                            if($column == 'PRIORITY' && $columns['TYPE_OF_STUDY']<>''){
                                $value = intval($value);
                                $go = true;
                            }
			    //это надо чтоб заапдейтить CFIELD_1 в APP_IDENTIFY
                            if($column == 'PRIORITY' && $value == '1')
                            {
                                foreach($columns as $column=>$value)
	                    		if($column == 'PRIORITY' && $value == '1')
	                    			$nspecialty_id = $columns['SPECIALTY_ID'];
                            }
                            if($value<>'')
                                $sql .= $column."='".str_replace("\'","''",$value)."',";
			}
                        
			$sql = substr($sql,0,-1) . " WHERE ID='$id' AND  SCHOOL_YEAR='".get_school_year()."'";
                        if($go)
                        {
                            db_execute($sql);
//                            echo $sql;
                        }
                        else
                            $errorArr['err'][] = _('Form of education has not been chosen');
                        //unset($_REQUEST['faculty']);
                        //var_dump($_REQUEST['faculty']);
                        //var_dump($sql);
                        //die();
                        $upd_idnt = false;
                        if($_Config['aid_spec'] === true)
                        {
	                        foreach($columns as $column=>$value)
	                        {
	                    		if($column == 'PRIORITY' && $value == '1')
	                    		{
	                    			$nspecialty_id = $columns['SPECIALTY_ID'];
//	                    			var_dump($nspecialty_id);
	                    			$upd_idnt = true;
	                    		}
	                        }
	                }
                        
                    }
//                    $Student->_setappSchool_array();
                }
                else
                {
                    //var_dump($columns);
                    if(count($columns) && $columns['GROUP_ID']<>'')
                    {
                        if(!$student_id) $student_id = get_student_id();
                        $go =false;
                        if(!$sql_start[$index])
                            $sql_start[$index] = "INSERT INTO STUDENT_SPEC_FIELDS (STUDENT_ID,SCHOOL_YEAR, ";
                        if(!$sql_values[$index])
                            $sql_values[$index] = "'".$student_id."','".get_school_year()."',";
                        unset($fields);
                        unset($values);
                        
                        foreach($columns as $column=>$value)
                        {
                            //var_dump($column,$value);
                            if($column == 'EDU_FORM_ID' && $columns['GROUP_ID']<>'' && $value<>'')
                            {
                                //var_dump($value);
                                //var_dump($columns['GROUP_ID']);
                                $SQL=db_execute("SELECT ID,EDU_FORM_ID FROM EDU_FORMS_IN_GROUPS WHERE STUDENT_ID='".$student_id."' AND GROUP_ID='".$columns['GROUP_ID']."' AND SCHOOL_YEAR='".get_school_year()."'");
                                $RESULT = db_request($SQL,array(),array());
                                if($RESULT[1]['ID']<>'')
                                {
                                    db_execute("UPDATE EDU_FORMS_IN_GROUPS SET EDU_FORM_ID = '".$value."' WHERE ID = '".$RESULT[1]['ID']."'");
                                    db_execute("UPDATE STUDENT_SPEC_FIELDS SET EDU_FORM_ID = '".$value."' WHERE STUDENT_ID = '".$student_id."' AND GROUP_ID = '".$columns['GROUP_ID']."' AND SCHOOL_YEAR='".get_school_year()."'");//ID = '".$RESULT[1]['ID']."'
                                }
                                else
                                {
                                    $insert = "INSERT INTO EDU_FORMS_IN_GROUPS (ID,STUDENT_ID,EDU_FORM_ID,GROUP_ID,SCHOOL_YEAR) VALUES(".db_seq_nextval('EDU_FORMS_IN_GROUPS_seq').",'".$student_id."','".$value."','".$columns['GROUP_ID']."','".get_school_year()."')";
                                    db_execute($insert);
                                    db_execute("UPDATE STUDENT_SPEC_FIELDS SET EDU_FORM_ID = '".$value."' WHERE STUDENT_ID = '".$student_id."' AND GROUP_ID = '".$columns['GROUP_ID']."' AND SCHOOL_YEAR='".get_school_year()."'");//ID = '".$RESULT[1]['ID']."'
                                }
                                //var_dump($insert);
                                //continue;
                            }
                            if($column == 'TYPE_OF_STUDY' && $value<>''){
                                $go = true;
                            //    $value = ','.implode(',',$value).',';
                            }
                            //elseif($column == 'unit_id')
//                                $column = 'SCHOOL_ID';

                            $fields[$index] = $fields[$index].$column.", ";
                            $values[$index] = $values[$index]."'$value',";
                        }
                        $cp_first = false;
                        if($_Config['aid_spec'] === true && $spec_cnt[1]['CNT'] == '0')
                        {
	                        foreach($columns as $column=>$value)
	                        {
	                    		if($column == 'PRIORITY' && $value == '1')
	                    		{
	                    			$nspecialty_id = $columns['SPECIALTY_ID'];
	                    			$cp_first = true;
	                    			$gen_aid = true;
//	                    			var_dump($nspecialty_id);
	                    		}
	                        }
	                }
                    
                        foreach($sql_start as $index=>$start)
                        {
                            $_SYSTEM['use_sequence_insert'] = false;
                            $sql1[$index] = $start;
                            $sql1[$index] = $sql1[$index].substr($fields[$index],0,-2).') values (';
                            $sql1[$index] = $sql1[$index].$sql_values[$index].substr($values[$index],0,-1).');';
                        }
//                        var_dump($fields);
//                        var_dump($values);
//                        echo '<hr>';
//                        var_dump($sql1);
                        foreach($sql1 as $index=>$query)
                        {
                            if($go)
                            {
                            //echo "11->".$query;
                            db_execute($query);
                            }
                        }
                    }
                }
            }
            //
            //
            //
    //die('dsnvgdlknbk');
//            var_dump($spec_cnt[1]['CNT']);
            if($_Config['aid_spec'] === true && $spec_cnt[1]['CNT'] == '0' && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && $idnt_new === false)
            {
//            echo "ggggggggggggggggg";
        	$school_id =($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?get_apply_school_id():get_school_id();
        	$spec_id = "AND CFIELD_1 = '$nspecialty_id'";
		if($_Config['AID']['SCHOOL_UNIQUE'] === true)
			$su_sql = "AND SCHOOL_ID = '".$school_id."'";
		$app_max_id = db_request(db_execute("SELECT MAX(APPLICANT_ID) AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' $su_sql $spec_id"));
		$app_max_id = $app_max_id[1]['MAX'];
		if(!$app_max_id || $app_max_id == '')
			$app_max_id = 1;
		else
			$app_max_id = $app_max_id+1;

    	        $idnt_sql = "UPDATE APP_IDENTIFY SET CFIELD_1 = '$nspecialty_id', APPLICANT_ID = '$app_max_id' WHERE STUDENT_ID = '$student_id'";
    	        //echo $idnt_sql;
    	        db_execute($idnt_sql);
            }
            elseif($_Config['aid_spec'] === true && $spec_cnt[1]['CNT'] > '0' && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && $_REQUEST['faculty']['new']['TYPE_OF_STUDY'] && $nspecialty_id)
            {
//		echo "bbbbbbbbbbbbbbbbbb";
		$app_id = db_request(db_execute("SELECT CFIELD_1,APPLICANT_ID,STUDENT_ID AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' AND STUDENT_ID = '".get_student_id()."'"));
		if($app_id[1]['CFIELD_1'] <> $nspecialty_id)
		{
		
	        	$school_id =($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?get_apply_school_id():get_school_id();
    		    	$spec_id = "AND CFIELD_1 = '$nspecialty_id'";
//        		echo $spec_id;
			if($_Config['AID']['SCHOOL_UNIQUE'] === true)
				$su_sql = "AND SCHOOL_ID = '".$school_id."'";
			$app_max_id = db_request(db_execute("SELECT MAX(APPLICANT_ID) AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' $su_sql $spec_id"));
			$app_max_id = $app_max_id[1]['MAX'];
//			var_dump($app_max_id);
			if($_REQUEST['faculty']['new']['TYPE_OF_STUDY'])
			{
				if(!$app_max_id || $app_max_id == '')
					$app_max_id = 1;
				else
					$app_max_id = $app_max_id+1;
			}
		
	    	        $idnt_sql = "UPDATE APP_IDENTIFY SET CFIELD_1 = '$nspecialty_id', APPLICANT_ID = '$app_max_id' WHERE STUDENT_ID = '".get_student_id()."'";
//    			echo $idnt_sql;
	    	        db_execute($idnt_sql);
    	        }
            }
            elseif($_Config['aid_spec'] === true && $spec_cnt[1]['CNT'] == '0' && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && $_REQUEST['faculty']['new']['TYPE_OF_STUDY'] && $cp_first === true)
            {
//		echo "xxxxxxxxxxxxxxxx";
        	$school_id =($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?get_apply_school_id():get_school_id();
        	$spec_id = "AND CFIELD_1 = '$nspecialty_id'";
//        	echo $spec_id;
		if($_Config['AID']['SCHOOL_UNIQUE'] === true)
			$su_sql = "AND SCHOOL_ID = '".$school_id."'";
		$app_max_id = db_request(db_execute("SELECT MAX(APPLICANT_ID) AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' $su_sql $spec_id"));
//		echo "SELECT MAX(APPLICANT_ID) AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' AND SCHOOL_ID = '".$school_id."' $spec_id";
		$app_max_id = $app_max_id[1]['MAX'];
//		var_dump($app_max_id);
//		var_dump($_REQUEST['faculty']['new']['TYPE_OF_STUDY']);
		if($_REQUEST['faculty']['new']['TYPE_OF_STUDY'])
		{
			if(!$app_max_id || $app_max_id == '')
				$app_max_id = 1;
			else
				$app_max_id = $app_max_id+1;
		}
		
    	        $idnt_sql = "UPDATE APP_IDENTIFY SET CFIELD_1 = '$nspecialty_id', APPLICANT_ID = '$app_max_id' WHERE STUDENT_ID = '".get_student_id()."'";
//    	        echo $idnt_sql;
    	        db_execute($idnt_sql);
            }
            elseif($_Config['aid_spec'] === true && $spec_cnt[1]['CNT'] > '0' && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && $upd_idnt === true)
            {
//		echo "eeeeeeeeeeeeeeeee";
		$app_id = db_request(db_execute("SELECT CFIELD_1,APPLICANT_ID,STUDENT_ID AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' AND STUDENT_ID = '".get_student_id()."'"));
//		echo "SELECT CFIELD_1,APPLICANT_ID,STUDENT_ID AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' AND STUDENT_ID = '".get_student_id()."'";
//		var_dump($app_id);
//		var_dump($nspecialty_id);
		if($app_id[1]['CFIELD_1'] <> $nspecialty_id)
		{
	        	$school_id =($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')?get_apply_school_id():get_school_id();
	        	$spec_id = "AND CFIELD_1 = '$nspecialty_id'";
//	        	echo $spec_id;
			if($_Config['AID']['SCHOOL_UNIQUE'] === true)
				$su_sql = "AND SCHOOL_ID = '".$school_id."'";
//			echo "SELECT MAX(APPLICANT_ID) AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' $su_sql $spec_id";
			$app_max_id = db_request(db_execute("SELECT MAX(APPLICANT_ID) AS MAX FROM APP_IDENTIFY WHERE SCHOOL_YEAR = '".get_school_year()."' $su_sql $spec_id"));
			$app_max_id = $app_max_id[1]['MAX'];
//			var_dump($app_max_id);
			{
				if(!$app_max_id || $app_max_id == '')
					$app_max_id = 1;
				else
					$app_max_id = $app_max_id+1;
			}
	    	        $idnt_sql = "UPDATE APP_IDENTIFY SET CFIELD_1 = '$nspecialty_id', APPLICANT_ID = '$app_max_id' WHERE STUDENT_ID = '".get_student_id()."'";
//	    	        echo $idnt_sql;
	    	        db_execute($idnt_sql);
		}
            }

	}
        unset($_REQUEST['faculty']);
//	var_dump($go);
//	var_dump($nspecialty_id);
//	var_dump($cp_first);



//die('dsgergfhr');
	if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php' && (($go && $nspecialty_id) || ($gen_aid === true && $nspecialty_id)))
	{
//	echo "vvvvvvvvvvvvvv";
		$Student->setStudentId(get_student_id());
		if($Student->genAID() === true)
		{
			$Student->updateAID();
			if($_REQUEST['student_id']=='new' || SystemPreferences('BLOCKUSERNAME','applicants',false) == 'Y')
				$Student->updateApplicantUsername();
		}
	}

	/*
		has added the $_REQUEST['..._log_values'] because if we have only the data fields, they will not be
		saved
	*/

	if(($_REQUEST['log_values'] && $_POST['log_values']) || ($_REQUEST['month_log_values'] || $_REQUEST['day_log_values'] || $_REQUEST['year_log_values']))
	{
		if(count($_REQUEST['month_log_values']))
		{
			/* this var will be set, if user entered some data in the logging fields */
			unset($logFieldValuesCount);
                        
			foreach($_REQUEST['month_log_values'] as $student_field_id=>$records)
			{
				foreach($records as $id=>$columns)
				{
					/* 
						will check the qty of the entered fields - if we have only default DATE
						values, will return 0
					*/
					if(preg_match('/new/', $id)) 
					{
						unset($logFieldValuesCount);
						$logFieldValuesCount = _checkLogFieldsValues($_REQUEST['log_values'][$student_field_id][$id]);
					}	
					
					foreach($columns as $field_name=>$month)
					{
						$_REQUEST['log_values'][$student_field_id][$id][$field_name] = $_REQUEST['year_log_values'][$student_field_id][$id][$field_name].'-'.$month.'-'.$_REQUEST['day_log_values'][$student_field_id][$id][$field_name];

						if(preg_match('/new/', $id))
							$defaultSelectionId = 'new';
						
						if(($_SESSION['default_log_date']['['.$student_field_id.']['.$id.']['.$field_name.']'] ==
						$_REQUEST['log_values'][$student_field_id][$id][$field_name] && $logFieldValuesCount==0 && ($skip != $id)) ||
						(
						($_SESSION['default_log_date']['['.$student_field_id.']['.$defaultSelectionId.']['.$field_name.']'] ==
						$_REQUEST['log_values'][$student_field_id][$id][$field_name] && $logFieldValuesCount==0 && ($skip != $id))
						)
						)
						{
							unset($_REQUEST['log_values'][$student_field_id][$id][$field_name]);
							unset($_SESSION['default_log_date']['['.$student_field_id.']['.$id.']['.$field_name.']']);
							unset($skip);
						} else {
							/* 
								for the case, if we have some DATE fields, and one of them has changed
							*/
							$skip = $id;
						}

						if(!VerifyDate($_REQUEST['log_values'][$student_field_id][$id][$field_name]))
						{
							if($_REQUEST['log_values'][$student_field_id][$id][$field_name]!='--')
								$note = '<IMG SRC=images/warning_button.gif>'._('The date you specified is not valid, so was not used.  The other data was saved.');
							unset($_REQUEST['log_values'][$student_field_id][$id][$field_name]);
						}
					}
				}
			}



                        /* if user choose n/a in the date field and want to make this field is blank */
                        foreach($_REQUEST['month_log_values'] as $student_field_id=>$records)
                        {
                                foreach($records as $id=>$columns)
                                {
                                        if($id != 'new')
                                        {
                                                foreach($columns as $field_name=>$month)
                                                {
                                                        if($month == '')
                                                        {
                                                                $_REQUEST['log_values'][$student_field_id][$id][$field_name] = '';
                                                        }
                                                }
                                        }
                                }
                        }
		}
				
		foreach($_REQUEST['log_values'] as $student_field_id=>$records)
		{
			foreach($records as $id=>$columns)
			{
				if(substr($id,0,3)!='new')
				{
					$sql = "UPDATE STUDENT_LF_DATA SET ";
					if(count($columns))
					{	$go = true;
                                                //Перевод чисел в буквы в конфиге задается следование
                                                if($columns[$_Config['NumToLetter']['CFIELD_'.$student_field_id]['FROM']]<>'')
                                                    $columns[$_Config['NumToLetter']['CFIELD_'.$student_field_id]['TO']] = $NumToText->Convert(intval($columns[$_Config['NumToLetter']['CFIELD_'.$student_field_id]['FROM']]));
                                                ////конец Перевод чисел в буквы в конфиге задается следование
						foreach($columns as $column=>$value)
						{
/*                                                        if($_Config['NumToLetter']['CFIELD_'.$student_field_id]['FROM']==$column)
                                                        {
                                                            $value = $NumToText->Convert(intval($value));
                                                        }
 * 
 */
							$sql .= $column."='".str_replace("\'","''",$value)."',";
						}
						$sql = substr($sql,0,-1) . " WHERE ID='$id'";
						if($go)
							db_execute($sql);
					}
				}
				else
				{
					$sql = "INSERT INTO STUDENT_LF_DATA ";

					$fields = 'ID,SCHOOL_ID,STUDENT_ID,STUDENT_FIELD_ID,';
					$values = db_seq_nextval('STUDENT_LF_DATA_SEQ').",'".get_school_id()."','".get_student_id()."','".$student_field_id."',";

					$go = 0;
					$fields_count = 0;
					unset($value);
                                        // Перевод чисел в буквы в конфиге задается следование
                                        if($columns[$_Config['NumToLetter']['CFIELD_'.$student_field_id]['FROM']]<>'')
                                            $columns[$_Config['NumToLetter']['CFIELD_'.$student_field_id]['TO']] = $NumToText->Convert(intval($columns[$_Config['NumToLetter']['CFIELD_'.$student_field_id]['FROM']]));
                                        ////конец Перевод чисел в буквы в конфиге задается следование
					foreach($columns as $column=>$value)
					{
						if(!empty($value))
						{
							$fields .= $column.',';
							$values .= "'".str_replace("\'","''",$value)."',";
							$fields_count++;
							//это нужно чтоб не записывалось значение СЕГОДНЯ для даты.
							$today_d = date("Y-m-d");
							if ($fields_count == 1 && $value == $today_d)
								$go = false;
							else
								$go = true;
						}
					}
					$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';

					if($go)
						db_execute($sql);
                                        $sql_add="INSERT INTO student_lf_data(student_field_id,student_id,school_id,log_field1)
                                        VALUES('999999','".get_student_id()."','".get_school_id()."','1')";
                                        db_execute($sql_add);
				}
			}
		}
	}
	unset($_REQUEST['servicefunction']);
	if(!get_student_id())
		unset($_REQUEST['values']);
	unset($_SESSION['_REQUEST_vars']['servicefunction']);
	unset($_SESSION['_REQUEST_vars']['values']);
}

if($_REQUEST['student_id']=='new')
{   
	ProgramTitle();
        if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
            DisplayHeader(".:"._('Add an Applicant').":.");
        else
            DisplayHeader(".:"._('Add a Student').":.");
	
}
else
{  
    if(isset($_REQUEST['GridOutputCount']))
    { 
	$tmp_REQUEST = $_REQUEST;
	unset($tmp_REQUEST['GridOutputCount']);
	unset($tmp_REQUEST['values']);
	unset($tmp_REQUEST['address_id']);
	unset($tmp_REQUEST['person_id']);
	unset($tmp_REQUEST['student_id']);
	unset($tmp_REQUEST['discipline_ir_id']);
	// search_servicefunction can probably be unset in any case
	//if($tmp_REQUEST['search_servicefunction']=='result')
	unset($tmp_REQUEST['search_servicefunction']);
	// since we need this for the referrals screen
	unset($tmp_REQUEST['stuid']);
	// since GrdPrintStudGrades has issues with the MP tabs ... this probably applies to any program, but why chance it...
	if($_REQUEST['servicemod']=='mod_grades/GrdPrintStudGrades.php')
	    unset($tmp_REQUEST['search_servicefunction']);
	
	if($_REQUEST['GridOutputCount']>1)
	{
	    $but_left =  '<A HREF='.SetRequestOptions($tmp_REQUEST).'&GridOutputCount='.($_REQUEST['GridOutputCount']-1).'><IMG SRC=images/arrow_left.gif border=0></A>';
	}
	if($_SESSION['student_list'] && $_REQUEST['GridOutputCount']<count($_SESSION['student_list']))
	{
	    $but_right =  '<A HREF='.SetRequestOptions($tmp_REQUEST).'&GridOutputCount='.($_REQUEST['GridOutputCount']+1).'><IMG SRC=images/arrow_right.gif border=0></A>';
	}
    }else{  
	unset($_SESSION['student_list']);
    }

   get_student_info(); 

}  
//echo $staticpath.'classes/Students.class.php';die;
Widgets('all');    
//echo "<pre>";print_r($addition);die;
Search('student_id',$addition); 

//print_r($addition);die('jdsfkgbk');
// step one is to determine what to display
/*
if(isset($_FILES['file']))
	{
	// we have received a file in the post data, disect all the useful information
	$file = $_FILES['file']['tmp_name'];
	$upload_dir=$uploaded_assets_dir.$title.'/'.get_student_id().'/';
	$ext=strtolower(pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION));
	// and assemble this into somthing useful
	do
	  {
	  $upload_fullpath=$upload_dir.time().'-'.rand().'.'.$ext;
	  }
	while (file_exists($upload_fullpath));

	// double check to ensure that the directory exists and is writeable
	if(file_exists($upload_dir))
	  {
	  if(!is_writable($upload_dir))
		echo _("At this time administration has disabled file uploads.<br>");
		echo "";
	  }
	else
	  {
	  mkdir($upload_dir,0755,true);
	  }

	//now we will rename the temporary file to its final position
	if(!move_uploaded_file($file, $upload_fullpath))
	  {
	  $error = _("The image you tried to upload could not be saved.  This is likely a system-configuration issue.  See a system administrator.");
	  $Message[1] = _("File upload is failed.<br>")."";
	  }
	else
	  {
	  $sql = "INSERT INTO PROGRAM_UPLOADED_FILES (id, title, location, uploaded_date, filesize) VALUES (".db_seq_nextval("PROGRAM_UPLOADED_FILES_seq").", '".$_FILES['file']['name']."', '".$upload_fullpath."', '".get_db_date()."', '".filesize($upload_fullpath)."')";
	  db_execute($sql);
	  $id = db_seq_currval('PROGRAM_UPLOADED_FILES_seq');
	  $sql = "UPDATE students SET ".$_POST['Upload_file_field_id']." = '".$id."' WHERE student_id = '".get_student_id()."'";
	  db_execute($sql);
	  $Message[1] = _("Your file has been successfully saved.");
	  }
	}


if(($_REQUEST['DeleteFileOK'])&&($_REQUEST['FileID'])&&($_REQUEST['Upload_file_field_id']))
  {
  //Deleting file ID from Students Table
  $sql = "UPDATE STUDENTS SET ".$_REQUEST['Upload_file_field_id']." = '' WHERE student_id = '".get_student_id()."' AND ".$_REQUEST['Upload_file_field_id']." = '".$_REQUEST['FileID']."'";
  db_execute($sql);
  //Phisically deleting file
  $FilePath = db_request(db_execute("SELECT LOCATION FROM PROGRAM_UPLOADED_FILES WHERE ID='".$_REQUEST['FileID']."'"));
  if(file_exists($FilePath[1]['LOCATION']))
     unlink($FilePath[1]['LOCATION']);
  //Deleting file from the FILES table
  $sql = "DELETE FROM PROGRAM_UPLOADED_FILES WHERE ID='".$_REQUEST['FileID']."'";
  db_execute($sql);
  $Message[1] = "File was successfully deleted.";
  
  }
 * 
 */
/*HOOK FOR UNENROLLMENT APPLICANT*/

//die;


// $school_query=db_request(db_execute("select title from schools where id=3"));
// echo "<pre>";
// $q=$school_query[1]['TITLE'];
//print_r($q);die;

$dont_show = false;
if($_REQUEST['include'] == 'stuenrollmentinfotab')
{

    $prompt = false;
    if(is_applicant())
    {
        if(is_array($_REQUEST['values']['STUDENT_REGISTRATION']) && $_REQUEST['old_next_school']!=='-1' && $_REQUEST['old_next_school']!=='0')
        {
            foreach($_REQUEST['values']['STUDENT_REGISTRATION'] as $id=>$data)
            {
                if($_REQUEST['values']['STUDENT_REGISTRATION'][$id]['NEXT_SCHOOL'] == '-1' || $_REQUEST['values']['STUDENT_REGISTRATION'][$id]['NEXT_SCHOOL'] == '0')
                {
                    $prompt = true;
                }
            }
        }
   
        if($prompt)
        {
        //print_r('geeta');die;
            if(Prompt(_('Change Status Confirmation'), _('Applicant is enrolled. Do you want to change enrollment status and un-enroll this applicant?'), '', false, _('OK'), false, _('Admission data will be cleared. Are you sure you want to continue?'), 'post', true))
            {
                db_execute("UPDATE STUDENT_SPEC_FIELDS SET ENROLLMENT_CODE = NULL,ENROLLMENT_DATE = NULL WHERE STUDENT_ID = '".get_student_id()."'");
                $dont_show_r = true;
            }
            $dont_show = ($dont_show_r)?false:true;
        }
    }
}
/*HOOK FOR UNENROLLMENT APPLICANT*/
if(!$dont_show)
{
        //student info
        //echo "==>".get_student_id()."--[".is_applicant().']';
        //echo $_REQUEST['servicemod'];
        if($_REQUEST['btn_verify'] && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && AllowEdit())
        {
                $hide_info = true;
                if(Prompt(_('Applicant Info Verification'),_('Are you sure you want to verify info for this applicant?')))
                {
                        $_SYSTEM['verify'] = true;
                        unset($_REQUEST['btn_verify']);
                }
        }

        if($_REQUEST['btn_copy'] && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && AllowEdit())
        {
                $hide_info = true;
                if(Prompt(_('Copy Applicant Info'),_('Are you sure you want to copy info for this applicant?'),_('Select a School'),false,_('OK'),null,null,'get',true,'toschool'))
                {
                        $_SYSTEM['copy'] = true;
                        unset($_REQUEST['btn_copy']);
                }
        }

        if($_REQUEST['btn_refuse'] && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && AllowEdit())
        {
                $hide_info = true;
                if(Prompt(_('Reject Applicant'),_('Are you sure you want to refuse info for this applicant?'),_('Specify a cause of a rejection'),false,_('OK'),null,null,'get',true,true))
                {
                        $_SYSTEM['refuse'] = true;
                        unset($_REQUEST['btn_refuse']);
                }
        }

        if($_SYSTEM['copy'] === true && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && AllowEdit())
        {
        //echo "Copying...<br>";
                $columns = '';
                $student_id = db_request(db_execute('SELECT '.db_seq_nextval('STUDENTS_SEQ').' AS STUDENT_ID '.FROM_DUAL));
                if($DBType == 'mssql')
                        $student_id = $student_id[1]['STUDENT_ID'];
                else
                        $student_id = $student_id[1]['STUDENT_ID']+1;
                //echo "before correct ".$student_id.'<br>';
        //    	echo "past student:".$_REQUEST['student_id'];
        //        echo "next $student_id<br>";
                $student_fields = db_request(db_execute("SELECT ID,TYPE FROM STUDENT_FIELDS WHERE TYPE NOT IN ('log','holder') AND TYPE IS NOT NULL"),array(),array('ID'));
                $exclude_fields = array();
                $exclude_fields += $_Config['exclude_fields'];
                foreach($student_fields as $sfield_id=>$values)
                {
            //		echo 'CFIELD_'.$column;
                        if(!in_array($sfield_id,$exclude_fields))
                                $columns .= 'CFIELD_'.$sfield_id.',';
                }

                if($DBType == 'mssql')
                    $id_corrector = $Student->getIdCorrector();

                if($DBType!='mssql')
                        db_execute("INSERT INTO STUDENTS (STUDENT_ID,$columns PROFILE,LAST_NAME,FIRST_NAME,MIDDLE_NAME,NAME_SUFFIX,PASSWORD) SELECT $student_id AS STUDENT_ID, $columns PROFILE,LAST_NAME,FIRST_NAME,MIDDLE_NAME,NAME_SUFFIX,PASSWORD FROM STUDENTS WHERE STUDENT_ID = '".get_student_id()."'");
                else
                        db_execute("INSERT INTO STUDENTS ($columns ID_CORRECTOR,PROFILE,LAST_NAME,FIRST_NAME,MIDDLE_NAME,NAME_SUFFIX,PASSWORD) SELECT $columns '$id_corrector' AS ID_CORRECTOR,PROFILE,LAST_NAME,FIRST_NAME,MIDDLE_NAME,NAME_SUFFIX,PASSWORD FROM STUDENTS WHERE STUDENT_ID = '".get_student_id()."'");
                if($DBType == 'mssql')
                    $student_id = $Student->FixStudentID($student_id,$id_corrector);

        //            echo "after correct ".$student_id;
                $Student->IDFrom = get_student_id();
                $Student->IDTo = $student_id;
                $Student->copy_school_id = $_REQUEST['toschool'];
                $Student->createAppIdntrecord();
                $Student->copySRrecord();
                $Student->copySIArecord();
                $varCopy = true;

                $student_logfields = db_request(db_execute("SELECT ID,TYPE FROM STUDENT_FIELDS WHERE TYPE = 'log' AND TYPE IS NOT NULL"),array(),array('ID'));
                foreach($student_logfields as $sfield_id=>$values)
                {
                        if(!in_array($sfield_id,$exclude_fields))
                                $log_columns .= $sfield_id.',';
                }
                $log_columns = substr($log_columns,0,-1);
                $columns = 'LOG_FIELD1,LOG_FIELD2,LOG_FIELD3,LOG_FIELD4,LOG_FIELD5,LOG_FIELD6,LOG_FIELD7,LOG_FIELD8,LOG_FIELD9,LOG_FIELD10,LOG_FIELD11,LOG_FIELD12,LOG_FIELD13,LOG_FIELD14,LOG_FIELD15,LOG_FIELD16,LOG_FIELD17,LOG_FIELD18,LOG_FIELD19,LOG_FIELD20,STUDENT_FIELD_ID,';
                if($DBType!='mssql')
                        db_execute("INSERT INTO STUDENT_LF_DATA (ID,STUDENT_ID,$columns SCHOOL_ID) SELECT ".db_seq_nextval('STUDENT_LF_DATA_SEQ').",$student_id AS STUDENT_ID,$columns SCHOOL_ID FROM STUDENT_LF_DATA WHERE STUDENT_ID = '".$_REQUEST['student_id']."' AND STUDNET_FIELD_ID IN ($log_columns)");
                else
                        db_execute("INSERT INTO STUDENT_LF_DATA (STUDENT_ID,$columns SCHOOL_ID) SELECT $student_id AS STUDENT_ID,$columns SCHOOL_ID FROM STUDENT_LF_DATA WHERE STUDENT_ID = '".$_REQUEST['student_id']."' AND STUDENT_FIELD_ID IN ($log_columns)");

                $Student->setStudentId($student_id);
                if($Student->genAID() === true)
                {
                        $Student->updateAID();
                        if(SystemPreferences('BLOCKUSERNAME','applicants',false) == 'Y')
                                $Student->updateApplicantUsername();
                }
                $_REQUEST['student_id'] = $student_id;
        //        $tmp_REQUEST['student_id'] = $student_id;
                $_SESSION['student_id'] = $student_id;
                $_SESSION['get_student_id'] = $student_id;
                $_SESSION['get_school_id'] = $_REQUEST['toschool'];
                $_SESSION['_REQUEST_vars']['ext_school_id'] = $_REQUEST['toschool'];
                $_SESSION['_REQUEST_vars']['school_id'] = $_REQUEST['toschool'];
                $_SESSION['_REQUEST_vars']['student_id'] = $student_id;
                $_SESSION['_REQUEST_vars']['get_student_id'] = $student_id;
                $varCopy = false;
                unset($_SYSTEM['copy']);
        }

//die('ryeyhe');
        if($_SYSTEM['verify'] === true && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && AllowEdit())
        {
                $sql = "UPDATE APP_IDENTIFY SET ";
                $sql .= "APPLICANT_VERIFIED = 'Y', VFD_DATE = '".get_db_date()."', VFD_USER_ID = '".get_user('USER_ID')."', VFD_USER_NAME = '".get_teacher_fullname(get_user('USER_ID'),'','FULL_NAME','true')."' WHERE STUDENT_ID = '".get_student_id()."'";
        //	echo $sql;
                db_execute($sql);
        //	$Student->setStudentId(get_student_id());
        //	$enr_rec = db_request(db_execute(db_limit("SELECT ID,STUDENT_ID,ENROLLMENT_CODE,START_DATE FROM STUDENT_REGISTRATION WHERE STUDENT_ID = '".get_student_id()."' AND END_DATE IS NULL AND DROP_CODE != '".$enr_codes['DEF_VFD_DROP_ID'][1]['VALUE']."' ORDER BY ID ASC",1)));
                $enr_rec = db_request(db_execute(db_limit("SELECT ID,STUDENT_ID,ENROLLMENT_CODE,START_DATE FROM STUDENT_REGISTRATION WHERE STUDENT_ID = '".get_student_id()."' AND END_DATE IS NULL AND DROP_CODE IS NULL ORDER BY ID ASC",1)));
              
        
       // print_r($enr_rec);die;
        //var_dump($enr_rec);
        //	echo $enr_rec[1]['ID'];
                $enr_codes = db_request(db_execute("SELECT VALUE,TITLE FROM SYSTEM_CONFIG WHERE PROGRAM = 'applicants' AND SCHOOL_ID = '".get_school_id()."'"),array(),array('TITLE'));
        //	var_dump($enr_codes);
        //	$sql = "UPDATE STUDENT_REGISTRATION SET END_DATE = '".get_db_date()."', DROP_CODE = '".$enr_codes['DEF_VFD_DROP_ID'][1]['VALUE']."' WHERE ID = '".$enr_rec[1]['ID']."'";
        //	$sql = "UPDATE STUDENT_REGISTRATION SET ENROLLMENT_CODE = '".$enr_codes['DEF_ACP_ENR_ID'][1]['VALUE']."' WHERE STUDENT_ID = '".get_student_id()."' AND ID = '".$enr_rec[1]['ID']."'";
                $sql = "UPDATE STUDENT_REGISTRATION SET ENROLLMENT_CODE = '".$enr_codes['DEF_ACP_ENR_ID'][1]['VALUE']."' WHERE ID = '".$enr_rec[1]['ID']."'";
                //echo $sql;
                db_execute($sql);
                /*Почта начало*/
                    /*$_REQUEST['student_id'] = get_student_id();
                    $_SESSION['student_id'] = get_student_id();
                    $_SESSION['STUDENT_ID'] = get_student_id();*/
                    $_REQUEST['student'] = array();
                    $_REQUEST['student'][] = get_student_id();
                    $_REQUEST['preview'] = false;
                    $_REQUEST['to_address'] = 'email_students';
                    $_REQUEST['_template_id'] = 2;
                    $_REQUEST['letter_text'] = _('Ваша анкета подтверждена');
                    $_TEMP = $_SYSTEM['User'];
                    $_SYSTEM['User'] = array();
                    $_SYSTEM['User'][1]['PROFILE']='online_apply';
                    $_SYSTEM['User'][1]['NAME']= _('ОмГАУ');
                    $_REQUEST['servicefunction'] = 'save';
                    $old_school = $_SESSION['get_school_id'];
                    //$_SESSION['get_school_id'] = $_Application['main_school_id'];
                    $_REQUEST['email_subject'] = _('You request checked ').get_school(get_school_id());
                    $_REQUEST['_search_all_schools'] = true;

                    include($staticpath.'modules/mod_students/StuLetterWorkspace.php');
                    // вот этот файл дайт доступ на админские права!!! переделай! или делай чтоб наверняка.
                    unset($_SYSTEM['get_user'][1]['PROFILE']);
                    $_SYSTEM['User'] = $_TEMP;
                    $_SESSION['get_school_id'] = $old_school;
                /*Почта конец*/



        //	echo "ddddd".is_applicant();
        //	$Student->genAID();
        //	$Student->updateAID();
        //	echo $Student->getAID();
        //	$enr_rec = db_request(db_execute(db_limit("SELECT ID,STUDENT_ID,ENROLLMENT_CODE,START_DATE FROM STUDENT_REGISTRATION WHERE STUDENT_ID = '".get_student_id()."' AND END_DATE IS NULL AND START_DATE IS NOT NULL AND DROP_CODE IS NULL ORDER BY ID DESC",1)));
        //	var_dump($enr_rec);
                unset($_SYSTEM['verify']);
        }
        if($_SYSTEM['refuse'] === true && $_REQUEST['servicemod']=='mod_apply/Applicants.php' && AllowEdit())
        {
                    /*Как именно он будет откланяться или удаляться*/
                    /*Почта начало*/
                    /*$_REQUEST['student_id'] = get_student_id();
                    $_SESSION['student_id'] = get_student_id();
                    $_SESSION['STUDENT_ID'] = get_student_id();*/
                    $_REQUEST['student'] = array();
                    $_REQUEST['student'][] = get_student_id();
                    $_REQUEST['preview'] = false;
                    $reason = $_REQUEST['reason'];
                    $_REQUEST['to_address'] = 'email_students';
                    //$_REQUEST['_template_id'] = 2;
                    $_REQUEST['letter_text'] = _('Ваша анкета откланена. Причина: ').$reason._(' Внесите необходимые изменения.');
                    $_TEMP = $_SYSTEM['User'];
                    $_SYSTEM['User'] = array();
                    $_SYSTEM['User'][1]['PROFILE']='online_apply';
                    $_SYSTEM['User'][1]['NAME']= _('ОмГАУ');
                    $_REQUEST['servicefunction'] = 'save';
                    $old_school = $_SESSION['get_school_id'];
                    //$_SESSION['get_school_id'] = $_Application['main_school_id'];
                    $_REQUEST['email_subject'] = _('Ваша анкета откланена');
                    $_REQUEST['_search_all_schools'] = true;

                    include($staticpath.'modules/mod_students/StuLetterWorkspace.php');
                    // вот этот файл дайт доступ на админские права!!! переделай! или делай чтоб наверняка.
                    unset($_SYSTEM['get_user'][1]['PROFILE']);
                    $_SYSTEM['User'] = $_TEMP;
                    $_SESSION['get_school_id'] = $old_school;
                /*Почта конец*/
        }


        if((get_student_id() || $_REQUEST['student_id']=='new') && $_REQUEST['servicefunction']!='editfile' && !$_REQUEST['btn_verify'] && !$_REQUEST['btn_refuse'] && !$_REQUEST['btn_copy'])
        {
                if($_REQUEST['servicefunction']!='delete' || $_REQUEST['delete_ok']=='1')
                {
                        if($_REQUEST['student_id']!='new')
                        {
                                $sql = "SELECT
                                                                s.STUDENT_ID,
                                                                s.FIRST_NAME,
                                                                s.LAST_NAME,
                                                                s.MIDDLE_NAME,
                                                                s.NAME_SUFFIX,
                                                                ssm.SCHOOL_ID,
                                                                ssm.CLASSLEVEL_ID,
                                                                ssm.GROUP_ID,
                                                                s.USERNAME,
                                                                s.PASSWORD,
                                                                s.PROFILE,
                                                                s.PROFILE_ID,
                                                                s.FORCE_PASSWORD_CHANGE
                                                FROM STUDENTS s,STUDENT_REGISTRATION ssm
                                                WHERE s.STUDENT_ID='".get_student_id()."' AND ssm.SCHOOL_YEAR='".get_school_year()."' AND ssm.STUDENT_ID=s.STUDENT_ID
                                                ORDER BY ssm.START_DATE DESC,ssm.END_DATE DESC";
                                $QI = db_execute($sql);
                                $student = db_request($QI);
                                $student = $student[1];
                                if($_REQUEST['servicemod'] == 'mod_students/Students.php' && $student['PROFILE'] == 'applicant')
                                        DisplayHeader(ErrorMessage(array(_('Applicant information can not be viewed in Students module.')),'fatal'),' &nbsp;');
                                if($_REQUEST['include']!='studescinfotab')
                                        DrawStudentHeader();
                                $_REQUEST['servicemod'] = str_replace('?student_id=new','',$_REQUEST['servicemod']);
                                echo "<FORM name=student enctype=multipart/form-data action=modloader.php?servicemod=$_REQUEST[servicemod]&include=$_REQUEST[include]&student_id=".get_student_id()."&category_id=$_REQUEST[category_id]&useontop=$_REQUEST[useontop]&GridOutputCount=".$_REQUEST['GridOutputCount']."&historical=".$_REQUEST['historical']."&servicefunction=update id=student method=POST>";

                                if($_REQUEST['servicemod']=='mod_apply/Applicants.php')
                                {
                                        if(get_user('PROFILE') !== 'applicant')
                                        $copy_button = $submitButton->createSButton(_('Copy'),'btn_copy',null,'submit').'&nbsp;&nbsp;';
                                        if(is_verified(get_student_id()) != 'Y' &&  AllowEdit() && get_user('PROFILE') !== 'applicant')
                                                $vfd_btn = $submitButton->createSButton(_('Refuse'),'btn_refuse',null,'submit').'&nbsp;&nbsp;'.$submitButton->createSButton(_('Verify'),'btn_verify',null,'submit');
                                }
                                if($error_aid)
                                        $err_aid = '<IMG SRC=images/x.gif> '.$error_aid;
                                DisplayHeader('&nbsp;'.$err_aid,$submitButton->createSButton(_('Save'),'btn_save','id=top_submit','submit','rb_submit=true;').'&nbsp;&nbsp;&nbsp;&nbsp;'.$copy_button.$vfd_btn.'  ');
                                //AND (s.PROFILE IS NULL OR s.PROFILE='student')
                                $school = db_request(db_execute("SELECT SCHOOL_ID,CLASSLEVEL_ID FROM STUDENT_REGISTRATION WHERE STUDENT_ID='".get_student_id()."' 
                                AND SCHOOL_YEAR='".get_school_year()."' AND ('".get_db_date()."' BETWEEN START_DATE AND END_DATE OR END_DATE IS NULL)"));
                        }
                        else
                        {
                                if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
                                        echo "<FORM name=student id=student ".(($_REQUEST['servicemod']=='mod_apply/AddApp.php')?"onSubmit=\"return check_spec_fields(this);\"":'')." enctype=multipart/form-data action=modloader.php?servicemod=mod_apply/Applicants.php&prev_servicemod=$_REQEST[prev_servicemod]&include=$_REQUEST[include]&category_id=$_REQUEST[category_id]&GridOutputCount=".$_REQUEST['GridOutputCount']."&servicefunction=update method=POST>";
                                else
                                        echo "<FORM name=student id=student enctype=multipart/form-data action=modloader.php?servicemod=mod_students/Students.php&include=$_REQUEST[include]&category_id=$_REQUEST[category_id]&GridOutputCount=".$_REQUEST['GridOutputCount']."&servicefunction=update method=POST>";
                        }
                        if($_REQUEST['category_id']=='1' && AllowUse('mod_students/DelStud.php') && !isset($_REQUEST['CREATEPDF']))
                        {
                                $attendance_array = db_request(db_execute("SELECT COUNT(*) AS COUNT FROM STUDENT_ATTENDANCE_PERIODS WHERE STUDENT_ID='".get_student_id()."'"));
                                $grades_array = db_request(db_execute("SELECT COUNT(*) AS COUNT FROM STUDENT_GRADES_CARD WHERE STUDENT_ID='".get_student_id()."'"));
                                if($grades_array[1]['COUNT']>0 || $attendance_array[1]['COUNT']>0)
                                        $disabled = ' DISABLED';
                                $delete_button = '<INPUT style="width:100px;" type=button value='._('Delete').$disabled.' onclick="window.location=\'modloader.php?servicemod=mod_students/DelStud.php&student_id='.get_student_id().'\'"> &nbsp; ';
                        }
                        if($errorArr['override_error'])
                        {
                                if(!$errorArr['err'])
                                {
                                        $overrideDisabled = '';
                                        $_SESSION['overrideDisabled'] = true;
                                }
                                else
                                        $overrideDisabled = 'DISABLED';

                                $override_button = '<INPUT type=button value='._('Override').' '.$overrideDisabled.' onclick="checkOverride(\'student\');"> &nbsp; ';
                        }

                        /*
                                if there are some errors, we will show them
                        */
                         _showErrorWarningMsg($errorArr, $show, true);
                         Echo(ErrorMessage($Message,'Note'));

                        if(get_user('PROFILE')=='admin' || true)
                        {
                                if(is_numeric(get_user('PROFILE_ID')))
                                {
                                        $can_use_array = db_request(db_execute("SELECT MODNAME FROM PROFILE_SETTINGS WHERE PROFILE_ID='".get_user('PROFILE_ID')."' AND VIEWER='N'"),array(),array('MODNAME'));
                                }
                                else
                                        $can_use_array = db_request(db_execute("SELECT MODNAME FROM USER_SETTINGS WHERE USERNAME='".get_user('USERNAME')."' AND VIEWER='N'"),array(),array('MODNAME'));
                        }
        //		var_dump($_REQUEST['servicemod']);
        //                var_dump($_REQUEST['prev_servicemod']);
        //		var_dump($can_use_array);
                        if($_REQUEST['servicemod']!=='mod_apply/Applicants.php')
                        {
                                if(!$can_use_array['mod_students/Students.php&category_id=1'])
                                        $tabs[] = array('title'=>_('General Info'),'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stugeneralinfotab&category_id=1&GridOutputCount=".$_REQUEST['GridOutputCount']);
                                if(!$can_use_array['mod_students/Students.php&category_id=3'])
                                        $tabs[] = array('title'=>_('Addresses'),'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stuaddresstab&category_id=3&GridOutputCount=".$_REQUEST['GridOutputCount']);
                                if(!$can_use_array['mod_students/Students.php&category_id=77'])
                                        $tabs[] = array('title'=>_('Enrollment Records'),'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stuenrollmentinfotab&category_id=77&GridOutputCount=".$_REQUEST['GridOutputCount']);
                                $categories_array = db_request(db_execute("SELECT ID,TITLE FROM STUDENT_FIELD_CATEGORIES WHERE ID!=1 AND ID!=3 ORDER BY SORT_ORDER,TITLE"));
                       // echo "<pre>";
                      //  print_r($categories_array);die('fgdf');
                                foreach($categories_array as $category)
                                {
                                        if(!$can_use_array['mod_students/Students.php&category_id='.$category['ID']])
                                                $tabs[] = array('title'=>$category['TITLE'],'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stuaddlinfo&category_id=".$category['ID']."&GridOutputCount=".$_REQUEST['GridOutputCount']);
                                }
                        }
                        else
                        {
                                if(!$can_use_array['mod_apply/Applicants.php&category_id=1'])
                                        $tabs[] = array('title'=>_('General Info'),'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stugeneralinfotab&category_id=1&GridOutputCount=".$_REQUEST['GridOutputCount']);
                                if(!$can_use_array['mod_apply/Applicants.php&category_id=3'])
                                        $tabs[] = array('title'=>_('Addresses'),'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stuaddresstab&category_id=3&GridOutputCount=".$_REQUEST['GridOutputCount']);
                                if(!$can_use_array['mod_apply/Applicants.php&category_id=77'])
                                        $tabs[] = array('title'=>_('Admission Records'),'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stuenrollmentinfotab&category_id=77&GridOutputCount=".$_REQUEST['GridOutputCount']);
        //			$categories_array = db_request(db_execute("SELECT ID,TITLE FROM STUDENT_FIELD_CATEGORIES WHERE ID!=1 AND ID!=3 AND ID IN (SELECT CATEGORY_ID FROM STUDENT_FIELDS WHERE FOR_APPLICANTS = 'Y') ORDER BY SORT_ORDER,TITLE"));
                                $categories_array = db_request(db_execute("SELECT ID,TITLE FROM STUDENT_FIELD_CATEGORIES WHERE ID!=1 AND ID!=3 AND (ID IN
                                        (SELECT CATEGORY_ID FROM STUDENT_FIELDS WHERE FOR_APPLICANTS = 'Y')
                                        OR ID IN (SELECT CATEGORY_ID FROM STUDENT_FIELDS_IN_CATS WHERE FIELD_ID IN
                                        (SELECT FIELD_ID FROM STUDENT_FIELDS WHERE FOR_APPLICANTS = 'Y')))
                                        ORDER BY SORT_ORDER,TITLE"));
                                foreach($categories_array as $category)
                                {
                                    //var_dump($can_use_array['mod_apply/Applicants.php&category_id='.$category['ID']]);
                                        if(!$can_use_array['mod_apply/Applicants.php&category_id='.$category['ID']])
                                        {

                                            if(get_user('PROFILE')=='applicant')
                                            {
                                                if(!$_SYSTEM['AppIgnoreTabs'][get_school_id()][$category['ID']])
                                                    $tabs[] = array('title'=>$category['TITLE'],'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stuaddlinfo&category_id=".$category['ID']."&GridOutputCount=".$_REQUEST['GridOutputCount']);
                                            }
                                            else
                                                $tabs[] = array('title'=>$category['TITLE'],'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stuaddlinfo&category_id=".$category['ID']."&GridOutputCount=".$_REQUEST['GridOutputCount']);

                                        }
                                }
                        }

                        $_SYSTEM['selected_tab'] = "modloader.php?servicemod=$_REQUEST[servicemod]&include=$_REQUEST[include]";
                        if($_REQUEST['category_id'])
                                $_SYSTEM['selected_tab'] .= '&category_id='.$_REQUEST['category_id']."&GridOutputCount=".$_REQUEST['GridOutputCount'];
                        //this made to reduce size between header modules and categories
        //		echo '<BR>';
                        if(Preferences('MENU')=='Top')
                                $width = 'width=80%';
                        else
                                $width = 'width=99%';

                        if($_REQUEST['student_id']=='new')
                                $tabs = false;

                        if($_REQUEST['include']=='studescinfotab')
                        {
                        //echo SetRequestOptions();
                                $tabs = _('Comments');
                                if(get_user('PROFILE')=='teacher')
                                {
                                        $editable_tabs_array = db_request(db_execute("SELECT ID,TITLE FROM STUDENT_FIELD_CATEGORIES WHERE ALLOW_TEACHER_MODIFY='Y'"));
                                        if(count($editable_tabs_array))
                                        {
                                                $tabs = array();
        //					$tabs = array('link'=>SetRequestOptions(null,array('category_id')),'title'=>_('Comments'));
                                                $tabs = array('link'=>SetRequestOptions(null,array('category_id')),'title'=>_('Comments'));
                                                foreach($editable_tabs_array as $editable_tab)
                                                {
                                                        $tabs[] = array('link'=>SetRequestOptions(null,array('category_id','students')).'&amp;category_id='.$editable_tab['ID'],'title'=>$editable_tab['TITLE']);
                                                }
                                        }
                                }

                                if($_REQUEST['category_id'])
                                {
                                        $to_include = 'stuaddlinfo';
                                        $_SYSTEM['selected_tab'] = SetRequestOptions(null,array('category_id','students')).'&amp;category_id='.$editable_tab['ID'];
                                }
                        }
        //		var_dump($_REQUEST['servicemod']);
                        echo PopTable('header',$tabs,$width,0);
                        if(!$to_include)
                                $to_include = $_REQUEST['include'];
                        // Тут инклудятся статичные вкладки.
                        include($staticpath.'modules/mod_students/includes/'.$to_include.'.inc.php');
                        if($_REQUEST['student_id']=='new' && $_REQUEST['servicemod']!=='mod_apply/AddApp.php' && $_REQUEST['servicemod']!=='mod_apply/Applicants.php')
                            include($staticpath.'modules/mod_students/includes/stuenrollmentinfotab.inc.php');
                        if(AllowEdit())
                                echo '<BR><CENTER>'.$submitButton->createSButton(_('Save'),'btn_save','id=bottom_submit','button','rb_submit=true;jQuery("#inputstudents_PASSWORD").attr("disabled",""); document.forms.student.'.(($_REQUEST['servicemod']=='mod_apply/AddApp.php')?'onsubmit':'submit').'();').'</CENTER>';
                        $cat_count = db_request(db_execute("SELECT * FROM STUDENT_FIELD_CATEGORIES"));
                //echo "<pre>";
               // print_r($cat_count);die;
                        if(count($cat_count) > 0)
                                echo PopTable('footer');
                        echo '</FORM>';
                }
                else
                        include('modules/mod_students/includes/'.$_REQUEST['include'].'.inc.php');
        //	echo $_REQUEST['include'];
        }


        if($_REQUEST['servicemod']=='mod_apply/AddApp.php')
        {
                echo "<script>\n";
                echo "function check_spec_fields(form)\n";
                echo "{\n";
                echo "var status = true;\n";
                echo "var fields = '';\n";
                foreach($REQUIRED_js_check as $id=>$name)
                {
                        if(is_numeric($id))
                        {
                            echo "if(faculty == 'inputstudents[CFIELD_".$id."]'){";
                                echo "if(document.getElementById('inputstudents_faculty').value == '') {fields += '".$name.",';status=false;} \n";
                            echo "}else{";
                                echo "if(document.getElementById('inputstudents[CFIELD_".$id."]').value == '') {fields += '".$name.",';status=false;} }\n";
                        }
                        else
                                echo "if(document.getElementById('inputstudents[".$id."]').value == '') {fields += '".$name.",';status=false;} \n";
                        if(is_numeric($id))
                        {
                            echo "Logme(document.getElementById('inputstudents[CFIELD_".$id."]').name);";
                            echo "Logme(document.getElementById('inputstudents[CFIELD_".$id."]').value);";
                            echo "Logme(document.getElementById('inputstudents[CFIELD_".$id."]').type);";
                        }
                }
                echo "if(fields.length !== 0){\n";
                echo "fields = fields.substr(0,fields.length-1);\n";
                echo "alert('"._('This page was not marked as complete since the following fields are required:')."'+ fields +'"._('. Please fix this and try to save again.')."');}\n";
                echo "if(status){DelileForms(ShowedForms);form.submit();}else{return false;}\n";
                echo "}\n";

                echo "</script>\n";
        }
}
?>