<?php

function _getEditsRules($idStr, $type)
{ 
	if($idStr[0] == ',')
		$idStr = substr($idStr, 1); 

	switch ($type)
	{
		case 1:
			$custTable = 'USER_FIELDS';
		break;
		
		case 2:
			$custTable = 'STUDENT_FIELDS';
		break;

		case 4 :
			$custTable = 'DISCIPLINE_INCIDENT_FIELDS';
		break;

		default:
			$custTable = 'SCHOOL_FIELDS';
		break;
	}
	

	$sqlQuery = "SELECT id, field_edits FROM ".$custTable." WHERE id IN (".$idStr.")";
	
	if($idStr)
		$res = db_request(db_execute($sqlQuery));
	
	if($res)
	{
		foreach ($res as $item)
		{
			$resArr[$item['ID']] = $item['FIELD_EDITS'];
		}
		return $resArr;
	}
	else 
	{
		return 0;
	}
}

function _checkUserValueCorrespondsEditsRule($editsRes, $value, $sectionName, $prefixBorder = '')
{	global $border, $forceFieldName;

	$errorArr = array();
	// we have only FIELD_EDITS in this array 
	//$editsRule = $editsRes['FIELD_EDITS']; 
	$editsRule = $editsRes; 
	
	/* ignore the rule, with uncorrect syntax, marked the ## */
	if(preg_match('/##/', $editsRule))
	{
		return $errorArr = array();
	}

	$editsRule = str_replace('�','"', $editsRule);
	$editsRule = str_replace(chr(148),'"', $editsRule);
	
	//$editsRule = str_replace('***','"', $editsRule);
	$editsRule = str_replace('\\"','"', $editsRule);
	
	/* if user wants to compare value with some DATE */
	$editsRule = _changeDateField($editsRule);
	
	/* if user uses field name in the edits rule */
	$editsRule = _changeFieldNameField($editsRule);

	
	/* if user uses border in the edits rule */
	$editsRule = _changeBorderTag($editsRule, $sectionName, $prefixBorder);
	$editsRule = str_replace('{FIELD_VALUE}','$value', $editsRule);
	
	//echo $editsRule; die();
	
		$error = array();
		$warning = array();
		ob_start();
		eval($editsRule);
		$errorString = ob_get_contents();
		ob_clean();

		if(preg_match('/Parse/',$errorString))
		{
			//$error = "Sorry, there were some problems, please, contact with the admin. Your data wasn't saved";
			/* ignore the rule, with uncorrect syntax */
			return $errorArr;
		}
			
		if($override_error)
		{
			$errorArr[] = array("override_error" => array($override_error));
		}
		if($error)
		{
			$errorArr[] = array("err" => array($error));
		}
		if($warning)
		{
			$errorArr[] = array("warning" => array($warning));
		}

	return $errorArr;
}

function _changeDateField($editsRuleStr)
{
	if(preg_match_all("|{DATE{(.*)+}}|U", $editsRuleStr, $out))
	{
		foreach ($out[0] as $item)
		{
		/*
			if this user field will contain value with some data,
			Birthdate for example
		*/
			if($item === '{DATE{FIELD_VALUE}}')
			{	
				$datesArr[]	= $item;
			}
			else 
			{
				$date = str_replace('{DATE{','',$item);
				$datesArr[] = str_replace('}}','',$date);
			}
		}	
		/* we got all dates from user string, deleted all '-' symbols,
		   and now will compare the values
		*/
		//$str = $editsRule;
		$i = 0;
		foreach ($out[0] as $items)
		{	
			if($items === '{DATE{FIELD_VALUE}}')
			{
					$repString = 'str_replace("-","", $value)';
			}	
			else
			{
					$repString = str_replace('-','',$datesArr[$i]);
			}
				$editsRuleStr = str_replace($items, $repString, $editsRuleStr);								
				$i++;
		}
		
		return $editsRuleStr;
	
	}
	else
	{
		return $editsRuleStr;
	}
}


function _changeBorderTag($editsRuleStr, $sName, $prefixBorder = '') 
{ 
	if(preg_match_all("|{BORDER{(.*)+}}|U", $editsRuleStr, $out))
	{
		/*
			if this user field will contain value with the border tag
		*/	
	foreach($out[0] as $item)
	{
			$fieldName = str_replace('{BORDER{','',$item);
			$custField = str_replace('}}','',$fieldName);

			if($prefixBorder != '')
				$editsRuleStr = str_replace('{BORDER{'.$custField.'}}', '$border[] = "'.$prefixBorder.'['.$custField.']"', $editsRuleStr);	
			else 
				$editsRuleStr = str_replace('{BORDER{'.$custField.'}}', '$border[] = "'.$sName.'['.$custField.']"', $editsRuleStr);
	}
		return $editsRuleStr; 
	}
	else
		return $editsRuleStr;
}


function _changeFieldNameField($editsRuleStr)
{	
	if(preg_match_all("|{FIELD_NAME{(.*)+}}|U", $editsRuleStr, $out))
	{
		/*
			if this user field will contain value with field name,
			CFIELD_50003=='' && CFIELD_50007!='' for example
		*/	
		foreach($out[0] as $item)
		{
			$fieldName = str_replace('{FIELD_NAME{','',$item);
			$custField = str_replace('}}','',$fieldName);
				
			if($_SESSION['customValues'])
			{
				foreach ($_SESSION['customValues'] as $key => $custValue)
				{
					if($key == $custField)
					{
						$editsRuleStr = str_replace($item, '$_SESSION["customValues"]["'.$custField.'"]', $editsRuleStr);
					}
					else 
						continue;
				}
			}
		}
		
			/* the situation, when we haven't the $_SESSION['customValues'] array */
			if(preg_match_all("|{FIELD_NAME{(.*)+}}|U", $editsRuleStr, $outNew))
			{
				foreach($out[0] as $item)
				{
					$fieldName = str_replace('{FIELD_NAME{','',$item);
					$custField = str_replace('}}','',$fieldName);
					$editsRuleStr = str_replace($item, '$'.$custField, $editsRuleStr);			
				}
			}	 
		return $editsRuleStr;
	}
	else 
	{
		return $editsRuleStr;
	}
}


function _makeInternalArrayWithCustomFields($valuesArray)
{
	$customArray = array();
if($valuesArray){
	foreach($valuesArray as $column_name=>$value)
	{
		/* check only CFIELD_ fields */
		if(preg_match('/CFIELD/', $column_name))
		{
			$customArray[$column_name] = $value;
		}
	}			
}
	return $customArray;
}

function _getAllEditsRules($idArray, $type)
{
	$resWithEdits = '';
	if($idArray)
	{	
		$idArray = array_unique($idArray);
		$idArray = implode(",", $idArray);
		/*
			get all Edit Rules
		*/
		$resWithEdits = _getEditsRules($idArray, $type);	

		return $resWithEdits;
	}
	else
		return $resWithEdits;	
}

function _saveStudentEnteredValues($request)
{ global $_SYSTEM;
	
	$_SYSTEM['fieldNames'] = array(
		'students',
		'values',
		'assign_student_id',
		'STUDENT_REGISTRATION',
		'ADDRESS',	
		'STUDENTS_IN_ADDRESS',
		'STUDENTS_IN_SR',
		'STUDENT_RELATIONS',
		'month_values',
		'day_values',
		'year_values',
		'address_id',
		'log_values'
	);

	$_SYSTEM['assign_student_id']['assign_student_id'] = $request['assign_student_id'];
	
	$_SYSTEM['values']['values[STUDENT_REGISTRATION][new][START_DATE]'] = $request['year_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$request['month_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$request['day_values']['STUDENT_REGISTRATION']['new']['START_DATE'];
	
	$_SYSTEM['address_id']['address_id'] = $request['address_id'];
	
if ($request['values']) {
		foreach ($request['values'] as $vKey => $vValue)
	{
			if($vKey == 'STUDENT_REGISTRATION')
			{
				foreach ($vValue['new'] as $ikey => $iValue)
				{
					$_SYSTEM['values']['values[STUDENT_REGISTRATION][new]['.$ikey.']'] = $iValue; 
				}
			}
			elseif($vKey == 'ADDRESS')
			{
				foreach ($vValue as $ikey => $iValue)
				{
					$_SYSTEM['values']['values[ADDRESS]['.$ikey.']'] = $iValue; 
				}
			}
			elseif($vKey == 'STUDENTS_IN_ADDRESS')
			{
				foreach ($vValue as $ikey => $iValue)
				{
					$_SYSTEM['values']['values[STUDENTS_IN_ADDRESS]['.$ikey.']'] = $iValue; 
				}	
			}
			elseif($vKey == 'STUDENTS_IN_SR')
			{
				foreach ($vValue as $sjpKey => $sjpValue)
				{
					if($sjpKey == 'new')
					{
						foreach ($sjpValue as $iSjpKey => $iSjpValue)
						{
							$_SYSTEM['values']['values[STUDENTS_IN_SR][new]['.$iSjpKey.']'] = $iSjpValue; 
						}
					}
					elseif($sjpKey == 'new2')
					{
						foreach ($sjpValue as $iSjpKey => $iSjpValue)
						{
							$_SYSTEM['values']['values[STUDENTS_IN_SR][new2]['.$iSjpKey.']'] = $iSjpValue; 
						}
					}
					elseif($sjpKey == 'newe')
					{
						foreach ($sjpValue as $iSjpKey => $iSjpValue)
						{
							$_SYSTEM['values']['values[STUDENTS_IN_SR][newe]['.$iSjpKey.']'] = $iSjpValue; 
						}
					}
				}
			}
			elseif($vKey == 'STUDENT_RELATIONS')
			{
				foreach ($vValue as $pKey => $pValue)
				{
					if($pKey == 'new')
					{
						foreach ($pValue as $iPKey => $iPValue)
						{
							$_SYSTEM['values']['values[STUDENT_RELATIONS][new]['.$iPKey.']'] = $iPValue; 
						}
					}
					elseif($pKey == 'new2')
					{
						foreach ($pValue as $iPKey => $iPValue)
						{
							$_SYSTEM['values']['values[STUDENT_RELATIONS][new2]['.$iPKey.']'] = $iPValue; 
						}
					}
					elseif($pKey == 'newe')
					{
						foreach ($pValue as $iPKey => $iPValue)
						{
							$_SYSTEM['values']['values[STUDENT_RELATIONS][newe]['.$iPKey.']'] = $iPValue; 
						}
					}
				}
			}
	}
	}
	
	if(!$request['log_values']) $request['log_values'] = array();
	foreach ($request['log_values'] as $vKey => $vValue)
	{
		if(!$vValue['new']) $vValue['new'] = array();
		foreach ($vValue['new'] as $ikey => $iValue)
		{
			$_SYSTEM['log_values']['log_values['.$vKey.'][new]['.$ikey.']'] = $iValue; 
		}
	}
}

/*
	will make foreach and save all values into the $_SYSTEM, and will use them
	if there will be an error, while user add a new school, and we need to restore the 
	values
*/

function _saveSchoolsEnteredValues($request)
{	global $_SYSTEM;
	
$_SYSTEM['fieldNames'] = array(
		'schools',
		'values',
	);	
	if ($request['values']) {
		foreach ($request['values'] as $vKey => $vValue)
		{
			$_SYSTEM['values'][$vKey] = $vValue; 
		}
	}
	
}


/*
	will make foreach and save all values into the $_SYSTEM, and will use them
	if there will be an error, while user add a new school, and we need to restore the 
	values
*/

function _saveUsersEnteredValues($request)
{ global $_SYSTEM;
	
	$_SYSTEM['fieldNames'] = array(
		'user'
	);	

	foreach ($request['user'] as $vKey => $vValue)
	{
		if($vKey == 'SCHOOLS')
		{
			$keys = explode(',',$vValue);
			if($keys)
			{
				foreach ($keys as $schoolsV)
				{
					if(!empty($schoolsV))
					{
						$_SYSTEM['user']['user['.$vKey.']['.$schoolsV.']'] = 'Y';
					}
				}
			}
		}
		else
			$_SYSTEM['user'][$vKey] = $vValue; 
	}
}


/*
	get all fields ID from the $_REQUEST

	@param $_REQUEST
	@param string $ValueName - name for the $_SYSTEM index, like
					$_SYSTEM['students'] or $_SYSTEM['schools']

	
	@return array with IDs				
*/

function _getIDsForEditRules($request, $programValueName)
{	global $_SYSTEM;
	$fieldIdArr = array();
	if($request)
	{
		foreach($request as $column_name=>$value)
		{ 
			$_SYSTEM[$programValueName][$programValueName.'['.$column_name.']'] = $value;
			/* check only CFIELD_ fields */
			if(preg_match('/CFIELD/', $column_name))
			{
				$fieldId = explode('CFIELD_',$column_name);
				$fieldIdArr[] = $fieldId[1];
			}	
		}
	}
	return $fieldIdArr; 
}

/*
	show Error or Warning messages
	
	@param array $errorsArray - the array contains error or warning messages 
	@param bool show or not the additional message (it will be useful, when we add a New record)
	@param bool show or not error messages
	
	@return bool $go
*/

function _showErrorWarningMsg($errorsArray, $showAdditional = false, $showMessages = false)
{
	$go = true;
	/*
		if we have an override_error message, we will add it to the
		$errorsArray['err']
	*/
	if($errorsArray['override_error'])
	{ 
		if($showMessages)	
			echo ErrorMessage($errorsArray['override_error'], 'note');	

		$go = false;	
	}
	
	/* if we have an error message */		
	if($errorsArray['err'])
	{
		if($showAdditional)
			echo _('The record was not added because you have to correct the data and than try again.');

		if($showMessages)	
			echo ErrorMessage($errorsArray['err']);	

		$go = false;
	}
	/* if we have a warning msg  */
	if ($errorsArray['warning'])	
	{
		if($showMessages)
			echo ErrorMessage($errorsArray['warning'],'warning');
	 		
		if($errorsArray['err'] or $errorsArray['override_error'])
 			$go = false;
  		else 
 			$go = true;
	}		
	return $go;
}

/*
	check user values using Edits Rules and return the array with error and notice messages
	
	@param $_REQUEST
	@param string $borderName - field name prefix (like 'students' or 'schools'),
			 it's used for displaying a red border
	@param array $editRulesArray - array with the Edits Rules
	@param string $prefixBorder - need for Advanced Report part
	
	@return array $errorsArray - the array contains error or warning messages 
*/

function _executeEditRulesAndGetMsg($request, $borderName, $editRulesArray, $prefixBorder = '')
{ global $border,$forceFieldName;
	$errorArr = array();

	if($request)
	{
		foreach($request as $column_name=>$value)
		{
			/* check only CFIELD_ fields */
			if(preg_match('/CFIELD/', $column_name))
			{
				/* get only digit (id) from the column name in the $fieldId[1] */
				$fieldId = explode('CFIELD_',$column_name);
				//$resWithEdits = _getEditsRules($fieldId[1], 2);
				/*
					if we got the Edit Rule for this ($fieldId[1]) field
				*/
				if(!$editRulesArray) $editRulesArray = array();
				if(array_key_exists ($fieldId[1], $editRulesArray))
					$errStr = _checkUserValueCorrespondsEditsRule($editRulesArray[$fieldId[1]], $value, $borderName, $prefixBorder);
				if(!$errStr) $errStr = array();
				foreach($errStr as $errValue)
				{
			 		if($errValue['err'])
				 	{
				 		$errorArr['err'][] = $errValue['err'][0];					 		
				 		/*
							we will display a red border for this field
						*/
						$border[] = $borderName.'['.$column_name.']';
				 	}
						if($errValue['warning'])
							$errorArr['warning'][] = $errValue['warning'][0];
							
			 		if($errValue['override_error'])
				 	{
				 		$errorArr['override_error'][] = $errValue['override_error'][0];					 		
				 		/*
							we will display a red border for this field
						*/
						$border[] = $borderName.'['.$column_name.']';
						/*
							if there is an override_error, the DIV will != force
						*/
						$forceFieldName[] = array($borderName => $column_name);
				 		
				 	}
				}
			}
		}
	}

	return $errorArr;
}

function _getMaxSortOrder($cust_table, $joinTable, $categoryID)
{
	$catId = $categoryID;	
	//MAX(SORT_ORDER) AS MAX
	$sql = "SELECT COUNT(SORT_ORDER) AS MAX FROM $cust_table cf WHERE CATEGORY_ID = '".$catId."' OR cf.id IN (SELECT FIELD_ID FROM ".$joinTable." WHERE CATEGORY_ID = '".$catId."')";
	
	$res = db_request(db_execute($sql));

	if($res)
		return $res[1]['MAX'];
	else 		
		return 0;	
}

function _saveLoggingFields($request, $sqlString, $studId, $htmlSectName, $goValue, $logTableName, $studentFieldIdField)
{	global $DBType;
	
	if(!$goValue)
		return $sqlString;
		//var_dump($request);
	/* if user choosen the Pull-Down Type */	
	if($request['SELECT_OPTIONS'] or $request['DATEVALUE'])
	{
		$delSelctSrting = "DELETE FROM LISTING_FIELDS_SETTINGS WHERE
					student_id = '".$studId."' AND
					html_field_title = '".$htmlSectName."'";
		
		/* clear all the old values */
		db_execute($delSelctSrting);
		
		if($DBType == 'mssql')
			$sqlSelectString = "INSERT INTO LISTING_FIELDS_SETTINGS ";
		else	
			$sqlSelectString = "INSERT INTO LISTING_FIELDS_SETTINGS VALUES ";
	}
	
	/* if user wants to remove the field, we will unset its title, if it exist */
	foreach ($request['TYPE'] as $key => $value)
	{
		if($value == '')
		{
			db_execute("UPDATE $logTableName SET ".$key." = NULL 
						WHERE
						".$studentFieldIdField." = $studId");	
			
			$request['VALUE'][$key.'_TITLE'] = '';
		}
	}
        if(!$request['SELECT_CODES']){$request['SELECT_CODES']=array();}
	foreach ($request['SELECT_CODES'] as $key => $value)
	{
		if(empty($request['SELECT_OPTIONS'][$key]))
			unset($request['SELECT_CODES'][$key]);
	}
	
	foreach ($request as $rKey => $rValue)
	{
		if($rKey == 'TYPE')
		{
			foreach ($rValue as $typeKey => $typeValue)
			{
				$tmpTypeValues[] = $typeKey."='".$typeValue."' ";
			}
			 $sqlString .= implode(", ", $tmpTypeValues);
		}
		
		if($rKey == 'VALUE')
		{
			foreach ($rValue as $valKey => $valValue)
			{
				$tmpValValues[] = $valKey."='".$valValue."' ";
			}
			 $sqlString .= ', '.implode(", ", $tmpValValues);
		}
		
		if($rKey == 'SELECT_OPTIONS' or $rKey == 'DATEVALUE')
		{
			if($DBType == 'mssql')
			{
				foreach ($rValue as $selectKey => $selectValue)
				{
					$sqlSelectArray[$selectKey] =	"select ".
					$studId.",'".
					$htmlSectName."','".	
					$selectKey."','".
					$selectValue."'";
				}
			}
			else 
			{
				foreach ($rValue as $selectKey => $selectValue)
				{
					$sqlSelectArray[$selectKey] =	"(".
					$studId.",'".
					$htmlSectName."','".	
					$selectKey."','".
					$selectValue."'";
				}
			}
			
			
		}
		
		if($rKey == 'SELECT_CODES')
		{
			if($DBType == 'mssql')
			{
				foreach ($rValue as $codesKey => $codesValue)
				{
					if(!empty($codesValue))
						$sqlOptArray[$codesKey] = ",'".$codesValue."'";
				}
			}
			else 
			{	
				foreach ($rValue as $codesKey => $codesValue)
				{
					if(!empty($codesValue))
						$sqlOptArray[$codesKey] = ",'".$codesValue."')";
				}
			}
		}		
	}

	if($sqlSelectArray)
	{
		foreach ($sqlSelectArray as $cKey => $cValue)
		{	
			if(!isset($sqlOptArray[$cKey]))
				if($DBType == 'mssql')
				{
					$tmpArray[] = $sqlSelectArray[$cKey].",''";
				}
				else 
				{	
					$tmpArray[] = $sqlSelectArray[$cKey].",'')";
				}	
			else 
				$tmpArray[] = $sqlSelectArray[$cKey].$sqlOptArray[$cKey];
		}
	}
	
	if($tmpArray)
	{
		if($DBType == 'mssql')
		{
			$sqlSelectString .= implode(" UNION ALL ",$tmpArray);
			/* save all new select_options (and codes) in the LISTING_FIELDS_SETTINGS table */
			db_execute($sqlSelectString);
		}
		else 
		{
			foreach($tmpArray as $item)
			{
				$sqlSelectStringTmp = $sqlSelectString.$item;
				/* save all new select_options (and codes) in the LISTING_FIELDS_SETTINGS table */
				db_execute($sqlSelectStringTmp);
			}
		}
	}
	
	/*
	if($tmpArray)
	{
		if($DBType == 'mssql')
			$sqlSelectString .= implode(" UNION ALL ",$tmpArray);
		else 
			$sqlSelectString .= implode(",",$tmpArray);
		/* save all new select_options (and codes) in the LISTING_FIELDS_SETTINGS table 
		db_execute($sqlSelectString);
	}
	*/

        //var_dump($sqlString);
	return $sqlString;
}

function _makeLoggingEditInterface($retCode, $fieldTitle, $selectValues, $fieldId)
{
	if($retCode)
	{
		$ordValue = _getMinAndMaxValue($retCode);
		$maxValue = $ordValue['max'];
		$minValue = $ordValue['min'];
						
		$code = '';
		foreach ($retCode as $retKey => $retValue)
		{	
			$code .= '<TD rowspan="2" valign=top align=center style="border-width:1px;border-color:'.Preferences('HIGHLIGHT').';border-style:none inset none inset;">
                        <Table><TR><TD  align=center>
			<div align="center" style="width:70px;"> <div>
				<input type="hidden" name="logfilednamediv" id="'.$retKey.'">';
		
			if($retValue['SORT_ORDER'] != $minValue)
				$code .= '<a href="#" onclick="changeSortOrder(\'left\', \''.$retKey.'\');"><img src="images/arrow_left.gif" border="0"></a>&nbsp;&nbsp;&nbsp;';
			if($retValue['SORT_ORDER'] != $maxValue)
				$code .='<a href="#" onclick="changeSortOrder(\'right\', \''.$retKey.'\');"><img src="images/arrow_right.gif" border="0"></a>';
			
			$code .= '</div><B>'.$retValue['NAME'].'</B></div></TD></TR><TR><TD ><fieldset><legend>'.
			SelectInput($retValue['TYPE'],'logging[TYPE]['.$retKey.']',_('Data Type of Field').'</legend><center>',$selectValues,false,'onchange="checkFieldType(this.options[this.selectedIndex].value, \''.$retKey.'\')"',false) 			
			.'</center></fieldset></TD></TR><TR><TD align=center>'.
			TextInput($retValue['TITLE'],'logging[VALUE]['.$retKey.'_TITLE]',_('Field Title').'','',false)
                        .'</center></fieldset></TD></TR><TR><TD align=center>'.
                        (($retValue['TYPE']=='text' || $retValue['TYPE']=='numeric')?CheckboxInput($retValue['COUNT_TOTAL'],'logging[VALUE]['.$retKey.'_COUNT_TOTAL]',_('Sum Values').''):"").
                        (($retValue['TYPE']=='text' || $retValue['TYPE']=='numeric' || $retValue['TYPE']=='select')?TextInput($retValue['SIZE'],'logging[VALUE]['.$retKey.'_SIZE]',_('Input width').''):"").'<div id="loggingDiv'.$retKey.'">';
			
			$code.='</TD></TR><TR><TD align=center><br>';
			if($retValue['TYPE'] == 'select')
				$code .= _getLoggingPullDownOptions($fieldId, $fieldTitle, $retKey, 'select');
		
			if($retValue['TYPE'] == 'date')
				$code .= _getLoggingPullDownOptions($fieldId, $fieldTitle, $retKey, 'date');
				
			$code.=	'</div></TD></TR></TABLE></TD>';
		}	
	}
	return $code;
}

function _getMinAndMaxValue($fielsArray)
{
	foreach ($fielsArray as $key => $item)
		$tmpArr[] = $item['SORT_ORDER'];
		
	return array('max' => max($tmpArr), 'min' => min($tmpArr));
}

function _getLoggingPullDownOptions($studId, $sectionName, $fieldID, $type)
{
	$sql = "SELECT
					SELECT_OPTIONS, SELECT_CODES
				FROM
					LISTING_FIELDS_SETTINGS
				WHERE
					STUDENT_ID = '".$studId."' AND
					HTML_FIELD_TITLE = '".$sectionName."' AND
					FIELD_NAME = '".$fieldID."'";
	
	$loggingOptions = db_request(db_execute($sql));
	
	if($type == 'select')
	{	
		return $optCode = "
		<div id='loggingDiv'.$fieldID>
			<Table><TR><TD><fieldset><legend>
		       	"._('Pull-Down Choices:')."
			</legend>
			<textarea id='textarealogging[SELECT_OPTIONS][".$fieldID."]' name='logging[SELECT_OPTIONS][".$fieldID."]' cols='18' rows='3'>".$loggingOptions[1]['SELECT_OPTIONS']."</textarea>
			<br>"._('* one per line')."<br>
			</fieldset></Td></TR><TR><Td><fieldset><legend>

			"._('Pull-Down Codes:')."</legend>
			
			<textarea id='textarealogging[SELECT_CODES][$fieldID]' name='logging[SELECT_CODES][".$fieldID."]' cols='18' rows='3' onchange='CompareAmountOpCodes(this);'>".$loggingOptions[1]['SELECT_CODES']."</textarea><br>"._('* one per line')."
			</fieldset></Td></TR></table>
		</div>";	
	}
	elseif($type == 'date')
	{	
		$dateOptions = array(
		'today' => _('Today'),
		'yesterday' => _('Yesterday'),
		'tomorrow' => _('Tomorrow'),
		'blank' => _('Blank')		
		);
		
		$optString = '';
		foreach($dateOptions as $key => $value)
		{
			$optString .= "<option value='".$key."'";
			
			if($key == $loggingOptions[1]['SELECT_OPTIONS'])
				$optString .= "selected";
			
			$optString .= ">".$value."</option>";
		}
		
		return "
			<div>
				<select name='logging[DATEVALUE][".$fieldID."]' id='inputlogging[DATEVALUE][".$fieldID."]'>
				".$optString."					
				</select><br>
				<small>"._('Default:')."</small>
			</div>";
	}
}

/*
	return an array with the logging fields info, sorted by sort_order, something like this

	[LOG_FIELD2] = Array
        (
            [TYPE] = radio
            [TITLE] = title
            [NAME] = Field #2
            [SORT_ORDER] = 1
        )

*/

function _sortLogFieldsBySOrder($fieldArray)
{
	if($fieldArray)
	{
		for($i = 1; $i <= 20; $i++)
		{
			if(!empty($fieldArray['LOG_FIELD'.$i]))
			{
				$tmpArr[$fieldArray['LOG_FIELD'.$i.'_SORT_ORDER']] = array('LOG_FIELD'.$i => array($fieldArray['LOG_FIELD'.$i] => array('TITLE'=>$fieldArray['LOG_FIELD'.$i.'_TITLE'],'COUNT_TOTAL'=>$fieldArray['LOG_FIELD'.$i.'_COUNT_TOTAL'],'SIZE'=>$fieldArray['LOG_FIELD'.$i.'_SIZE'])));
			}
		}
		
		if(!$tmpArr) $tmpArr = array();
		ksort($tmpArr);
		
		foreach ($tmpArr as $sortKey => $sortItem)
		{	
			foreach ($sortItem as $fieldK => $fieldV)
			{
				foreach ($fieldV as $typeKey => $typeValue)
				{
					$newFieldArray[$fieldK]['TYPE'] = $typeKey;
					$newFieldArray[$fieldK]['TITLE'] = $typeValue['TITLE'];
					$newFieldArray[$fieldK]['NAME'] = makeLoggingName($fieldK);
                                        $newFieldArray[$fieldK]['COUNT_TOTAL'] = $typeValue['COUNT_TOTAL'];
                                        $newFieldArray[$fieldK]['SIZE'] = $typeValue['SIZE'];
					$newFieldArray[$fieldK]['SORT_ORDER'] = $sortKey;
				}
			}
		}
		
		return $newFieldArray;
	} else 
		return $fieldArray;
}

function makeLoggingName($stringForName)
{
	$str = explode('_',$stringForName);
	$str = explode('FIELD',$str[1]);
	
	return $str = _('Field #').$str[1];
}
function makeLoggingCheckbox($stringForCheckbox)
{
        //if()

	//return $str = _('Field #').$str[1];
}
function _checkFieldInTheJoinTable($catId, $fieldId, $isArray = false)
{	global $custom_fields_table,$student_fields_join_categories;
	
	if($fieldId)
	{
		if($isArray)
			$idSign = ' IN('.$fieldId.')';
		else 
			$idSign = '= '.$fieldId;

		$custFieldExist = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE ID".$idSign." AND CATEGORY_ID=".$catId));
		if(!empty($custFieldExist))
			db_execute("DELETE FROM ".$student_fields_join_categories." WHERE FIELD_ID".$idSign." AND CATEGORY_ID=".$catId);
	}
}


function _getDeletedCategoriesList($requestCategories,$categoriesFromSession)
{
	if($categoriesFromSession)
	{			
		/* field was deleted from the parent category*/
		if(!$_SESSION['fieldParentCategoryId']) $_SESSION['fieldParentCategoryId'] = array();
		if(!in_array($_SESSION['fieldParentCategoryId'],$requestCategories))	
			$categoriesFromSession[] = $_SESSION['fieldParentCategoryId'];
		else 
		{			
			$aKey = array_search($_SESSION['fieldParentCategoryId'],$requestCategories);
			if($aKey)
				unset($requestCategories[$aKey]);
		}
		if(!$requestCategories) $requestCategories = array();
		foreach($requestCategories as $item)
		{
			$uKey = array_search($item,$categoriesFromSession);
			if($uKey !== false)
				unset($categoriesFromSession[$uKey]);
		}

		return $categoriesFromSession;
	}

	return 0;
}


function _checkLogFieldsValues($request)
{ global $logFieldValuesCount;
	
	if(isset($logFieldValuesCount))
		return $logFieldValuesCount;

	if($request)
	{
		foreach($request as $item => $value)
		{
			if(!empty($value))
				$logFieldValuesCount++;
		}
		
		if(isset($logFieldValuesCount) && !empty($logFieldValuesCount))
			return $logFieldValuesCount;
		else 
			return 0;	
	}
	else 
		return 0;
}



function _makeSelInput($value,$name,$ajaxid=false,$size=false)
{
    global $THIS_array,$_SYSTEM;
    if($THIS_array['ID'])
        $id = $THIS_array['ID'];
    else
        $id = 'new';
    if($value=='')
        $_SYSTEM['set_js_onchange'] = false;
    $school = get_school_title($school_id,$column);
    $QI=db_execute("SELECT ID,SYSTEM_CODE,TITLE FROM SCHOOLS WHERE ID <> '".  get_apply_school_id()."'");
    if(!$_SYSTEM['get_school_title'])
        $_SYSTEM['get_school_title'] = db_request($QI,array(),array('ID'));
    foreach($_SYSTEM['get_school_title'] as $school_id=>$school_info)
        $options[$school_id] = $school_info[1]['TITLE'].' ['.$school_info[1]['SYSTEM_CODE'].']';
    if($ajaxid)
        return SelectAjaxInput($value,'faculty_'.$ajaxid.'_'.$name.'','faculty['.$ajaxid.']['.$name.']','',$options,'',($size)?"style=\"".$size."\"":'style="width:200px;"',true,'','',$id);
    else
        return SelectAjaxInput($value,'faculty_'.$id.'_'.$name.'','faculty['.$id.']['.$name.']','',$options,'','style="width:200px;"',true,'','',$id);
}



function _makeAdmGroupInput($value,$name,$ajaxid=false,$Limit='')
{
    global $THIS_array,$_SYSTEM;
    if($THIS_array['ID'])
        $id = $THIS_array['ID'];
    else
        $id = 'new';
    if($value=='')
        $_SYSTEM['set_js_onchange'] = false;
    //$school = get_school_title($school_id,$column);
    if($ajaxid)
        $QI=db_execute("SELECT ID,TITLE FROM APP_ADM_GROUPS  WHERE INCLUDE_ALL_SS IS NULL AND SCHOOL_YEAR='".get_school_year()."' $Limit");
    else
	$QI=db_execute("SELECT ID,TITLE FROM APP_ADM_GROUPS  WHERE SCHOOL_YEAR='".get_school_year()."' $Limit");
    //if(!$_SYSTEM['get_groups_title'])
        $_SYSTEM['get_groups_title'] = db_request($QI,array(),array('ID'));
    foreach($_SYSTEM['get_groups_title'] as $group_id=>$group_info)
        $options[$group_id] = $group_info[1]['TITLE'];
    if($ajaxid)
        return SelectAjaxInput($value,'faculty_'.$ajaxid.'_'.$name.'','faculty['.$ajaxid.']['.$name.']','',$options,'','style="width:200px;"',true,'','',$id,$ajaxid);
    else
        return SelectAjaxInput($value,'faculty_'.$id.'_'.$name.'','faculty['.$id.']['.$name.']','',$options,'','style="width:200px;"',true,'','',$id,$ajaxid);
}
function _makeCompetitionInput($value,$name,$ajaxid=false)
{
    global $THIS_array,$_SYSTEM;
    if($THIS_array['ID'])
        $id = $THIS_array['ID'];
    else
        $id = 'new';
    if($value=='')
        $_SYSTEM['set_js_onchange'] = false;
    //$faculty = get_faculty_title($value,$column);
    $QI=db_execute("SELECT ID,TITLE,SHORT_NAME FROM FACULTY  WHERE  SCHOOL_YEAR='".get_school_year()."'");
    if(!$_SYSTEM['get_faculty_title'])
        $_SYSTEM['get_faculty_title'] = db_request($QI,array(),array('ID'));
    foreach($_SYSTEM['get_faculty_title'] as $faculty_id=>$faculty_info)
        $options[$faculty_id] = $faculty_info[1]['TITLE'].'  ['.$faculty_info[1]['SHORT_NAME'].']';
    if($ajaxid)
        return SelectAjaxInput($value,'faculty_'.$ajaxid.'_'.$name.'','faculty['.$ajaxid.']['.$name.']','',$options,'','style="width:200px;',true,'','',$id);
    else
        return SelectAjaxInput($value,'faculty_'.$id.'_'.$name.'','faculty['.$id.']['.$name.']','',$options,'','style="width:200px;',true,'','',$id);
}
function _makeFacInput($value,$name,$ajaxid=false)
{
    global $THIS_array,$_SYSTEM;
    if($THIS_array['ID'])
        $id = $THIS_array['ID'];
    else
        $id = 'new';
    if($value=='')
        $_SYSTEM['set_js_onchange'] = false;
    $faculty = get_faculty_title($value,$column);
    $QI=db_execute("SELECT ID,TITLE,SHORT_NAME FROM FACULTY  WHERE  SCHOOL_YEAR='".get_school_year()."'");
    if(!$_SYSTEM['get_faculty_title'])
        $_SYSTEM['get_faculty_title'] = db_request($QI,array(),array('ID'));
    foreach($_SYSTEM['get_faculty_title'] as $faculty_id=>$faculty_info)
        $options[$faculty_id] = $faculty_info[1]['TITLE'].'  ['.$faculty_info[1]['SHORT_NAME'].']';
    if($ajaxid)
        return SelectAjaxInput($value,'faculty_'.$ajaxid.'_'.$name.'','faculty['.$ajaxid.']['.$name.']','',$options,'','style="width:200px;',true,'','',$id);
    else
        return SelectAjaxInput($value,'faculty_'.$id.'_'.$name.'','faculty['.$id.']['.$name.']','',$options,'','style="width:200px;',true,'','',$id);
}

function _makeSpecializationInput($value,$name,$ajaxid=false,$clear=false)
{
    global $THIS_array,$_SYSTEM;
    if($THIS_array['ID'])
        $id = $THIS_array['ID'];
    else
        $id = 'new';
    if($value=='')
        $_SYSTEM['set_js_onchange'] = false;
    //$faculty = get_faculty_title($value,$column);
    $QI=db_execute("SELECT ID,TITLE,SHORT_NAME FROM SPECIALIZATION  WHERE  SCHOOL_YEAR='".get_school_year()."'");
    if(!$_SYSTEM['get_specialization_title'])
        $_SYSTEM['get_specialization_title'] = db_request($QI,array(),array('ID'));
    foreach($_SYSTEM['get_specialization_title'] as $specialization_id=>$specialization_info)
        $options[$specialization_id] = $specialization_info[1]['TITLE'].'  ['.$specialization_info[1]['SHORT_NAME'].']';
    if($clear)
        $options = array('0'=>_('N/A'));
    if($ajaxid)
        return SelectAjaxInput($value,'faculty_'.$ajaxid.'_'.$name.'','faculty['.$ajaxid.']['.$name.']','',$options,'','style="width:200px;',true,'','',$id);
    else
        return SelectAjaxInput($value,'faculty_'.$id.'_'.$name.'','faculty['.$id.']['.$name.']','',$options,'','style="width:200px;',true,'','',$id);
}
function _makeSpecInput($value,$name,$ajaxid=false,$clear=false)
{
    global $THIS_array,$_SYSTEM;
    if($THIS_array['ID'])
        $id = $THIS_array['ID'];
    else
        $id = 'new';
    if($value=='')
        $_SYSTEM['set_js_onchange'] = false;
    $specialty = get_specialty_title($value,$column);
    $QI=db_execute("SELECT ID,TITLE,SHORT_NAME FROM SPECIALTY  WHERE  SCHOOL_YEAR='".get_school_year()."'");
    if(!$_SYSTEM['get_specialty_title'])
        $_SYSTEM['get_specialty_title'] = db_request($QI,array(),array('ID'));
    foreach($_SYSTEM['get_specialty_title'] as $specialty_id=>$specialty_info)
        $options[$specialty_id] = $specialty_info[1]['TITLE'].'  ['.$specialty_info[1]['SHORT_NAME'].']';
    if($clear)
        $options = array();
    $div  = ($id == 'new')?false:'force';


    if($ajaxid)
        return SelectAjaxInput($value,'faculty_'.$ajaxid.'_'.$name.'','faculty['.$ajaxid.']['.$name.']','',$options,'','style="width:150px;"',$div,'','',$id,$ajaxid);
    else
        return SelectAjaxInput($value,'faculty_'.$id.'_'.$name.'','faculty['.$id.']['.$name.']','',$options,'','style="width:150px;"',$div,'','',$id);

}
function _makeTOSInput($value,$name,$ajaxid=false,$clear=false)
{
    global $THIS_array,$_SYSTEM;
    if($THIS_array['ID'])
        $id = $THIS_array['ID'];
    else
        $id = 'new';
    $div = 'force';
    $tos = get_tos_title($value,$column);
    $QI=db_execute("SELECT ID,TITLE,SHORT_NAME FROM TYPE_OF_STUDY  WHERE  SCHOOL_YEAR='".get_school_year()."'");
    if(!$_SYSTEM['TYPE_OF_STUDY'])
        $_SYSTEM['TYPE_OF_STUDY'] = db_request($QI,array(),array());
    foreach($_SYSTEM['TYPE_OF_STUDY'] as $tos_id=>$tos_info)
        $options[$tos_id] = $tos_info[1]['TITLE'].'  ['.$tos_info[1]['SHORT_NAME'].']';
    if($clear)
        unset($options);
    if($value=='')
        $_SYSTEM['set_js_onchange'] = false;
    if(count($_SYSTEM['TYPE_OF_STUDY']))
    {
        if($clear)
          $schools_options = array();
        if($ajaxid)
            return make_ajax_tos_radio($value, 'faculty_'.$ajaxid.'_'.$name.'','faculty['.$ajaxid.']['.$name.']','', $schools_options,null,null,$div,2,$ajaxid,$clear);
        else
            return make_ajax_tos_radio($value, 'faculty_'.$id.'_'.$name.'','faculty['.$id.']['.$name.']','', $schools_options,null,null,$div,2,$id,$clear);
    }

}

function _makePriorityInput($value,$name,$ajaxid=false)
{
    global $THIS_array,$_SYSTEM;
    if($THIS_array['ID'])
    {
        $id = $THIS_array['ID'];
        $div = 'force';
    }
    else
    {
        $div = false;
        $id = 'new';
    }
    if($value=='')
        $_SYSTEM['set_js_onchange'] = false;
    if($value=='')
    {
        $_SESSION['PRIORITY']['count']++;
        $value = $_SESSION['PRIORITY']['count'];
    }
	if($name!='TITLE')
		$addition = 'size=6 maxlength=10';
	if($name=='SORT_ORDER')
		$comment = '<!-- '.$value.' -->';
        if($ajaxid)
            return $comment.AjaxTextInput($value,'faculty_'.$ajaxid.'_'.$name.'','faculty['.$ajaxid.']['.$name.']','',$addition,$div,'numeric',$ajaxid);
        else
            return $comment.AjaxTextInput($value,'faculty_'.$id.'_'.$name.'','faculty['.$id.']['.$name.']','',$addition,$div,'numeric',$id);
}
?>