<?php
        $borderstyle='style="border-bottom: 1px inset #'.Preferences('HIGHLIGHT').';"';
	$bgstyle='style="background-color:#'.Preferences('HIGHLIGHT_BACKGROUND').';background-image: -moz-linear-gradient(#FFFFFF, #'.Preferences('HIGHLIGHT_BACKGROUND').') "';

//die('kk');
if($_REQUEST['servicemod']=='mod_users/Users.php' || $_REQUEST['servicemod']=='mod_users/UsrMyInfo.php' || $_REQUEST['servicemod']=='mod_users/AddUser.php' || $_REQUEST['servicefunction']=='create_account')
{ 
	$custom_fields_table = 'USER_FIELDS';
	$categories_table = 'USER_FIELD_CATEGORIES';
	$students_table = 'USERS';
	$student_id_field = 'USER_ID';
	$log_student_id_field = 'USER_ID';
	$student_fields_join_categories = 'USER_FIELDS_IN_CATS';
	//if just created user we need to get user_id from request
	// (this need w/o selecting profile)
	$get_student_id = get_user_id();
	if(!$get_student_id && $_REQUEST['user_id']!='new') $get_student_id = $_REQUEST['user_id'];
//	echo "nnn-->".$get_student_id;
	$log_table = 'USER_LF_DATA';
	$student_field_id_field = 'USER_FIELD_ID';
	$html_field_title = 'user';
}


else if(($_REQUEST['servicemod']=='mod_ssetup/SchProperties.php') || ($_REQUEST['new_school'] == true))
{  
	$custom_fields_table = 'SCHOOL_FIELDS';
//print_r($custom_fields_table);
	$categories_table = 'SCHOOL_FIELD_CATEGORIES';
	$students_table = 'SCHOOLS';
	$student_id_field = 'ID';
//print_r($student_id_field);
	$log_student_id_field = 'SCHOOL_ID';
	$student_fields_join_categories = 'SCHOOL_FIELDS_IN_CATS';
//print_r($student_fields_join_categories);
	$get_student_id = get_school_id();
	$log_table = 'SCHOOL_LF_DATA';
	$student_field_id_field = 'SCHOOL_FIELD_ID';
	$html_field_title = 'schools';
}
elseif($_REQUEST['servicemod']=='mod_discipline/DisFieldsProperties.php' || $_REQUEST['servicemod']=='mod_discipline/DisIncidentList.php' || $_REQUEST['new_incident']==true)
{  
	$custom_fields_table = 'DISCIPLINE_INCIDENT_FIELDS';
	$categories_table = 'DISCIPLINE_INCIDENT_CATEGORIES';
	$students_table = 'STUDENT_DISCIPLINE_INCIDENTS';
	$student_fields_join_categories = 'DISCIPLINE_INCIDENTS_FIELDS_IN_CATS';
	//we need this var for using in the PullDownOptions.fnc.php
	$student_id_field = 'ID';
	$singular = _('Discipline Incident Field');
	$plural = _('Discipline Incident Fields');
	$singular_student = _('incident');
	$plural_student = _('incidents');
//$search_function_parameter = 'student_id';

	$get_student_id = UserIncidentID();

	$html_field_title = 'incident';
	$default_text = _('Default for new incident');
}
//die('kk');
else
{   
	$custom_fields_table = 'STUDENT_FIELDS';
	$categories_table = 'STUDENT_FIELD_CATEGORIES';
	$students_table = 'STUDENTS';
	$student_id_field = 'STUDENT_ID';
	$alt_cat_field_name = 'ALTERNATIVE_NAME,';
	$log_student_id_field = 'STUDENT_ID';
	$student_fields_join_categories = 'STUDENT_FIELDS_IN_CATS';
	$get_student_id = get_student_id();
	$log_table = 'STUDENT_LF_DATA';
	$student_field_id_field = 'STUDENT_FIELD_ID';
	$html_field_title = 'students';
}
//die('hhhh');
require_once($staticpath.'functions/extra/StudentsFunctional.fnc.php');
require_once($staticpath.'functions/extra/CategoriesSelection.fnc.php');
if($_REQUEST['servicefunction']=='delete' && $_REQUEST['id'] && get_user('PROFILE')=='admin' && $_REQUEST['delete_list_fields'] == true)
{ 
	if(!$_REQUEST['delete_ok'] && !$_REQUEST['delete_cancel'])
		echo '</FORM>';
	if(DeletePrompt(_('log entry')))
	{
		db_execute("DELETE FROM ".$log_table." WHERE ID='$_REQUEST[id]'");
		unset($_REQUEST['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		unset($_REQUEST['id']);
		unset($_SESSION['_REQUEST_vars']['id']);
	}
}
if($_REQUEST['servicefunction']=='delete' && $_REQUEST['id'] && get_user('PROFILE')=='admin' && $_REQUEST['delete_faculty_fields'] == true)
{
	if(!$_REQUEST['delete_ok'] && !$_REQUEST['delete_cancel'])
		echo '</FORM>';
	if(DeletePrompt(_('log entry')))
	{
		db_execute("DELETE FROM student_spec_fields WHERE ID='$_REQUEST[id]'");
		unset($_REQUEST['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		unset($_REQUEST['id']);
		unset($_SESSION['_REQUEST_vars']['id']);
	}
}

if($_REQUEST['servicefunction']!='delete' && $_REQUEST['category_id']=='required' && $_REQUEST['add_screen_required']!=true)
{  
        include_once($staticpath.'modules/mod_students/includes/studatafieldsfunc.inc.php');
        if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
        {
	        $fields_categories_array = db_request(db_execute("SELECT cf.*,sfc.ALTERNATIVE_NAME FROM ".$custom_fields_table." cf, ".$categories_table." sfc
				WHERE cf.CATEGORY_ID=sfc.ID AND (cf.REQUIRED='Y' OR cf.FOR_APPLICANTS='Y')
				ORDER BY sfc.SORT_ORDER, cf.SORT_ORDER, cf.TITLE"),array(),array('CATEGORY_ID'));//(cf.DEFAULT_SELECTION IS NOT NULL) OR
        }
        else
        {
		$fields_categories_array = db_request(db_execute("SELECT cf.* FROM ".$custom_fields_table." cf, ".$categories_table." sfc
				WHERE cf.CATEGORY_ID=sfc.ID AND (cf.REQUIRED='Y' OR cf.APPLICATION='Y' )
				ORDER BY sfc.SORT_ORDER, cf.SORT_ORDER, cf.TITLE"),array(),array('CATEGORY_ID'));//(cf.DEFAULT_SELECTION IS NOT NULL) OR
        }
	$categories_array = db_request(db_execute("SELECT ID,TITLE,{$alt_cat_field_name}COLUMNS FROM ".$categories_table." ORDER BY SORT_ORDER"),array(),array('ID'));
//	var_dump($categories_array);

	/*----------- Multiple Categories Start -----------*/
	if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
		$fields_categories_array = _joinAppAddlFields($custom_fields_table, $student_fields_join_categories, $fields_categories_array, '*');
	else
		$fields_categories_array = _joinAdditionalFields($custom_fields_table, $student_fields_join_categories, $fields_categories_array, '*');
//var_dump($fields_categories_array);
	/*
		Thus, we have included in the $fields_categories_array array fields from the
		$student_fields_join_categories table
	*/
	/*----------- Multiple Categories End-----------*/
	$_REQUEST['add_screen_required'] = true;
	foreach($categories_array as $category_id=>$category_array)
	{
		$category_array = $categories_array[$category_id];
		$fields_array = $fields_categories_array[$category_id];
		$fields_array = _changeSortOrder($fields_array);
		$app_usage = false;
		if($_REQUEST['servicemod']=='mod_apply/AddApp.php' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
		{
			if(AllowUse('mod_apply/Applicants.php&category_id='.$category_id))
			{
				if(count($fields_array) || $category_id==3)
				{
					echo '<BR><A onclick="switchMenu(\'fields_'.$category_id.'_table\');" style="cursor:pointer;"><IMG SRC=images/arrow_down.gif style="padding-left:5px;" id=fields_'.$category_id.'_table_arrow> <B>'.$categories_array[$category_id][1]['TITLE'].'</B></A><BR><DIV width=100% id=fields_'.$category_id.'_table style="display:block;border:2px solid #'.Preferences('HIGHLIGHT').';">';
					if($category_id==3 && $students_table=='STUDENTS')
						include($staticpath.'modules/mod_students/includes/stuaddresstab.inc.php');
					else
					{
						include($staticpath.'modules/mod_students/includes/stuaddlinfo.inc.php');
					}
					echo '</DIV>';
				}
			}
		}
		else
		{
			if(is_array($fields_array) || $category_id==3)
			{
				echo '<BR><A onclick="switchMenu(\'fields_'.$category_id.'_table\');" style="cursor:pointer;"><IMG SRC=images/arrow_down.gif style="padding-left:5px;" id=fields_'.$category_id.'_table_arrow> <B>'.$categories_array[$category_id][1]['TITLE'].'</B></A><BR><DIV width=100% id=fields_'.$category_id.'_table style="display:block;border:2px solid #'.Preferences('HIGHLIGHT').';">';
				if($category_id==3 && $students_table=='STUDENTS')
					include($staticpath.'modules/mod_students/includes/stuaddresstab.inc.php');
				else
				{
					include($staticpath.'modules/mod_students/includes/stuaddlinfo.inc.php');
				}
				echo '</DIV>';
			}
		}
	}
}
elseif($_REQUEST['servicefunction']!='delete')
{   
	if($_REQUEST['new_school'] == true)
	{
		unset($get_student_id);
	}
//	        var_dump($_REQUEST['servicemod']);
//	        var_dump($_SYSTEM['application']);
//	        var_dump($_REQUEST['category_id']);
//	        var_dump($_SYSTEM['for_application']);
	include_once($staticpath.'modules/mod_students/includes/studatafieldsfunc.inc.php');
	if($_REQUEST['category_id']!='required')
		$category_array = db_request(db_execute("SELECT ID,TITLE,{$alt_cat_field_name}COLUMNS FROM ".$categories_table." WHERE ID='".$_REQUEST['category_id']."'"));
	if($_SYSTEM['application']==true)
        {
		$fields_array = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE
									CATEGORY_ID='$_REQUEST[category_id]' AND
									APPLICATION='Y' OR
										ID IN (SELECT FIELD_ID FROM ".$student_fields_join_categories." WHERE CATEGORY_ID='".$_REQUEST['category_id']."')
									ORDER BY SORT_ORDER"));
        }
        elseif($_SYSTEM['for_application'] == true)
        {
            //APP_ONLINE_USE = 'Y' OR
            $ex_online_field = db_request(db_execute("SELECT FIELD_ID FROM ONLINE_FIELDS WHERE EDU_CAT_ID='".$_REQUEST['link']."' AND CATEGORY_ID='".$_REQUEST['category_id']."' AND APP_ONLINE_USE='Y'"),array(),array());
            $in = '';
            $allow_fields = array();
            foreach ($ex_online_field as $index=>$id)
            {
                $in .= "".$id['FIELD_ID'].",";
                $allow_fields[$id['FIELD_ID']] = true;
            }
            $in = substr($in,0,-1);
            $fields_array = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE ID IN ($in) AND CATEGORY_ID='$_REQUEST[category_id]'
                                                    OR ID IN (SELECT FIELD_ID FROM ".$student_fields_join_categories." WHERE CATEGORY_ID='".$_REQUEST['category_id']."')
                                                    ORDER BY SORT_ORDER"));
            $i=1;
            foreach($fields_array as $index=>$field_mass)
            {
                if($allow_fields[$field_mass['ID']])
                {
                    $result[$i]=$field_mass;
                    $i++;
                }
            }
            $fields_array = $result;
            //var_dump($result);
        }
        elseif($_REQUEST['servicemod']=='mod_apply/Applicants.php' && $_REQUEST['category_id']!='required')
        {
            $fields_array = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE
									CATEGORY_ID='$_REQUEST[category_id]' AND
									FOR_APPLICANTS='Y' OR 
										ID IN (SELECT FIELD_ID FROM ".$student_fields_join_categories." WHERE CATEGORY_ID='".$_REQUEST['category_id']."')
									ORDER BY SORT_ORDER"));
        }
	elseif($_REQUEST['category_id']!='required')
		$fields_array = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE
						CATEGORY_ID='$_REQUEST[category_id]' OR ID IN (SELECT FIELD_ID FROM ".$student_fields_join_categories." WHERE CATEGORY_ID='".$_REQUEST['category_id']."')
						ORDER BY SORT_ORDER"));
	if(is_array($fields_array))
	{
		if($get_student_id)
		{
			$custom_array = db_request(db_execute("SELECT * FROM ".$students_table." WHERE ".$student_id_field."='".$get_student_id."'"));
			$value = $custom_array[1];
			$_SYSTEM['other_info_blank'] = true;

			/*
			   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($custom_array[1]);

			foreach($fields_array as $field)
			{
				if($value['CFIELD_'.$field['ID']] && $_SYSTEM['application']!==true && $_SYSTEM['for_application']!==true)
					$_SYSTEM['other_info_blank'] = false;
			}
		}
		$bgcolor = $bgstyle;
	//	var_dump($_REQUEST);
	//	if($_REQUEST['include'] != 'stugeneralinfotab')

		echo '<TABLE cellspacing=0 cellpadding=3 width=100% class="freetable" ><TR '.$bgstyle.'>';
		$count = 1;
                
                $REQUIRED_js_check['LAST_NAME'] = _('Last Name');
                $REQUIRED_js_check['FIRST_NAME'] = _('First Name');
		for($o=1;$o<=count($fields_array);$o++)
		{
		    $field = $fields_array[$o];
	    	    if(!$_SYSTEM['APP_FIELDS'][$field['ID']])
		    {
			
			if($field['REQUIRED']=='Y' && AllowEdit())
			{
                                $REQUIRED_js_check[$field['ID']] = $field['TITLE'];
				$field['TITLE'] .= ' <font color=red>*</font>';
                                //$field['TITLE'] .= "<script>REQUIRED['".$field['ID']."'] = 'Y';</script>";
                        }
                      if(!$_Config['app_exclude_fields']) $_Config['app_exclude_fields'] = array();
if(in_array($field['ID'], $_Config['app_exclude_fields']) && $_REQUEST['servicemod']=='mod_apply/AddApp.php'){
//                                unset($field['TITLE']);
                                unset($REQUIRED_js_check[$field['ID']]);
                        }
			$colspan = 0;
			
			$_SYSTEM['APP_FIELDS'][$field['ID']] = true;
                			if(!$border) $border = array();
			if(in_array($html_field_title.'[CFIELD_'.$field['ID'].']', $border))
				$fontColor = "#ff0000";
			else
				$fontColor = '#3f3f3f';

			if($category_array[1]['COLUMNS']!='3' && $field['TYPE']!='log' && $field['TYPE']!='holder' && $field['TYPE']!='faculty')
			{
//				echo '<TD align=left width=30% bgcolor='.$bgcolor.' style="border-width:2px;border-style:none none inset none;border-color:'.Preferences('HIGHLIGHT').';"><font color='.$fontColor.'>'.($field['TITLE']?$field['TITLE']:'<p style="float:left;"></p>').'</font></TD>';
				echo '<TD align=left width=30%  '.$borderstyle.'><font color='.$fontColor.'>'.($field['TITLE']?$field['TITLE']:'').'</font></TD>';
				unset($field['TITLE']);
			}
			elseif($category_array[1]['COLUMNS']!='3' && ($field['TYPE']=='log' || $field['TYPE']=='faculty'))
			{
				$colspan=2;
				$bgcolor = 'style="background-color: #fff; background-image: none;"';
			}
			elseif($category_array[1]['COLUMNS']!='3' && $field['TYPE']=='holder')
			{
//				echo '<TD align=left width=30% bgcolor='.$bgcolor.' style="border-width:2px;border-style:none none inset none;height:5px;border-color:'.Preferences('HIGHLIGHT').';"><font color='.$fontColor.'>'.($field['TITLE']?$field['TITLE']:'<p style="float:left;"></p>').'</font></TD>';
				echo '<TD class="nonline" align=center colspan=2 '.$borderstyle.'><font color=#1F5EB3 style="text-align:center; font-weight: bold; font-size: 120%;">'.($field['TITLE']?$field['TITLE']:'<SPAN style="float:left;"></SPAN>').'</font>';
//				$colspan=2;
//				$bgcolor = 'FFFFFF';
			}
			else
			{
				if(($count%3)==1)
				{
					if($fields_array[$o+1]['TYPE']=='holder')
					{
						$count++;
						$o++;
						$colspan++;
					}
					if($fields_array[$o+1]['TYPE']=='holder')
					{
						$count++;
						$o++;
						$colspan++;
					}
				}
				elseif($count%3==2 && $fields_array[$o+1]['TYPE']=='holder')
				{
					$count++;
					$o++;
					$colspan++;
				}
			}

			if($colspan)
				$colspan = ' colspan='.($colspan+1);
			else
				$colspan = '';
			if($field['TYPE']=='log' || $field['TYPE']=='faculty')
				$colspan .= ' ';

		//	if($o!=count($fields_array))
		//	{
		    	    if($category_array[1]['COLUMNS']!='3' && $field['TYPE']!='holder')
			    echo '<TD'.$colspan.' width=70% '.$borderstyle.'>';
		//	}else{
		//	    echo '<TD'.$colspan.' width=70% bgcolor='.$bgcolor.'>';
		//	}

			switch($field['TYPE'])
			{
				case 'text':

					if($field['MAX_LENGTH'])
					{
						$options = ' maxlength='.$field['MAX_LENGTH'];
					}
					else
						$options = false;
                                        if($field['SIZE'])
                                            $options .= ' size='.$field['SIZE'];
										
         if(!$_Config['app_exclude_fields']) $_Config['app_exclude_fields'] = array();
		 								
 if(in_array($field['ID'],$_Config['app_exclude_fields']) && $_REQUEST['servicemod']=='mod_apply/AddApp.php')
echo _('N/A');
                                        else
                                        	echo _makeTextInput('CFIELD_'.$field['ID'],$field['TITLE'],$options);
				break;

				case 'numeric':
					echo _makeTextInput('CFIELD_'.$field['ID'],$field['TITLE'],'onkeyup="return check_numeric(this);" onchange="return check_numeric(this);" class="numeric" ','size=5 maxlength=20');
				break;

				case 'date':
				//	echo $field['ID'];
					echo _makeDateInput('CFIELD_'.$field['ID'],$field['TITLE'],'');
				break;

				case 'select':
					echo _makeSelectInput('CFIELD_'.$field['ID'],$field['TITLE']);
				break;

				case 'textarea':
            		//die("jljljll");
					//echo "jljllljlljlj";
					echo _makeTextareaInput('CFIELD_'.$field['ID'],$field['TITLE']);
				break;

				case 'multiple':
					echo _makeMultipleInput('CFIELD_'.$field['ID'],$field['TITLE']);
				break;

				case 'select_one':
					echo _makeSelectOneInput('CFIELD_'.$field['ID'],$field['TITLE']);
				break;

				case 'file':
					echo _makeFileInput('CFIELD_'.$field['ID'],$field['TITLE']);
				break;
				case 'faculty':
                                    unset($_SESSION['AJAX_SPECIALTY']);
                                    unset($_SESSION['ONLINE_APP_GROUPS']);
                                    $data_array = array();
                                    echo "<script>";
                                    echo "var priority_array = new Array();var java_edu_form_selector = new Array();";
                                    if(count($data_array))
                                    {
                                        foreach ($data_array as $index=>$info)
                                        {
                                            if(!$set[$info['JS_GROUP_ID']])
                                            {
                                                echo "priority_array[".$info['JS_GROUP_ID']."] = new Array();\n";
                                                $set[$info['JS_GROUP_ID']] = true;
                                            }
                                            echo "priority_array[".$info['JS_GROUP_ID']."][".$info['JS_PRIORITY']."] = ".$info['JS_PRIORITY'].";\n";
                                        }
                                    }
                                        echo "</script>";

                                    if($_REQUEST['servicemod'] == 'applicants_online')
                                    {
                                        $school_and_groups = db_request(db_execute("SELECT aag.ID as GROUP_ID,aag.TITLE as GROUP_TITLE,sch.title as SCHOOL_TITLE, sch.id as SCHOOL_ID FROM APP_ADM_GROUPS aag,specialty sp, faculty fac, schools sch WHERE aag.ID=sp.GROUP_ID AND sp.FACULTY_ID=fac.id AND sch.id = fac.SCHOOL_ID"),array(),array('SCHOOL_TITLE'));
                                        $content = "";
                                        $col = ceil(count($school_and_groups)/2);
                                        $content .="<div style=\"font-size:10px;\"><table><tr><td>";
                                        $col_num = 0;
                                        foreach($school_and_groups as $school_title=>$group_in_school)
                                        {
                                            $col_num++;
                                            $content .= '<b style="font-size:12px;">'.$school_title.'</b><br>';
                                            $ex = array();
                                            $content .= "<UL>";
                                            foreach ($group_in_school as $index=>$other)
                                            {
                                                if(!$ex[$other['GROUP_ID']]){$content .= '<li style="font-size:10px;">'.$other['GROUP_TITLE'].'</li>';$ex[$other['GROUP_ID']]= true;}
                                            }
                                            $content .= "</UL>";
                                            if($col_num==$col)
                                                $content .="</td><td>";

                                        }
                                        $content .="</td></tr></table></div>";
                                        $width = 500;
                                        $faculty .=   '<span onMouseOver=\'stm(["'._('Be at a loss in a choice?').'","'.str_replace('"','\"',str_replace("'",'&rsquo;',$content)).'"],
						["white","#'.Preferences('HIGHLIGHT').'","","","",,"black","#'.Preferences('COLOR').'","","","",,'.$width.',,2,"#'.Preferences('HIGHLIGHT_FRAME').'",2,,,,,"",,,,]);\'
						onMouseOut=\'htm()\')"><img src="'.
						'img/info-help.jpg" style="cursor:hand;width:16px;height:16px" border="0" alt="'._('Be at a loss in a choice?').'" />'._('Be at a loss in a choice?').'</span>';
//                                        $faculty .= '<img src="some" alt="'._('Help').'">';


  //                                      $faculty .= '</div>';
                                        $_SESSION['PRIORITY']['count'] = 0;
                                        /*echo '<!-- Выбор факультета -->';
                                        echo '<div style="float: right;" id="add_more">Выбрать специальность[+]</div><DIV id="sfstos"></div>';
                                        echo  '<!-- Выбор факультета -->';*/
                                        $faculty .= '<div>';
                                        //$faculty .=  $button->createSimpleText(_('Choose Major'),'#',"jQuery('#add_spec').toggle();");
                                        $add_spec =  "<script language='JavaScript' src='".$IntegralPathWeb."js/selectChain.js'></script>";
                                        $add_spec .=  "<script language='JavaScript'>
                                            var selected_group = new Array();
                                            var i = 1;
                                            function AddSpec(id)
                                            {
                                                jQuery.post('ajax.php?function_=get_form&id='+id+'&num=new', function(data){jQuery('#add_spec').append(data);jQuery.getScript('ajax.php?function_=genjs&id='+id+'&num=new', function(data){});});
                                            }
                                                </script>";
                                        $add_spec .= "<script language='JavaScript'>AddSpec(1);</script>";
                                        $add_spec .=  "<script language='JavaScript'>
                                                var valu;
                                                var ids;
                                                var flag;
                                                var mass =new Array();
                                                if (typeof priority_array == 'undefined')
                                                    var priority_array = new Array();
                                                ";
                                                $groups_array = array();
                                                $groups_array = db_request(db_execute("SELECT ID FROM APP_ADM_GROUPS"),array(),array('ID'));
                                                $edu_forms = array();
                                                $edu_forms = db_request(db_execute("select aef.TITLE,aef.ID,aef.SHORT_NAME,sy.GROUP_ID from edu_forms_in_spec efis,app_edu_forms aef,specialty sy,specialization sz where sy.id = sz.SPECIALTY_ID AND efis.SPECIALIZATION_ID = sz.id AND efis.EDU_FORM_ID = aef.ID AND sy.GROUP_ID IS NOT NULL"),array(),array('GROUP_ID'));
                                                $add_spec .=  "var eduform = new Array(); \n";
                                                foreach($groups_array as $group_id=>$other)
                                                {
//                                            	    echo "alert('".$group_id."');";
                                                    $add_spec .=  "eduform[$group_id] = new Array(); \n";
                                                    if($edu_forms[$group_id])
                                                    {
                                                	foreach($edu_forms[$group_id] as $index=>$sval)
                                                	{
                                                    	    if($sval['ID']<>'' && $sval['TITLE']<>'')
                                                        	$add_spec .=  "eduform[$group_id][".$sval['ID']."] = '".$sval['TITLE']."';\n";
                                                	}
                                            	    }
                                            	}
                                                //добавление EDU_FORMS
                                                        {
                                                        $add_spec .= "
                                                            var also_show = new Array();
                                                         function change_groups(in_value,id)
                                                         {
                                                            var selected_id;
                                                            var ele;
                                                            if(in_value!=='Н/Д' && in_value!=='')
                                                            {
                                                                flag = 'true';
                                                                jQuery('#inputfaculty_'+id+'_GROUP_ID option:selected').each(function ()
                                                                {\n
                                                                    selected_id = this.value;
                                                                });
                                                                if (typeof priority_array[selected_id] == 'undefined')
                                                                {
                                                                    jQuery('#inputfaculty_'+id+'_PRIORITY').val('1');
                                                                    priority_array[selected_id] = new Array();
                                                                    priority_array[selected_id][1] = 1;
                                                                }
                                                                else
                                                                {
                                                                    var max_new = 1;
                                                                    priority_array[selected_id] = priority_array[selected_id].sort()
                                                                    for (var key in priority_array[selected_id])
                                                                    {
                                                                        var val = priority_array[selected_id][key];
                                                                        //Logme('key=>'+key+' val=>'+val);
                                                                        if(val > max_new)
                                                                            max_new = val;
                                                                    }
                                                                    jQuery('#inputfaculty_'+id+'_PRIORITY').val(max_new+1);
                                                                }

                                                                ele = eduform[selected_id];
                                                                var toAppend = \"\";
                                                                for (var key in ele)
                                                                {
                                                                    var val = ele[key];
                                                                    toAppend += '<option value = \"' + key + '\">' + val + '</option>';
                                                                }
                                                                if(!also_show[selected_id])
                                                                {
                                                                    jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').empty();
                                                                    jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').html(toAppend).show();
                                                                    also_show[selected_id] = true;
                                                                }
                                                                else
                                                                {
                                                                    jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').hide();
                                                                }
                                                             }
                                                            else
                                                                jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').hide();
                                                        }";
                                                        }
                                                        $add_spec .=  "var exist_sp = new Array();";
                                                        for($s=0;$s<$field['DEFAULT_SELECTION'];$s++)
                                                            $add_spec .=  "exist_sp[$s] = new Array();";
                                        $add_spec .= "</script>";

                                        $add_spec .=  '';
                                        $faculty .= '<DIV id="add_spec" style="display:block;">'.$add_spec.'</DIV>';
                                        $faculty .= "<div id=\"add_more\" style=\"display:none;\">".$button->createSimpleText(_('Add more'),'#','i++;AddSpec(i);')."</div>";
                                        $faculty .= '</div>';

                                        echo $faculty;
                                    }
                                    elseif($_REQUEST['servicemod'] == 'mod_apply/AddApp.php' || $_REQUEST['servicemod'] == 'mod_apply/Applicants.php')
                                    {
                                        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'] = false;
                                        }
                                        /*Старый вариант{Подразделение->Факультет->Специальность->Форма обучения}*/
                                      /*  if(get_student_id())
                                            $data_array = db_request(db_execute("SELECT * FROM student_spec_fields WHERE STUDENT_ID = '".get_student_id()."' ORDER BY ID"),array('SCHOOL_ID'=>'_makeSelInput','FACULTY_ID'=>'_makeFacInput','SPECIALTY_ID'=>'_makeSpecInput','TYPE_OF_STUDY'=>'_makeTOSInput'),array());
                                        else
                                            $data_array = array();

                                        $columns = array('SCHOOL_ID'=>'Подразделение','FACULTY_ID'=>'Факультет','SPECIALTY_ID'=>'Специальность','TYPE_OF_STUDY'=>'Форма обучения');
                                        $link['add']['html']['SCHOOL_ID'] = _makeSelInput('','SCHOOL_ID');
                                        $link['add']['html']['FACULTY_ID'] = _makeFacInput('','FACULTY_ID');
                                        $link['add']['html']['SPECIALTY_ID'] = _makeSpecInput('','SPECIALTY_ID');
                                        $link['add']['html']['TYPE_OF_STUDY'] = _makeTOSInput('','TYPE_OF_STUDY');
                                        if((!count($data_array) &&  $_REQUEST['servicemod']<>'mod_apply/Applicants.php' && $_REQUEST['servicemod']<>'mod_apply/Students.php') || ($_REQUEST['servicemod']=='mod_apply/AddApp.php' && $field['DEFAULT_SELECTION'] && is_numeric($field['DEFAULT_SELECTION'])) ||($_REQUEST["include"]=='stugeneralinfotab' && $_REQUEST['servicemod']=='mod_apply/Applicants.php'))
                                        {
                                            for($i=1;$i<=$field['DEFAULT_SELECTION'];$i++)
                                            {
                                                foreach($link['add']['html'] as $column=>$v)
                                                {
                                                    $data_array[$i][$column] = str_replace(array("_new_","[new]"),array("_new".$i."_","[new][".$i."]"),$link['add']['html'][$column]);
                                                    //$data_array[$i][$column] = str_replace(,,$link['add']['html'][$column]);
                                                }
                                            }
                                        }

                                        if(get_student_id())
                                        {
                                            $link['remove']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&include=$_REQUEST[include]&category_id=$_REQUEST[category_id]&servicefunction=delete&GridOutputCount=".$_REQUEST['GridOutputCount']."&delete_faculty_fields=true";
                                            $link['remove']['variables'] = array('id'=>'ID');
                                        }
                                        else
                                        {
                                            unset($link);
                                        }
                                        if(count($log_array)>0)
                                                    $lo_options['count'] = false;
                                            $lo_options['middle'] = '<font color=#3f3f3f>'.$field['TITLE'].'</font>';
                                        Gridoutput($data_array,$columns,$field['TITLE'].' '._('Entryes'),$field['TITLE'].' '._('Entries'),$link,array(),$lo_options);
                                        echo '<BR>';
                                        echo "<script language='JavaScript' src='".(($_REQUEST['servicemod'] == 'applicants_online')?$IntegralPathWeb:'')."js/selectChain.js'></script>";
                                        if($_REQUEST['servicemod'] !== 'applicants_online')
                                        {
                                            echo "<script language='JavaScript'>
                                            var mass =new Array();";
                                            if($field['DEFAULT_SELECTION'] && is_numeric($field['DEFAULT_SELECTION']))
                                            {
                                                for($i=1;$i<=$field['DEFAULT_SELECTION'];$i++)
                                                {

                                                    echo "jQuery.getScript(\"".(($_REQUEST['servicemod'] == 'applicants_online')?$IntegralPathWeb:'')."ajax.php?function_=genjs&id=new$i\", function(data){});";
                                                }
                                            }
                                            echo "jQuery.getScript(\"".(($_REQUEST['servicemod'] == 'applicants_online')?$IntegralPathWeb:'')."ajax.php?function_=genjs&id=new\", function(data){});";
                                            echo "
                                            function openline(id)
                                            {
                                                if(mass['fac'+id] != 'ok'){
                                                    jQuery('#innerdivfaculty_'+id+'_FACULTY_ID').trigger('click');
                                                    mass['fac'+id] = 'ok';
                                                }
                                                if(mass['sch'+id] != 'ok'){
                                                    jQuery('#innerdivfaculty_'+id+'_SCHOOL_ID').trigger('click');
                                                    mass['sch'+id] = 'ok';
                                                }
                                                if(mass['spec'+id] != 'ok'){
                                                    jQuery('#innerdivfaculty_'+id+'_SPECIALTY_ID').trigger('click');
                                                    mass['spec'+id] = 'ok';
                                                }
                                                if(mass['tos'+id] != 'ok'){
                                                    jQuery('#innerdivfaculty_'+id+'_TYPE_OF_STUDY').trigger('click');
                                                    mass['tos'+id] = 'ok';
                                                }
                                            }
                                            function get(id){
                                                jQuery.getScript(\"ajax.php?function_=genjs&id=\"+id, function(data){});
                                            }
                                            </script>";
                                        }*/
                                        /*Старый вариант{Подразделение->Факультет->Специальность->Форма обучения}*/
                                        /*Новый вариант{Группа->Специальность->Специальизация->Форма обучения}*/
                                        $_SESSION['PRIORITY']['count'] = 0;
                                        if(get_student_id())
                                            $data_array = db_request(db_execute("SELECT ID,STUDENT_ID,EDU_FORM_ID,GROUP_ID,GROUP_ID AS JS_GROUP_ID,SPECIALTY_ID,SPECIALIZATION_ID,TYPE_OF_STUDY,PRIORITY, PRIORITY AS JS_PRIORITY FROM student_spec_fields WHERE STUDENT_ID = '".get_student_id()."'  AND  SCHOOL_YEAR='".get_school_year()."' ORDER BY GROUP_ID,PRIORITY"),array('SCHOOL_ID'=>'_makeSelInput','FACULTY_ID'=>'_makeFacInput','SPECIALTY_ID'=>'_makeSpecInput','TYPE_OF_STUDY'=>'_makeTOSInput','GROUP_ID'=>'_makeAdmGroupInput','SPECIALIZATION_ID'=>'_makeSpecializationInput','PRIORITY'=>'_makePriorityInput'),array());//,'EDU_FORM_ID'=>'_makeSelectEduForms'
                                        else
                                            $data_array = array();
                                        echo "<script>";
                                        echo "var priority_array = new Array();var java_edu_form_selector = new Array();";
                                        if(count($data_array))
                                        {
                                            foreach ($data_array as $index=>$info)
                                            {
                                                if(!$set[$info['JS_GROUP_ID']])
                                                {
                                                    echo "priority_array[".$info['JS_GROUP_ID']."] = new Array();\n";
                                                    $set[$info['JS_GROUP_ID']] = true;
                                                }
                                                echo "priority_array[".$info['JS_GROUP_ID']."][".$info['JS_PRIORITY']."] = ".$info['JS_PRIORITY'].";\n";
                                            }
                                        }
                                        echo "</script>";
                                        $columns = array('GROUP_ID'=>_('Competitive Group'),'SPECIALTY_ID'=>_('Major'),'SPECIALIZATION_ID'=>_('Special Subject'),'TYPE_OF_STUDY'=>_('Form of Education'),'PRIORITY'=>_('Priority'));//,'EDU_FORM_ID'=>'Edu Forms'
                                        $link['add']['html']['GROUP_ID'] = _makeAdmGroupInput('','GROUP_ID');
//                                        $link['add']['html']['EDU_FORM_ID'] = _makeSelectEduForms('','EDU_FORM_ID');
                                        $link['add']['html']['SPECIALTY_ID'] = _makeSpecInput('','SPECIALTY_ID',false,true);
                                        $link['add']['html']['SPECIALIZATION_ID'] = _makeSpecializationInput('','SPECIALIZATION_ID',false,true);
                                        $link['add']['html']['TYPE_OF_STUDY'] = _makeTOSInput('','TYPE_OF_STUDY',false,true);
                                        $link['add']['html']['PRIORITY'] = _makePriorityInput((!count($data_array)?'':count($data_array)+1),'PRIORITY');
                                        if((!count($data_array) &&  $_REQUEST['servicemod']<>'mod_apply/Applicants.php' && $_REQUEST['servicemod']<>'mod_apply/Students.php') || ($_REQUEST['servicemod']=='mod_apply/AddApp.php' && $field['DEFAULT_SELECTION'] && is_numeric($field['DEFAULT_SELECTION'])) ||($_REQUEST["include"]=='stugeneralinfotab' && $_REQUEST['servicemod']=='mod_apply/Applicants.php'))
                                        {
                                            for($i=1;$i<=$field['DEFAULT_SELECTION'];$i++)
                                            {
                                                foreach($link['add']['html'] as $column=>$v)
                                                {
                                                    $data_array[$i][$column] = str_replace(array("_new_","[new]","value=\"1\""),array("_new".$i."_","[new][".$i."]","value=\"$i\""),$link['add']['html'][$column]);
                                                    //$data_array[$i][$column] = str_replace(,,$link['add']['html'][$column]);
                                                }
                                            }
                                        }

                                        if(get_student_id())
                                        {
                                            $link['remove']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&include=$_REQUEST[include]&category_id=$_REQUEST[category_id]&servicefunction=delete&GridOutputCount=".$_REQUEST['GridOutputCount']."&delete_faculty_fields=true";
                                            $link['remove']['variables'] = array('id'=>'ID');
                                        }
                                        else
                                        {
                                            unset($link);
                                        }
                                        if(count($log_array)>0)
                                                    $lo_options['count'] = false;
                                        $lo_options = array('search'=>false,'xscroll'=>false,'sort'=>false,'yscroll'=>false,'save'=>false);
                                        $lo_options['middle'] = '<font color=#3f3f3f>'.$field['TITLE'].'</font>';
                                        Gridoutput($data_array,$columns,_('Competitive Group Entries'),_('Amount of Competitive Group Entries'),$link,array(),$lo_options);
                                        echo '<input type="hidden" id="inputstudents_faculty" value="">';
                                        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;
                                        }
                                        echo '<BR>';
                                        echo "<script language='JavaScript' src='".(($_REQUEST['servicemod'] == 'applicants_online')?$IntegralPathWeb:'')."js/selectChain.js'></script>";
                                        echo "<script language='JavaScript'>
                                                var faculty = 'inputstudents[CFIELD_".$field['ID']."]';
                                                var valu;
                                                var ids;
                                                var flag;
                                                var mass =new Array();";
                                                $groups_array = array();
                                                $groups_array = db_request(db_execute("SELECT ID FROM APP_ADM_GROUPS"),array(),array('ID'));
                                                $edu_forms = array();
                                                $edu_forms = db_request(db_execute("select aef.TITLE,aef.ID,aef.SHORT_NAME,sy.GROUP_ID from edu_forms_in_spec efis,app_edu_forms aef,specialty sy,specialization sz where sy.id = sz.SPECIALTY_ID AND efis.SPECIALIZATION_ID = sz.id AND efis.EDU_FORM_ID = aef.ID AND sy.GROUP_ID IS NOT NULL"),array(),array('GROUP_ID'));
                                                echo "var eduform = new Array(); \n";
                                                foreach($groups_array as $group_id=>$other)
                                                {
//                                            	    echo "alert('".$group_id."');";    
                                                    echo "eduform[$group_id] = new Array(); \n";
                                                    if($edu_forms[$group_id])
                                                    {
                                                	foreach($edu_forms[$group_id] as $index=>$sval)
                                                	{
                                                    	    if($sval['ID']<>'' && $sval['TITLE']<>'')
                                                        	echo "eduform[$group_id][".$sval['ID']."] = '".$sval['TITLE']."';\n";
                                                	}
                                            	    }
                                            	}
                                                        echo "var exist_sp = new Array();";
                                                        for($s=0;$s<$field['DEFAULT_SELECTION'];$s++)
                                                            echo "exist_sp[$s] = new Array();";
                                                        echo "
                                                             function change_specialty(count,in_value,id)
                                                             {
                                                                exist_sp = new Array();
                                                                var line_id = parseInt(id.substr(3,4));
                                                                {
                                                                    jQuery('#inputfaculty_'+id+'_SPECIALTY_ID option:selected').each(function (){\n
                                                                        var starts = line_id;
                                                                        for(var i = 1;i<=starts;i++)
                                                                        {
                                                                            jQuery('#inputfaculty_new'+i+'_SPECIALTY_ID option:selected').each(function (){
                                                                                if(this.value !== '')
                                                                                    exist_sp[i]=this.value;
                                                                                else
                                                                                    exist_sp[i]= new Array();
                                                                            });
                                                                        }
                                                                        var start = line_id+1;
                                                                        var options = new Array();
                                                                        jQuery('#inputfaculty_new1_SPECIALTY_ID option').each(function (){options[this.value] = this.text;});
                                                                        var ex,ex2,ex3;
                                                                        for (var key in options){
                                                                            var val = options [key];
                                                                            ex += key+' = '+val;
                                                                        }
                                                                        for (var key in exist_sp){
                                                                            var val = exist_sp[key];
                                                                            ex2 += ' [ '+key+' = '+val+' ]';
                                                                            if(val!=='' && options[val]!=='"._('N/A')."'){delete options[val];}
                                                                        }
                                                                        var toAppend = '';
                                                                        for (var key in options){
                                                                            var val = options [key];
                                                                            toAppend += '<option value = \"' + key + '\">' + val + '</option>';
                                                                        }
                                                                        for(i = start;i<=count;i++){ //идем по элементам которые идут после изменяемого
                                                                            jQuery('#inputfaculty_new'+i+'_SPECIALTY_ID').empty().html(toAppend);//отчистка специальностей и добавление специальностей
                                                                            jQuery('#inputfaculty_new'+i+'_SPECIALIZATION_ID').empty().html('<option value = \"\">"._('N/A')."</option>'); //Зануление и добавление Н/Д к специализациям
                                                                            jQuery(\"#inputfaculty_new\"+i+\"_SPECIALTY_ID :contains('"._('N/A')."')\").attr(\"selected\", \"selected\");
                                                                            jQuery('#divfaculty_new'+i+'_TYPE_OF_STUDY').hide(); // Скрытие форм обучения
                                                                            var pri_hide = false;
                                                                            jQuery('#inputfaculty_new'+i+'_SPECIALTY_ID option:selected').each(function (){ //получаем выбранные элементы специальности
                                                                            //Logme(this.text);
                                                                                if(this.text == '"._('N/A')."') pri_hide = true;//если равно Н/А  то флаг переводим в тру
                                                                            });

                                                                            if(pri_hide == true)
                                                                            {
                                                                            //faculty_new1_PRIORITY
                                                                                jQuery('#divfaculty_new'+i+'_PRIORITY').hide(); //Если закоментить строчку приоритеты не будут исчезать
                                                                            }
                                                                        }
                                                                    });
                                                                    }
                                                             }
                                                        ";
                                                if($_REQUEST['servicemod'] !== 'applicants_online')
                                                {
                                                    if($field['DEFAULT_SELECTION'] && is_numeric($field['DEFAULT_SELECTION']) && $_REQEST['prev_servicemod']=='mod_apply/AddApp.php')
                                                    {
                                                        for($i=1;$i<=$field['DEFAULT_SELECTION'];$i++)
                                                        {
                                                            echo "jQuery.getScript(\"".(($_REQUEST['servicemod'] == 'applicants_online')?$IntegralPathWeb:'')."ajax.php?function_=genjs&id=new$i&count=".$field['DEFAULT_SELECTION']."\", function(data){".(($i>1)?"jQuery('#inputfaculty_new'+".$i."+'_GROUP_ID').attr('disabled', 'disabled');jQuery('#inputfaculty_new'+".$i."+'_EDU_FORM_ID').attr('disabled', 'disabled');":"")."});";//
                                                        }
                                                    }
                                                    else
                                                    {
                                                        echo "jQuery.getScript(\"".(($_REQUEST['servicemod'] == 'applicants_online')?$IntegralPathWeb:'')."ajax.php?function_=genjs&id=new\", function(data){});";
                                                    }
                                                     if(SystemPreferences('BLOCKGROUP', 'applicants', true)=='Y')
                                                    {
                                                        echo "function change_groups(count,in_value,id){\n";
                                                        //добавление EDU_FORMS
                                                        {
                                                        echo "
                                                            var selected_id;
                                                            var ele;
                                                            //Logme('<b>EVENT CHANGE GROUPS</b>)('+count+','+in_value+','+id+')');
                                                            if(in_value!=='Н/Д' && in_value!=='')
                                                            {
                                                                flag = 'true';
                                                                jQuery('#inputfaculty_'+id+'_GROUP_ID option:selected').each(function ()
                                                                {\n
                                                                    selected_id = this.value;
                                                                });
                                                                if (typeof priority_array == 'undefined')
                                                                    jQuery('#inputfaculty_new_PRIORITY').val('1');
                                                                else
                                                                {
                                                                    if (typeof priority_array[selected_id] == 'undefined')
                                                                        jQuery('#inputfaculty_new_PRIORITY').val('1');
                                                                    else
                                                                    {
                                                                        var max_new = 1;
                                                                        priority_array[selected_id] = priority_array[selected_id].sort()
                                                                        for (var key in priority_array[selected_id])
                                                                        {
                                                                            var val = priority_array[selected_id][key];
                                                                            //Logme('key=>'+key+' val=>'+val);
                                                                            if(val > max_new)
                                                                                max_new = val;
                                                                            //Logme('max_new = '+max_new);

                                                                        }
                                                                        jQuery('#inputfaculty_new_PRIORITY').val(max_new+1);
                                                                    }
                                                                }
                                                                    
                                                                //inputfaculty_new_PRIORITY
                                                                ele = eduform[selected_id];
                                                                var toAppend = \"\";
                                                                for (var key in ele)
                                                                {
                                                                    var val = ele[key];
                                                                    var selected = '';
                                                                    if(java_edu_form_selector[id]==key)
                                                                        selected = 'selected';
                                                                    else
                                                                        selected = '';
                                                                    //Logme(java_edu_form_selector[id] + '_' + id + '_' + key + '_' + selected);
                                                                    toAppend += '<option value = \"' + key + '\" ' + selected + '>' + val + '</option>';
                                                                }
                                                                jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').empty();
                                                                jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').html(toAppend).show();
                                                             }
                                                            else
                                                                jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').hide();";
                                                        }
                                                        //Блокировка и скрытие остальных групп
                                                        {
                                                        echo "
                                                            for(var el=2;el<=count;el++)
                                                            {
                                                                if(in_value!=='"._('N/A')."' && in_value!=='')
                                                                {
                                                                    
                                                                    jQuery('#inputfaculty_new'+el+'_GROUP_ID').removeAttr(\"disabled\");
                                                                    jQuery('#inputfaculty_new'+el+'_GROUP_ID').attr('disabled','');
                                                                    jQuery('#inputfaculty_new'+el+'_GROUP_ID').html('<option value=\"'+selected_id+'\">'+in_value+'</option>').hide();
                                                                    jQuery('#inputfaculty_new1_EDU_FORM_ID').trigger('change');
                                                                }
                                                            ";
                                                            if($DBType == 'mssql')
                                                            {
                                                                //echo "jQuery('#inputfaculty_new1_SPECIALTY_ID');\n";
                                                                //.trigger('change');
                                                                //echo "jQuery('#inputfaculty_new'+el+'_GROUP_ID');\n";
                                                                //.trigger('change')
                                                            }
                                                        echo "}\n";
                                                        }
                                                    echo "}\n";
                                                    echo "
                                                        jQuery('#inputfaculty_new1_EDU_FORM_ID').change(function(){
                                                            for(var el=2;el<=count;el++)
                                                            {
                                                                jQuery('#inputfaculty_new1_EDU_FORM_ID option:selected').each(function ()
                                                                {\n
                                                                    efselected_id = this.value;
                                                                    eftext = this.text;
                                                                });
                                                                jQuery('#inputfaculty_new'+el+'_EDU_FORM_ID').removeAttr(\"disabled\");
                                                                jQuery('#inputfaculty_new'+el+'_EDU_FORM_ID').attr('disabled','');
                                                                jQuery('#inputfaculty_new'+el+'_EDU_FORM_ID').html('<option value=\"'+efselected_id+'\">'+eftext+'</option>').hide();
                                                            }
                                                        });

                                                        ";
                                                    }
                                                    else
                                                    {
                                                         echo "function change_groups(count,in_value,id){\n";
                                                         echo "//Logme('id=>'+id+'count=>'+count+'in_value=>'+in_value)";
                                                        //добавление EDU_FORMS
                                                        {
                                                        echo "
                                                            var selected_id;
                                                            var ele;
                                                            if(in_value!=='Н/Д' && in_value!=='')
                                                            {
                                                                flag = 'true';
                                                                jQuery('#inputfaculty_'+id+'_GROUP_ID option:selected').each(function ()
                                                                {\n
                                                                    selected_id = this.value;
                                                                });
                                                                ele = eduform[selected_id];
                                                                var toAppend = \"\";
                                                                for (var key in ele)
                                                                {
                                                                    var val = ele[key];
                                                                    toAppend += '<option value = \"' + key + '\">' + val + '</option>';
                                                                }
                                                                jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').empty();
                                                                jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').html(toAppend).show();
                                                             }
                                                            else
                                                                jQuery('#inputfaculty_'+id+'_EDU_FORM_ID').hide();";
                                                        }
                                                         echo "}\n";
                                                    }
                                                    echo "
                                                        var change = new Array();
                                                    function openline(id)
                                                    {
                                                        if(mass['sch'+id] != 'ok'){
                                                            jQuery('#innerdivfaculty_'+id+'_GROUP_ID').trigger('click').trigger('change');
                                                            mass['sch'+id] = 'ok';
                                                        }
                                                        if(mass['eduform'+id] != 'ok'){
                                                            jQuery('#innerdivfaculty_'+id+'_EDU_FORM_ID').trigger('click').trigger('change');
                                                            mass['eduform'+id] = 'ok';
                                                        }
                                                        if(mass['spec'+id] != 'ok'){
                                                            jQuery('#innerdivfaculty_'+id+'_SPECIALTY_ID').trigger('click').trigger('change');
                                                            mass['spec'+id] = 'ok';
                                                        }
                                                        if(mass['fac'+id] != 'ok'){
                                                            jQuery('#innerdivfaculty_'+id+'_SPECIALIZATION_ID').trigger('click').trigger('change');
                                                            mass['fac'+id] = 'ok';
                                                        }
                                                        if(mass['tos'+id] != 'ok'){
                                                            jQuery('#innerdivfaculty_'+id+'_TYPE_OF_STUDY').trigger('click').trigger('change');
                                                            mass['tos'+id] = 'ok';
                                                        }
                                                        if(mass['prio'+id] != 'ok'){
                                                            jQuery('#innerdivfaculty_'+id+'_PRIORITY').trigger('click').trigger('change');
                                                            mass['prio'+id] = 'ok';
                                                        }
                                                    }
                                                    function get(id)
                                                    {
                                                        jQuery.getScript(\"ajax.php?function_=genjs&exist_line=true&id=\"+id, function(data){});
                                                    }
                                                    </script>";
                                                }
                                        /*Новый вариант{Группа->Специальность->Специальизация->Форма обучения}*/
                                    }
                                break;
				case 'log':
				$log_functions = array();
				$newLogField = _sortLogFieldsBySOrder($field);

					$link = array();
					$columns = array();
					$count_fields = 0;
					$table = $field['ID'];
					$sum_log = array();

					$functions = array('radio'=>'_makeLogCheckbox',
					'select'=>'_makeLogSelect',
					'date'=>'_makeLogDate',
					'text'=>'_makeLogText',
                                        'numtotext'=>'_makeLogNumToText',
                                        'textandcount'=>'_makeCountText',
					'numeric'=>'_makeNumText',
					'textarea'=>'_makeLogTextArea',
					'time'=>'_makeTimeInput'
					);
					if (!$newLogField) $newLogField = array();
					foreach ($newLogField as $fKey => $fValue)
					{

						switch ($fValue['TYPE']) {
							case 'radio':
								$count_fields++;
								$log_functions[$fKey] = $functions['radio'];
								$columns[$fKey] = $fValue['TITLE'];
								$link['add']['html'][$fKey] = $functions['radio']('',$fKey);
							break;

							case 'select':
								$count_fields++;
                                                                if($fValue["SIZE"]<>'')
                                                                {
                                                                    $_SESSION['SIZE'][$table][$fKey] = $fValue["SIZE"];
                                                                    $_SESSION['SIZE'][$table]['new'][$fKey] = $fValue["SIZE"];
                                                                }
								$logOpt_array = db_request(db_execute("SELECT SELECT_OPTIONS FROM LISTING_FIELDS_SETTINGS
													WHERE STUDENT_ID = '".$field['ID']."' AND HTML_FIELD_TITLE = '".$html_field_title."' AND FIELD_NAME = '".$fKey."'"));
//echo "=====>".$logOpt_array[1]['SELECT_OPTIONS'];
								$log_options[$fKey] = $logOpt_array[1]['SELECT_OPTIONS'];
								$log_functions[$fKey] = $functions['select'];
								$columns[$fKey] = $fValue['TITLE'];
								$link['add']['html'][$fKey] = $functions['select']('',$fKey);
							break;

							case 'date':
								$log_array = db_request(db_execute("SELECT ID,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 FROM ".$log_table." WHERE ".$log_student_id_field."='".$get_student_id."' AND ".$student_field_id_field."='".$field['ID']."' ORDER BY ID ASC"),$log_functions);
								$count_fields += 2;
								$log_functions[$fKey] = $functions['date'];
								$columns[$fKey] = $fValue['TITLE'];
									if(!count($log_array) && $field['DEFAULT_SELECTION'] && is_numeric($field['DEFAULT_SELECTION'])) // so that the extra calendars aren't created -- these break the other calendars
										$link['add']['html'][$fKey] = true;
									else
										$link['add']['html'][$fKey] = $functions['date']('',$fKey);
							break;

							case 'text':

								$count_fields++;
                                                                if($fValue["SIZE"]<>'')
                                                                {
                                                                    $_SESSION['SIZE'][$table][$fKey] = $fValue["SIZE"];
                                                                }
                                                                if($fValue["COUNT_TOTAL"] == 'Y')
                                                                {
                                                                    $log_functions[$fKey] = $functions['textandcount'];
                                                                    unset($_SESSION['COUNT'][$fKey]);
                                                                    $sum_log = array();
                                                                    //$link['count']['html'][$fKey] = get_log_count($fKey,get_student_id(),$field['ID']);
                                                                    $link['count']['html'][$fKey] = true;
                                                                }
                                                                else
                                                                    $log_functions[$fKey] = $functions['text'];
								$columns[$fKey] = $fValue['TITLE'];
								$link['add']['html'][$fKey] = $functions['text']('',$fKey);
							break;

							case 'numeric':
								$count_fields++;
                                                                if($fValue["SIZE"]<>'')
                                                                {
                                                                    $_SESSION['SIZE'][$table][$fKey] = $fValue["SIZE"];
                                                                }
                                                                if($fValue["COUNT_TOTAL"] == 'Y')
                                                                {
                                                                    $log_functions[$fKey] = $functions['textandcount'];
                                                                    unset($_SESSION['COUNT'][$fKey]);
                                                                    $sum_log = array();
                                                                    $link['count']['html'][$fKey] = 'true';
                                                                }
                                                                else
								$log_functions[$fKey] = $functions['numeric'];
								$columns[$fKey] = $fValue['TITLE'];
								$link['add']['html'][$fKey] = $functions['numeric']('',$fKey);
                                                                
							break;

							case 'textarea':
								if($count_fields<3)
									$textarea_extra = 'cols=60 rows=7';
								elseif($count_fields<5)
									$textarea_extra = 'cols=35 rows=4';
								else
									$textarea_extra = 'cols=25 rows=4';
								$log_functions[$fKey] = $functions['textarea'];
								$columns[$fKey] = $fValue['TITLE'];
								$link['add']['html'][$fKey] = $functions['textarea']('',$fKey);
							break;

							case 'time':
								$count_fields++;
								$log_functions[$fKey] = $functions['time'];
								$columns[$fKey] = $fValue['TITLE'];
								$link['add']['html'][$fKey] = $functions['time']('',$fKey);
							break;
						}
					}
					$link['remove']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&include=$_REQUEST[include]&category_id=$_REQUEST[category_id]&servicefunction=delete&GridOutputCount=".$_REQUEST['GridOutputCount']."&delete_list_fields=true";
					$link['remove']['variables'] = array('id'=>'ID');
                                        if($field['MAX_RECORD']<>'')
                                            $log_array = db_request(db_execute(db_limit("SELECT ID,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 FROM ".$log_table." WHERE ".$log_student_id_field."='".$get_student_id."' AND ".$student_field_id_field."='".$field['ID']."' ORDER BY ID ASC",$field['MAX_RECORD'])),$log_functions);
                                        else
                                            $log_array = db_request(db_execute("SELECT ID,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 FROM ".$log_table." WHERE ".$log_student_id_field."='".$get_student_id."' AND ".$student_field_id_field."='".$field['ID']."' ORDER BY ID ASC"),$log_functions);
                                        if(count($log_array) >= $field['MAX_RECORD'] && $field['MAX_RECORD']<>'')
                                        {
                                            unset($link['add']['html']);
                                        }
                                        if($_REQUEST['servicemod'] == 'applicants_online' || !(get_student_id() || get_user_id()))
                                            $log_array = array();
					$lo_options = array('search'=>false,'xscroll'=>false);
                                        if(!$link['count']['html'])$link['count']['html']=array();
                                        foreach($link['count']['html'] as $key => $lf_val)
                                        {
                                            
                                            $link['count']['html'][$key] = $sum_log[$key];
                                        }
					if(!count($log_array) && $field['DEFAULT_SELECTION'] && is_numeric($field['DEFAULT_SELECTION']))
					{
						for($i=1;$i<=$field['DEFAULT_SELECTION'];$i++)
						{
							foreach($link['add']['html'] as $column=>$v)
							{
								//if(substr($column,0,8)=='date')
                                                                //$log_array[$i]['LOG_FIELD0'] = '<img border="0" width="15" vspace="0" class="GridOutput_fieldint" src="images/add_button.gif" style="width: 15px; height: 15px;">';
								if($v=='date')
								{
									$count_fields += 2;
									$log_functions['date'] = $functions['date'];
									$columns['LOG_FIELD'.$i] = $field['LOG_FIELD'.$i.'_TITLE'];
									//$log_array[$i][$column] = str_replace("[new]","[new".$i."]",$functions['date']('',$v));
									$log_array[$i][$column] = str_replace("[new]","[new".$i."]",$functions['date']('',$column));
								}
								else
									$log_array[$i][$column] = str_replace("[new]","[new".$i."]",$link['add']['html'][$column]);
							}
						}
						unset($link['add']['html']);
                                                unset($link['count']['html']);
						unset($link['remove']);
						$lo_options['save'] = false;
						$lo_options['sort'] = false;
					}
					if(count($log_array)>0)
						$lo_options['count'] = false;
					$lo_options['middle'] = '<font color=#3f3f3f>'.$field['TITLE'].'</font>';
                                        //var_dump($log_array);
					Gridoutput($log_array,$columns,$field['TITLE'].' '._('Entry'),$field['TITLE'].' '._('Entries'),$link,array(),$lo_options);
					echo '<BR>';
                                        unset($log_functions);
				break;

				case 'radio':
					echo _makeCheckboxInput('CFIELD_'.$field['ID'],$field['TITLE']);
				break;

				case 'holder':
//					echo '<p style="float:right;"></p>';
//					echo '';
				break;
			}
			echo '</TD>';
//			echo "->".$category_array[1]['COLUMNS'];
			if($category_array[1]['COLUMNS']==0 || $category_array[1]['COLUMNS'])
//			if($count%$category_array[1]['COLUMNS']==0)
			{
				echo '</TR>';
				if($bgcolor=='style="background-color: #fff; background-image: none;"')

					$bgcolor = $bgstyle;

				else
					$bgcolor = 'style="background-color: #fff; background-image: none;"';


				echo '<TR '.$bgcolor.'>';
			}
			$count++;
		    } //end if
		}//end for() fields
		//echo '<TD style="border-width:1; border-color:black; border-style: solid none solid none;"></TD>';
		if($category_array[1]['COLUMNS']!='1')
		{
			if($count%3==2)
//				echo '<TD '.$bgcolor.'></TD><TD '.$bgcolor.'>1</TD>';
				echo '';
			elseif($count%3==0)
//				echo '<TD '.$bgcolor.'>2</TD>';
				echo '';
		}
		echo '</TR></TABLE>';
	}
}
?>