<?php
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;

if($_REQUEST['servicemod']=='mod_users/UsrFieldsProperties.php')
{
	$custom_fields_table = 'USER_FIELDS';
	$categories_table = 'USER_FIELD_CATEGORIES';
	$students_table = 'USERS';

	//we need this var for using in the PullDownOptions.fnc.php
	$student_id_field = 'USER_ID';
	$singular = _('User Fields');
	$plural = _('Amount of User Fields');
	$singular_student = _('user');
	$plural_student = _('users');
//	$search_function_parameter = 'user_id';
//	$get_student_id = get_user_id();
	$student_fields_join_categories = 'USER_FIELDS_IN_CATS';

	$log_table = 'USER_LF_DATA';
	$student_field_id_field = 'USER_FIELD_ID';
	$html_field_title = 'user';
	
	$default_text = _('Default value for new user');
}
elseif(($_REQUEST['servicemod']=='mod_school/SchFieldsProperties.php') OR ($_REQUEST['servicemod']=='mod_ssetup/SchFieldsProperties.php'))
{
	$custom_fields_table = 'SCHOOL_FIELDS';
	$categories_table = 'SCHOOL_FIELD_CATEGORIES';
	$students_table = 'SCHOOLS';
	$student_fields_join_categories = 'SCHOOL_FIELDS_IN_CATS';
	//we need this var for using in the PullDownOptions.fnc.php
	$student_id_field = 'ID';
	$singular = _('School Info Fields');
	$plural = _('Amount of School Info Fields');
	$singular_student = _('school');
	$plural_student = _('schools');
//	$search_function_parameter = 'student_id';
//	$get_student_id = get_student_id();

	$log_table = 'SCHOOL_LF_DATA';
	$student_field_id_field = 'SCHOOL_FIELD_ID';
	$html_field_title = 'schools';
	
	$default_text = _('Default value for new school');
}
elseif(($_REQUEST['servicemod']=='mod_discipline/DisFieldsProperties.php'))
{
	$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 = get_student_id();
//$log_table = 'SCHOOL_LF_DATA';
	//$student_field_id_field = 'SCHOOL_FIELD_ID';
	$html_field_title = 'incident';
	
	$default_text = _('Default value for new incident');
}
else
{
	$custom_fields_table = 'STUDENT_FIELDS';
	$categories_table = 'STUDENT_FIELD_CATEGORIES';
	$students_table = 'STUDENTS';
	$student_fields_join_categories = 'STUDENT_FIELDS_IN_CATS';
	
	//we need this var for using in the PullDownOptions.fnc.php
	$student_id_field = 'STUDENT_ID';
	$singular = _('Student Fields');
	$plural = _('Student Fields');
	$singular_student = _('student');
	$plural_student = _('students');
//	$search_function_parameter = 'student_id';
//	$get_student_id = get_student_id();

	$log_table = 'STUDENT_LF_DATA';
	$student_field_id_field = 'STUDENT_FIELD_ID';
	$html_field_title = 'students';
	if($_REQUEST['servicemod'] == 'mod_apply/AppFieldsProperties.php')
		$default_text = _('Default value for new applicant');
	else
		$default_text = _('Default value for new student');
}

require_once($staticpath.'functions/extra/PullDown.fnc.php');
require_once($staticpath.'functions/extra/StudentsFunctional.fnc.php');

if($_REQUEST['fieldname'] && $_REQUEST['nearelem'])
{
	if($_REQUEST['nearelem'] != 'undefined')
	{
		db_execute("UPDATE $custom_fields_table SET 
				".$_REQUEST['fieldname']."_sort_order = ".$_REQUEST['nearelem']."_sort_order,
				".$_REQUEST['nearelem']."_sort_order = ".$_REQUEST['fieldname']."_sort_order
				WHERE id = ".$_REQUEST['id']."");
	}
	/*
		unset these vars because if we have the direction and fieldname, we just want to
		change the sort order, so 'tables' is unnecessary for us
	*/	
	unset($_REQUEST['tables']);
	unset($_POST['tables']);
}

if($_REQUEST['tables'] && $_POST['tables'])
{
	$table = $_REQUEST['table'];
	foreach($_REQUEST['tables'] as $id=>$columns)
	{
		if($id!='new')
		{
			$oldSortOrderSql = "SELECT SORT_ORDER FROM ".$student_fields_join_categories." WHERE FIELD_ID = ".$id." AND CATEGORY_ID = ".$_REQUEST['category_id']."";
			$oldSortOrderInfo = db_request(db_execute($oldSortOrderSql));
			/* i.e. we are trying to update the sort_order for the multiple filed */ 
			if(!empty($_SESSION['fieldParentCategoryId']) && $columns['SORT_ORDER'] && (array_key_exists($_REQUEST['category_id'], $_SESSION['multiple_field_num']))
			&& $table != $categories_table)
			{
				//echo 'here4';
				if($_SESSION['fieldParentCategoryId'] != $_REQUEST['category_id'])
					_rearrangeSortOrderForMultipleField($id, $_REQUEST['category_id'], $oldSortOrderInfo[1]['SORT_ORDER'], $columns['SORT_ORDER']);
				/*$updSql = "UPDATE ".$student_fields_join_categories."
						SET sort_order = ".$columns['SORT_ORDER']."
						WHERE FIELD_ID = ".$id." AND
						CATEGORY_ID = ".$_REQUEST['category_id']."";
				db_execute($updSql);
				*/
				unset($columns['SORT_ORDER']);
			}

			$old_sort_order = db_request(db_execute("SELECT SORT_ORDER FROM ".$custom_fields_table." WHERE ID='".$id."'"));
			$old_sort_order = $old_sort_order[1]['SORT_ORDER'];
			
			if($table==$custom_fields_table && $columns['SORT_ORDER'] && !$_SESSION['multiple_field_num']
			&& $table != $categories_table)
			{	
				//echo 'here2';
				_rearrangeSortOrders($_REQUEST['category_id'],$id,$old_sort_order,$columns['SORT_ORDER']);
				unset($columns['SORT_ORDER']);
			}
			
			//$columns['CATEGORY_ID']!=$_REQUEST['category_id']
				if(!$_SESSION['joinCategories']) $_SESSION['joinCategories'] = array();
				foreach ($_SESSION['joinCategories'] as $key => $categoryItem)
					$catListFromSession[] = $key;	
			
					/* get the IDs of the deleted categories */	
				$deletedCategories = _getDeletedCategoriesList($_REQUEST['tables'][$id]['CATEGORY_ID'], $catListFromSession);
			
			/*
				if we will use the multiple field, and move it from the parent category,
				into another, we will correct the orders in the given category and 
				move the field in the end of the new category
			*/
			if($columns['CATEGORY_ID'] && !in_array($_REQUEST['category_id'], $columns['CATEGORY_ID']) 
			&& !in_array($_REQUEST['category_id'],$deletedCategories))
			{ 
				if(array_key_exists($_REQUEST['category_id'], $_SESSION['multiple_field_num']))
					$old_sort_order = $oldSortOrderInfo[1]['SORT_ORDER'];
				else 
				 	$old_sort_order = $old_sort_order;
				 	
				if($_REQUEST['category_id'] != $_SESSION['fieldParentCategoryId']) 
				{
					//echo 'here';
					// delete from current category
					_rearrangeSortOrders($_REQUEST['category_id'],$id,$old_sort_order,false);
				
					$_REQUEST['category_id'] = $columns['CATEGORY_ID'][0];
					
					// add at the end of the new category
					_rearrangeSortOrders($_REQUEST['category_id'],$id,false,false,true);
				}
				else 
				{
					//echo 'here5';
					// delete from current category
					_rearrangeSortOrders($_REQUEST['category_id'],$id,$old_sort_order,false);
					
					$_REQUEST['category_id'] = $columns['CATEGORY_ID'][0];
					
					// add at the end of the category
					_rearrangeSortOrders($_REQUEST['category_id'],$id,false,-1);
				}
				_checkFieldInTheJoinTable($_REQUEST['category_id'],$id);
			}
			
			if(count($columns))
			{
				$_REQUEST['new'] = false;
				$sql = "UPDATE $table SET ";
				$go = true;
				
				foreach($columns as $column=>$value)
				{
					/*
						 we need this for log fields - because they has the 'logging' name
						 and without this hidden filed we wouldn't save the values
					*/
					if($column == 'CATEGORY_ID_EMPTY')
						continue;
					
					if($column == 'CATEGORY_ID')
					{
						if(in_array($_SESSION['mainFieldsCategory'], $value))
							$value = $_SESSION['mainFieldsCategory'];
						else 
							$value = $value[0];
					}
                                        
					
					if($column == 'SELECT_OPTIONS')
					{
						$value = _clearPullDown($value);
						/* 
						check, if some options has been changed - if so, will change the values
						into the DB and show the notice
						*/
						//$changedValuesCount = _checkAndReplaceOldOptions($value);
						if($changedValuesCount)
						{
							$notice[] = $changedValuesCount.' '.$plural.' have been changed';
							$errorString = ErrorMessage($notice, 'warning');
						}
					}
					if($column == 'SELECT_OPTION_CODES')
					{
						$value = _clearCodesPullDown($value);
					}
				
					/* 
						check the correctness of the Edit Rules - if it has some errors,
						show the error message
					*/
					if($column == 'FIELD_EDITS')
					{
						if($value)
						{
							$editsRule = str_replace('\\"','"', $value);
							$editsRule = str_replace('�','"', $editsRule);
							$editsRule = str_replace(chr(148),'"', $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, $html_field_title);
							$editsRule = str_replace('{FIELD_VALUE}','$value', $editsRule);
							/*
								eval the rules, if there will be the errors, display the notice about it
							*/
							
							ob_start();
							eval($editsRule);
							$errorString = ob_get_contents();
							ob_clean();
							
							$error = array();
							if(preg_match('/Parse/',$errorString))
							{		
								$error[] = _("Sorry, your Edit Rules contains some errors - maybe, you forgot the {} sign, or ';'. Check it, and try again.");
								$errorString = ErrorMessage($error);
								/*
									let's mark the uncorrect rules, and in the future, if we will have ||
									at the start of the expression, simply ignore it
								*/
								$value = '##'.$value.'##';
							}
							
						}
					}
					
					$sql .= $column."='".str_replace("\'","''",$value)."',"; 
					
				}

				/* check counts of options */
				if(!_checkQtyOfPullDown())
				{
					$msg[] = _('You have to enter the equal quantity of options!');
					$errorString = ErrorMessage($msg, 'warning');
				}

				if($_REQUEST['logging'] and $id!='new')
				{
					$sql = _saveLoggingFields($_REQUEST['logging'], $sql, $id, $html_field_title, $go, $log_table, $student_field_id_field);
//					var_dump($sql);
				}		
				$sql = substr($sql,0,-1) . " WHERE ID='$id'";
			}
		}
		else // ***************************insert new field **************************************
		{
			$go = true;
			unset($errMsg);
			
			if($table==$custom_fields_table)
			{
				if(empty($_REQUEST['tables']['new']['TITLE']))
				{			
					$errMsg[] = _('You have to enter the title of the field');
					$go = false;	
				}
				if(empty($_REQUEST['tables']['new']['CATEGORY_ID']))
					$_REQUEST['tables']['new']['CATEGORY_ID'][] = $_REQUEST['category_id'];
			}

			if($DBType == 'mssql' && $table==$custom_fields_table)
				$sql = "UPDATE $table SET ";
//				$sql = "INSERT INTO $table ";
			else
				$sql = "INSERT INTO $table ";
				
			if($table==$custom_fields_table)
			{
				//if($columns['TYPE']=='holder')
					//unset($columns['TITLE']);
				if($columns['CATEGORY_ID'])
				{
					/* 
						we will use the [0]th element as main, and insert it
						in the STUDENT_FIELDS, or will use the $_SESSION['mainFieldsCategory']
						value
					 */
					if(in_array($_SESSION['mainFieldsCategory'], $_REQUEST['tables']['new']['CATEGORY_ID']))
					{	
						$_REQUEST['category_id'] = $_SESSION['mainFieldsCategory'];	
						$key = array_search($_SESSION['mainFieldsCategory'], $_REQUEST['tables']['new']['CATEGORY_ID']);
						if($key !== FALSE)
							unset($_REQUEST['tables']['new']['CATEGORY_ID'][$key]);	
					}
					else 
					{
						$_REQUEST['category_id'] = $columns['CATEGORY_ID'][0];
						/*
							because we have only one field num, and there are no
							additional categories
						*/
						if(count($columns['CATEGORY_ID']) == 1)
							unset($_REQUEST['tables']['new']['CATEGORY_ID']);
						else 
							unset($_REQUEST['tables']['new']['CATEGORY_ID'][0]);
					}
					
					unset($columns['CATEGORY_ID']);
				}
				if($DBType == 'mssql')
				{
					if($go)
					{
						$id = db_request(db_execute("SELECT isnull(max(Id), 0) + 1 as Id FROM ".$custom_fields_table.' WHERE Id < 40000'));
						db_execute("INSERT INTO ".$custom_fields_table." (Id) values (".$id[1]['ID'].")");
					}
				}
				else
				{
					if($go)
					{
						$id = db_request(db_execute("SELECT ".db_seq_nextval('STUDENT_FIELDS_SEQ').' AS ID '.FROM_DUAL));
					}
				}
				if($go)
					$id = $id[1]['ID'];
				
				if($DBType == 'mssql')
					$fields = "CATEGORY_ID = '".$_REQUEST['category_id']."'";
				else
				{
					$fields = "ID,CATEGORY_ID,";
					$values = $id.",'".$_REQUEST['category_id']."',";
				}
				$_REQUEST['id'] = $id;
				$_REQUEST['new'] = true;
				
				if($go)
				{
                                    switch($columns['TYPE'])
                                    {
                                            case 'radio':
                                                    db_execute("ALTER TABLE ".$students_table." ADD CFIELD_$id VARCHAR(1)");
                                            break;

                                            case 'text':
                                            case 'select':
                                            case 'select_one':
                                                    db_execute("ALTER TABLE ".$students_table." ADD CFIELD_$id VARCHAR(255)");
                                            break;

                                            case 'multiple':
                                                    db_execute("ALTER TABLE ".$students_table." ADD CFIELD_$id VARCHAR(1000)");
                                            break;

                                            case 'numeric':
                                                    db_execute("ALTER TABLE ".$students_table." ADD CFIELD_$id NUMERIC");
                                            break;

                                            case 'date':
                                                    if($DBType == 'mssql')
                                                            db_execute("ALTER TABLE ".$students_table." ADD CFIELD_$id DATETIME");
                                                    else
                                                            db_execute("ALTER TABLE ".$students_table." ADD CFIELD_$id DATE");
                                            break;

                                            case 'textarea':
                                                    db_execute("ALTER TABLE ".$students_table." ADD CFIELD_$id VARCHAR(5000)");
                                            break;

                                            case 'file':
                                                    db_execute("ALTER TABLE ".$students_table." ADD CFIELD_$id VARCHAR(255)");
                                            break;

                                            case 'log':
                                            break;
                                    }
				}
				if($DBType == 'mssql')
				{					
					if($go)
						if($columns['TYPE']!='log' && $columns['TYPE']!='holder' && $columns['TYPE']!='file')
							db_execute("CREATE INDEX ".$students_table."CFIELD_IND$id ON ".$students_table." (CFIELD_$id)");
				}
				else
				{
					if($go)
					{
						if($columns['TYPE']!='log' && $columns['TYPE']!='holder' && $columns['TYPE']!='file' && $columns['TYPE']!='text')
							db_execute("CREATE INDEX ".$students_table."CFIELD_IND$id ON ".$students_table." (CFIELD_$id)");
						elseif($columns['TYPE']=='text')
							db_execute("CREATE INDEX ".$students_table."CFIELD_IND$id ON ".$students_table." (LOWER(CFIELD_$id))");					
					}
				}
			}
			elseif($table==$categories_table)
			{
				if($go)
				{
					$id = db_request(db_execute("SELECT ".db_seq_nextval($categories_table.'_SEQ').' AS ID '.FROM_DUAL));
					$id = $id[1]['ID'];
					$fields = "ID,";
					$values = $id.",";
					$_REQUEST['category_id'] = $id;
				}
			}
			
			$go = false;
			foreach($columns as $column=>$value)
			{
				if($column == 'SELECT_OPTIONS')
				{
					$value = _clearPullDown($value);
				}
				if($column == 'SELECT_OPTION_CODES')
				{
					$value = _clearCodesPullDown($value);
				}
				if(($column == 'USE_APPLICANTS' || $column == 'USE_STUDENTS') && $value == '')
				{
					$value = 'N';
				}
				if($value)
				{
					if($DBType == 'mssql' && $table==$custom_fields_table)
					{
						$fields .= ', '.$column.' = '."'".str_replace("\'","''",$value)."'";
						$go = true;
					}
					else
					{
						$fields .= $column.',';
						$values .= "'".str_replace("\'","''",$value)."',";
						$go = true;
					}
				}
			}
			/* check counts of options */
			if(!_checkQtyOfPullDown())
			{
				$msg[] = _('You entered a different number of values and codes. You should enter exactly the same number of values and codes.');
				$errorString = ErrorMessage($msg, 'warning');
			}

			if($errMsg)
			{
				$errorString = ErrorMessage($errMsg);	
				$go = false;	
			}			

			if($DBType == 'mssql' && $table==$custom_fields_table)
				$sql .= $fields.' WHERE Id = '.$id;
			else
				$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
				
			if($_REQUEST['logging'] && $_REQUEST['new'] == true)
			{
				$logValuesSql = "UPDATE ".$custom_fields_table." SET ";
				$logValuesSql = _saveLoggingFields($_REQUEST['logging'], $logValuesSql, $id, $html_field_title, $go, $log_table, $student_field_id_field);
				$logValuesSql .= "WHERE ID = '".$id."'";
			}	
		}
		
		if($go)
		{
			db_execute($sql);
  //                      var_dump($sql);
//                        die();
			if($logValuesSql)
			{
				db_execute($logValuesSql);
				unset($logValuesSql);
			}
			if(key($_REQUEST['tables'])=='new' && $table==$custom_fields_table)
				_rearrangeSortOrders($_REQUEST['category_id'],$id,false,$columns['SORT_ORDER']);
		}
	}
	//unset($_REQUEST['tables']);
}

if(isset($_REQUEST['id']) && $_REQUEST['id'] != 'new')
{
	//$_REQUEST['tables'][$_REQUEST['id']]['SORT_ORDER'] ? $sort_order = $_REQUEST['tables'][$_REQUEST['id']]['SORT_ORDER'] : $sort_order = $_SESSION['JOIN_SORT_ORDER'];
	$fId = $_REQUEST['id'];
	if(!empty($_REQUEST['tables']['new']['CATEGORY_ID']) OR !empty($_REQUEST['tables'][$_REQUEST['id']]['CATEGORY_ID']))
	{
		if($_SESSION['joinCategories'])
		{
			if(!empty($_REQUEST['tables'][$_REQUEST['id']]['CATEGORY_ID']))
				$requestCatArray = $_REQUEST['tables'][$_REQUEST['id']]['CATEGORY_ID'];
			else 
				$requestCatArray = $_REQUEST['tables']['new']['CATEGORY_ID'];

			foreach ($_SESSION['joinCategories'] as $key => $categoryItem)
			{	
				$joinCategories[] = $key;	
			}
			
			$catListFromSession = $joinCategories;
			/* get the IDs of the deleted categories */	
			$deletedCategories = _getDeletedCategoriesList($requestCatArray, $catListFromSession);
			
			
			if(!empty($deletedCategories))
			{
				foreach($deletedCategories as $cItem)
				{
					//echo 'here1';
					/* 
						we are removing the field from the parent category, som we need its
						sort_order from the CFIELD_ table
					*/
					if($cItem == $_SESSION['fieldParentCategoryId'])
						$fieldInfo = db_request(db_execute("SELECT SORT_ORDER FROM ".$custom_fields_table." WHERE ID=".$fId.""));
					else
						$fieldInfo = db_request(db_execute("SELECT SORT_ORDER FROM ".$student_fields_join_categories." WHERE FIELD_ID=".$fId." AND CATEGORY_ID=".$cItem.""));
					/*
						fix the sort_order in the category, from where we deleted this field
					*/
					_rearrangeSortOrders($cItem, $fId,$fieldInfo[1]['SORT_ORDER'],false);
				}
			}
			
			$joinCat = implode(',', $joinCategories);
			/*
				we will delete records with the given category_ids and field_id,
				because user could delete some categories from the list, or changed the 
				sort order
			*/
			$dSql = "DELETE FROM ".$student_fields_join_categories." WHERE FIELD_ID = ".$fId." AND CATEGORY_ID IN (".$joinCat.")";
			db_execute($dSql);
		}
		
		/* if user chose some categories */
		if(!empty($_REQUEST['tables']['new']['CATEGORY_ID']) OR !empty($_REQUEST['tables'][$_REQUEST['id']]['CATEGORY_ID']))
		{
			if(!empty($_REQUEST['tables'][$_REQUEST['id']]['CATEGORY_ID']))
				$catArray = $_REQUEST['tables'][$_REQUEST['id']]['CATEGORY_ID'];
			else 
				$catArray = $_REQUEST['tables']['new']['CATEGORY_ID'];

			foreach ($catArray as $joinCatItems)
			{	
				//if($joinCatItems == $_REQUEST['category_id'])
					//continue;
				/*
					 $_SESSION['fieldParentCategoryId'] -contains the parent category id, from the custom_fields
					 table - we shouldn't insert this value into the _fields_join_categories table
				*/
				if(!$joinCatItems) $joinCatItems = array();
				if((!empty($_SESSION['fieldParentCategoryId']) && $joinCatItems == $_SESSION['fieldParentCategoryId'])
				|| in_array($joinCatItems,$deletedCategories))
					continue;
				
				if(array_key_exists($joinCatItems, $_SESSION['joinCategories']))
					$sort_order = $_SESSION['joinCategories'][$joinCatItems][1]['SORT_ORDER'];
				else					
					$sort_order = (_getMaxSortOrder($custom_fields_table, $student_fields_join_categories, $joinCatItems)+1);

				$iSql = "INSERT INTO ".$student_fields_join_categories." values (".$fId.",".$joinCatItems.",".$sort_order.")";
				db_execute($iSql);
			}
		}
		
		unset($_SESSION['joinCategories']);
		
		/* 
			if user changed sort order for the given field and the given category
		*/
		if($_REQUEST['tables'][$_REQUEST['id']]['SORT_ORDER'])
		{
			$uSql = "UPDATE ".$student_fields_join_categories." SET SORT_ORDER = ".$_REQUEST['tables'][$_REQUEST['id']]['SORT_ORDER']." WHERE FIELD_ID = ".$fId." AND CATEGORY_ID = ".$_REQUEST['category_id']."";
			db_execute($uSql);
		}
	}	
}

unset($_REQUEST['tables']);
if(!$_REQUEST['servicefunction'])
{ 	
	// ADDING & EDITING FORM
	if($_REQUEST['id'] && $_REQUEST['id']!='new')
	{
		$array = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE ID='$_REQUEST[id]'"));
		$array = $array[1];
		$title = $array['TITLE'];
		
		_checkFieldInTheJoinTable($array['CATEGORY_ID'],$array['ID']);
		
		/*
			it means, that field is from another category (multiple field), and we must use 
			not its original order, but get it from _FIELDS_JOIN_CATEGORIES table
		*/
		if($array['CATEGORY_ID'] != $_REQUEST['category_id'])
		{
			$multipleFieldSortOrder = db_request(db_execute("SELECT SORT_ORDER FROM ".$student_fields_join_categories." WHERE FIELD_ID='$_REQUEST[id]' AND CATEGORY_ID = '".$_REQUEST['category_id']."'"));
			$array['SORT_ORDER'] = $multipleFieldSortOrder[1]['SORT_ORDER'];
		}
		
		$_SESSION['fieldParentCategoryId'] = $array['CATEGORY_ID'];
		
		/* clear our rules from the ## */
		$array['FIELD_EDITS'] = str_replace('##','', $array['FIELD_EDITS']);
	}
	elseif($_REQUEST['category_id'] && $_REQUEST['category_id']!='new' && $_REQUEST['id']!='new')
	{
		$sql = "SELECT * FROM ".$categories_table." WHERE ID='$_REQUEST[category_id]'";
		$array = db_request(db_execute($sql));
		$array = $array[1];
		$title = $array['TITLE'];
	}
	elseif($_REQUEST['id']=='new')
		$title = _('New Field');
	elseif($_REQUEST['category_id']=='new')
		$title = _('New Field Category');
		
	/* get and save in the session count of Pull-Down/Select Multiple Choices options
	   it will be helpful when will be checking qty of Pull-Down and Codes for Pull-Down
	   options
	*/	
	$_SESSION['pullDownOptionsCount'] = _returnOptionsCount($array['SELECT_OPTIONS']);	
	$_SESSION['codesPullDownOptionsCount'] = _returnOptionsCount($array['SELECT_OPTION_CODES']);
	
	if(($array['TYPE'] == 'select') OR ($array['TYPE'] == 'select_one') OR ($array['TYPE'] == 'multiple'))
	{		
		$arr = explode("\n", $array['SELECT_OPTIONS']);
		$values = array("ID" => $array['ID'], "OPTIONS" => $arr);
		
		/* save into the session array with the old values */
		$_SESSION['oldOptionsArr'] = $values;
	}
}

if($_REQUEST['id']=='new')
{

?>
<script language=javascript>
function changeDataType(type)
{
	switch(type)
	{

		case 'radio':
			document.getElementById('options_div').innerHTML = '';
			document.getElementById('option_codes_div').innerHTML = '';
			document.getElementById('default_div').innerHTML = '<INPUT type=checkbox name=tables[new][DEFAULT_SELECTION] value=Y>';
			document.getElementById('default_text_div').innerHTML = '<?php echo $default_text; ?> ';
			document.getElementById('edit_text_div').innerHTML = '';
		break;
		case 'faculty':
			document.getElementById('options_div').innerHTML = '';
			document.getElementById('option_codes_div').innerHTML = '';
			document.getElementById('default_div').innerHTML = '';
			document.getElementById('default_text_div').innerHTML = '';
			document.getElementById('edit_text_div').innerHTML = '';
		break;

		case 'text':
			document.getElementById('options_div').innerHTML = '';
			document.getElementById('option_codes_div').innerHTML = '';
			document.getElementById('default_div').innerHTML = '<INPUT type=text name=tables[new][DEFAULT_SELECTION] size=10>';
			document.getElementById('default_text_div').innerHTML = '<?php echo ''.$default_text; ?> ';
			document.getElementById('edit_text_div').innerHTML = '<?php echo TextAreaInput($array['FIELD_EDITS'],'tables['.$_REQUEST['id'].'][FIELD_EDITS]','<BR>'._('Rules of editing'),'rows=7 cols=50'); ?> ';
		break;

		case 'select_one':
		case 'select':
			document.getElementById('options_div').innerHTML = '<?php echo TextAreaInput($array['SELECT_OPTIONS'],'tables['.$_REQUEST['id'].'][SELECT_OPTIONS]','<BR>'._('Field Choices').' - '._('* one per line'),'rows=7 cols=40'); ?> ';
			document.getElementById('option_codes_div').innerHTML = '<?php echo TextAreaInput($array['SELECT_OPTION_CODES'],'tables['.$_REQUEST['id'].'][SELECT_OPTION_CODES]','<BR>'._('Codes for Field Choices').' - '._('* one per line'),'rows=7 cols=40'); ?> ';
			document.getElementById('default_div').innerHTML = '<INPUT type=text name=tables[new][DEFAULT_SELECTION] size=10>';
			document.getElementById('default_text_div').innerHTML = '<?php echo $default_text; ?> ';
			if(type == 'select')
				document.getElementById('edit_text_div').innerHTML = '<?php echo TextAreaInput($array['FIELD_EDITS'],'tables['.$_REQUEST['id'].'][FIELD_EDITS]','<BR>'._('Rules of editing'),'rows=7 cols=50'); ?> ';
			else
				document.getElementById('edit_text_div').innerHTML = '';
		break;
		case 'numeric':
			document.getElementById('options_div').innerHTML = '';
			document.getElementById('option_codes_div').innerHTML = '';
			document.getElementById('default_div').innerHTML = '<INPUT type=text name=tables[new][DEFAULT_SELECTION] size=4>';
			document.getElementById('default_text_div').innerHTML = '<?php echo $default_text; ?> ';
			document.getElementById('edit_text_div').innerHTML = '<?php echo TextAreaInput($array['FIELD_EDITS'],'tables['.$_REQUEST['id'].'][FIELD_EDITS]','<BR>'._('Rules of editing'),'rows=7 cols=50'); ?> ';
		break;

		case 'multiple':
			document.getElementById('options_div').innerHTML = '<?php echo TextAreaInput($array['SELECT_OPTIONS'],'tables['.$_REQUEST['id'].'][SELECT_OPTIONS]','<BR>'._('List of Options for Pull-Down & Multiple Choices').' - '._('* one per line'),'rows=7 cols=40'); ?> ';
			document.getElementById('option_codes_div').innerHTML = '<?php echo TextAreaInput($array['SELECT_OPTION_CODES'],'tables['.$_REQUEST['id'].'][SELECT_OPTION_CODES]','<BR>'._('List of Codes').' - '._('* one per line'),'rows=7 cols=40'); ?> ';
			document.getElementById('default_div').innerHTML = '<INPUT type=text name=tables[new][DEFAULT_SELECTION] size=10>';
			document.getElementById('default_text_div').innerHTML = '<?php echo $default_text; ?> ';
			document.getElementById('edit_text_div').innerHTML = '';
		break;

		case 'date':
			document.getElementById('options_div').innerHTML = '';
			document.getElementById('option_codes_div').innerHTML = '';
			document.getElementById('default_div').innerHTML = '<INPUT type=text name=tables[new][DEFAULT_SELECTION] size=10>* <?php echo _('YYYY-MM-DD'); ?> ';
			document.getElementById('default_text_div').innerHTML = '<?php echo $default_text; ?> ';
			document.getElementById('edit_text_div').innerHTML = '<?php echo TextAreaInput($array['FIELD_EDITS'],'tables['.$_REQUEST['id'].'][FIELD_EDITS]','<BR>'._('Rules of editing'),'rows=7 cols=50'); ?> ';
		break;

		case 'textarea':
			document.getElementById('options_div').innerHTML = '';
			document.getElementById('option_codes_div').innerHTML = '';
			document.getElementById('default_div').innerHTML = '<TEXTAREA name=tables[new][DEFAULT_SELECTION] cols=20 rows=4></TEXTAREA>';
			document.getElementById('default_text_div').innerHTML = '<?php echo $default_text; ?> ';
			document.getElementById('edit_text_div').innerHTML = '<?php echo TextAreaInput($array['FIELD_EDITS'],'tables['.$_REQUEST['id'].'][FIELD_EDITS]','<BR>'._('Rules of editing'),'rows=7 cols=50'); ?> ';
		break;
                case 'faculty':
                    document.getElementById('option_codes_div').innerHTML = '';
                    document.getElementById('default_div').innerHTML = '<INPUT type=text name=tables[new][DEFAULT_SELECTION] size=4>';
                    document.getElementById('default_text_div').innerHTML = '<?php echo _('Default number of entry rows'); ?> ';
                    document.getElementById('edit_text_div').innerHTML = ''; 
                break;
		case 'log':
			document.getElementById('option_codes_div').innerHTML = '';
			document.getElementById('options_div').innerHTML = '<?php
			$new = true;
			$div = false;
			$header .= ''._('Setup the Logging Fields').':<TABLE cellspacing="0" border="0" cellpadding="0" width="100%" id="logTable"><TR id="loggingTable">';
			// COPY TO LOWER SECTION STARTING HERE 
			$header .= '<TD style="white-space:nowrap;" height="20" valign=left><small><B>'._('Use Field?').'&nbsp;&nbsp;</b></small></TD>';

			$typesFroLoggFields = array('' => _('N/A'),
				'radio'=>_('Checkbox'),
				'text'=>_('Text'),
				'select'=>_('PullDown'),
				'numeric'=>_('Numeric'),
				'date'=>_('Date'),
				'textarea'=>_('Long Text'),
				'time'=>_('Time'));

			$header .= '<TD rowspan="2" valign=top ALIGN=CENTER"><TABLE><TR><TD align=center><BR>';
			$header .= ''._('Field #1').'</TD></TR><TR><TD><fieldset><legend>';
			$header .= SelectInput('','logging[TYPE][LOG_FIELD1]',_('Field Type').'</legend>',$typesFroLoggFields,false,'onchange="checkFieldType(this.options[this.selectedIndex].value, &quot;LOG_FIELD1&quot;);"',$div, null, false).'</fieldset></TD></TR><TR><TD><fieldset><legend>';
			$header .= TextInput('','logging[VALUE][LOG_FIELD1_TITLE]',_('Field Title').'</legend>','',$div).'</fieldset></TD></TR><TR><TD>';
			$header .= '<div id="loggingDivLOG_FIELD1"></div></TD>';
			$header .= '</TR></TABLE></TR><TR>';

			$header .= '<TD valign=top align=center><A HREF="#"><IMG SRC="images/add_button.gif" width=30 height=25 onclick="addNewLogField()" border=0 vspace=0 class=GridOutput_fieldint></TD>';
			// END COPY
			$header .= '</TR></TABLE>'; 
			echo $header;
			$header = '';
				 ?> ';
			document.getElementById('default_div').innerHTML = '<INPUT type=text name=tables[new][DEFAULT_SELECTION] size=4>';
			document.getElementById('default_text_div').innerHTML = '<?php echo _('Default number of entry rows'); ?> ';
			document.getElementById('edit_text_div').innerHTML = '<?php echo _('Max amount of records in the field'); ?> <INPUT type=text name=tables[new][MAX_RECORD] size=4>';
		break;
		case 'holder':
		case 'file':
			document.getElementById('options_div').innerHTML = '';
			document.getElementById('option_codes_div').innerHTML = '';
			document.getElementById('edit_text_div').innerHTML = '';
		break;
	}
}
</script>
<?php
}
DisplayHeader(".:".ProgramTitle().":.");
$_SYSTEM['allow_edit'] = true;

if($_REQUEST['servicefunction']=='delete')
{
	if(!empty($_SESSION['fieldsInTheCategoryList']) && !$_REQUEST['id'])
		$fieldIdForCheck = ' IN ('.$_SESSION['fieldsInTheCategoryList'].')';
	else 
		$fieldIdForCheck = "='".$_REQUEST['id']."'";

	if($_REQUEST['id'] || $_REQUEST['category_id'])
	{
		$multipleFields = db_request(db_execute("SELECT * FROM ".$student_fields_join_categories." WHERE FIELD_ID ".$fieldIdForCheck." AND CATEGORY_ID != '".$_REQUEST['category_id']."'"));
	}
	if($multipleFields && ($_REQUEST['id'] || $_REQUEST['category_id']))
	{
		if($_REQUEST['id'] && $_REQUEST['category_id'])
			$errorText[] = _("You can not delete this field, because it is used in other categories");
		else 
			$errorText[] = _("You can not delete this category, because it's fields are used in other categories");
		echo ErrorMessage($errorText);
		
		echo "<div align = 'center'><a href = '#' onclick='history.back();return false;'>Back</a></div>";
	}
	else 
	{
		if($_REQUEST['id'] && ($_REQUEST['id']<40000 || $_REQUEST['id']>=50000))
		{
			$field = db_request(db_execute("SELECT TYPE,SORT_ORDER FROM ".$custom_fields_table." WHERE ID='".$_REQUEST['id']."'"));
			$singular = 'field';
			if(DeletePrompt($singular))
			{
				$id = $_REQUEST['id'];
				db_execute("DELETE FROM ".$custom_fields_table." WHERE ID='$id'");
				_rearrangeSortOrders($_REQUEST['category_id'],$id,$field[1]['SORT_ORDER'],false);
				if($field[1]['TYPE']!='log' && $field[1]['TYPE']!='holder')
				{
				        if($DBType == 'mssql' && $field[1]['TYPE']!='log' && $field[1]['TYPE']!='holder' && $field[1]['TYPE']!='file')
						db_execute("DROP INDEX ".$students_table.".".$students_table."CFIELD_IND$id");
					db_execute("ALTER TABLE ".$students_table." DROP COLUMN CFIELD_$id");
				}
				elseif($field[1]['TYPE']=='log')
					db_execute("DELETE FROM ".$log_table." WHERE ".$student_field_id_field."='".$id."'");
				$_REQUEST['servicefunction'] = '';
				unset($_REQUEST['id']);
			}
		}
		elseif(($_REQUEST['category_id'] && $_REQUEST['category_id']>3 && $_REQUEST['category_id']!=999) ||
			($_REQUEST['category_id'] && ($_REQUEST['servicemod'] == 'mod_ssetup/SchFieldsProperties.php' || $_REQUEST['servicemod'] == 'mod_users/UsrFieldsProperties.php'))
			|| ($_REQUEST['servicemod'] == 'mod_discipline/DisFieldsProperties.php'))
		{
			if(DeletePrompt(_('field category and all fields in the category')))
			{
				$fields = db_request(db_execute("SELECT ID,TYPE FROM ".$custom_fields_table." WHERE CATEGORY_ID='$_REQUEST[category_id]'"));
				foreach($fields as $field)
				{
					db_execute("DELETE FROM ".$custom_fields_table." WHERE ID='$field[ID]'");
	    				if($field['TYPE']!='log' && $field['TYPE']!='holder')
					{
					    //if($DBType == 'mssql' && $field['TYPE']!='log' && $field['TYPE']!='holder' && $field['TYPE']!='file')
						//	db_execute("DROP INDEX ".$students_table.".".$students_table."CFIELD_IND$field[ID]");
						db_execute("ALTER TABLE ".$students_table." DROP COLUMN CFIELD_$field[ID]");
					}
					elseif($field['TYPE']=='log')
						db_execute("DELETE FROM ".$log_table." WHERE ".$student_field_id_field."='".$field['ID']."'");
				}
				db_execute("DELETE FROM ".$categories_table." WHERE ID='$_REQUEST[category_id]'");
				/* delete all fields with the given category_id */
				db_execute("DELETE FROM ".$student_fields_join_categories." WHERE
					CATEGORY_ID='".$_REQUEST['category_id']."'");
				$_REQUEST['servicefunction'] = '';
				unset($_REQUEST['category_id']);
			}
		}
	}
	$sql = "SELECT * FROM ".$categories_table." WHERE ID='$_REQUEST[category_id]'";
	$array = db_request(db_execute($sql));
	$array = $array[1];

}

if(!$_REQUEST['servicefunction'])
{
	// CATEGORIES
	if($students_table == 'STUDENTS')
		$for_app = ",USED_APPLICANTS";
	else
		unset($for_app);
	$sql = "SELECT ID,TITLE $for_app FROM ".$categories_table." ORDER BY SORT_ORDER,TITLE";
	$QI = db_execute($sql);
	$categories_array = db_request($QI,array('USED_APPLICANTS'=>'_printText'));
	
	if(AllowEdit())
	{
		if($custom_fields_table=='STUDENT_FIELDS')
			$required_fields = array(50000,50001,50002,50004,50012);
		else
			$required_fields = array(40001,40002,40003);

		if($_REQUEST['id']!='new' && $_REQUEST['category_id']!='new')
			$delete_button = "<INPUT style='width:100px;' type=button value="._('Delete')." onClick='javascript:window.location=\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete&category_id=$_REQUEST[category_id]&id=$_REQUEST[id]\"'> &nbsp; &nbsp; ";
		if((!$_REQUEST['id'] && $_REQUEST['category_id'] && (($custom_fields_table=='STUDENT_FIELDS' && $_REQUEST['category_id']<=3) || ($custom_fields_table=='USER_FIELDS' && $_REQUEST['category_id']==1))) || ($_REQUEST['id'] && (($_REQUEST['id']>=40000 && $_REQUEST['id']<50000) || in_array($_REQUEST['id'],$required_fields))))
			$delete_button = '<INPUT style="width:100px;" type=button value='._('Delete').' DISABLED> &nbsp; &nbsp; ';	
//		if(($_REQUEST['id'] && $_REQUEST['id']>=40000) || (!$_REQUEST['id'] && $_REQUEST['category_id'] && $_REQUEST['category_id']<=3))
	}
	
	if($_REQUEST['category_id'] && $_REQUEST['category_id']!='new')
	{
		
		$fieldList = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE CATEGORY_ID=".$_REQUEST['category_id']));
		if($fieldList)
		{
			foreach($fieldList as $fieldArrKey => $fieldArrValue)
			{
				$fieldsString.=$fieldArrValue['ID'].',';
			}
		}
		_checkFieldInTheJoinTable($_REQUEST['category_id'], substr($fieldsString,0,-1), true);
		
		$_SESSION['fieldsInTheCategoryList'] = substr($fieldsString,0,-1);
		
		/*
			get all fields from the custom_fields and fields from the
			fields_join_categories table and sort it by sort_order
		*/
		$sql= "SELECT ID,TITLE,TYPE,TYPE AS PLAIN_TYPE,
				CASE
					WHEN sfjc.sort_order IS NOT NULL
					THEN sfjc.sort_order
					ELSE cf.sort_order END
					AS sort_order
				FROM ".$custom_fields_table." cf LEFT JOIN ".$student_fields_join_categories." sfjc ON cf.id = sfjc.field_id AND sfjc.category_id = '".$_REQUEST['category_id']."'
				WHERE cf.CATEGORY_ID='".$_REQUEST['category_id']."' OR
				cf.id IN (SELECT FIELD_ID FROM ".$student_fields_join_categories." WHERE CATEGORY_ID = '".$_REQUEST['category_id']."') ORDER BY SORT_ORDER,TITLE";
		$fields_array = db_request(db_execute($sql),array('TYPE'=>'_makeType'));
	}
	
	if($_REQUEST['id'])
	{
		echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&category_id=$_REQUEST[category_id]";
		if($_REQUEST['id']!='new')
			echo "&id=$_REQUEST[id]";
		echo "&table=".$custom_fields_table." method=POST onsubmit='return StudentListFieldCheck();' id='fieldsForm'>";
		DisplayHeader($title,$delete_button.'<INPUT style="width:100px;" type=submit id=savebutton value='._('Save').'>');
		$header .= '<TABLE cellpadding=0 width=100% border=0 cellspacing="0">'; 
		$header .= '<TR><TD colspan=6 background=themes/'.Preferences('HIGHLIGHT_FRAME').'/gline.png height=20></TD></TD>';
		$header .= '<TR>';
		//if($array['TYPE']!='holder')
		$header .= '<TD valign=bottom>'.TextInput($array['TITLE'],'tables['.$_REQUEST['id'].'][TITLE]',_('Field Name'),'maxlength=100').'</TD>';
		$types = array('radio'=>_('Checkbox'),
			'text'=>_('Text'),
			'select'=>_('PullDown'),
			'numeric'=>_('Numeric'),
			'date'=>_('Date'),
			'textarea'=>_('Long Text'),
			'log'=>_('Logging Fields'),
                        'faculty'=>_('Static Type: Faculties'),
//			'select_one'=>_('Select One from Options'),
//			'multiple'=>_('Select Multiple from Options'),
			'select_one'=>_('Select One'),
			'multiple'=>_('Select Multiple'),
			'holder'=>_('Placeholder'),
			'file'=>_('File Upload'));
		if($_REQUEST['id']=='new')
			$header .= '<TD valign=bottom>'.SelectInput($array['TYPE'],'tables['.$_REQUEST['id'].'][TYPE]',_('Data Type of Field'),$types,false,'onchange="changeDataType(this.options[this.selectedIndex].value)"').'</TD>';
		elseif($array['TYPE']=='select' || $array['TYPE']=='select_one')
			$header .= '<TD valign=bottom>'._changeSelect($array['TYPE']).'</TD>';
		else
			$header .= '<TD valign=bottom>'._('Data Type of Field').'&nbsp;'. _makeType($array['TYPE'],null).''.'</TD>';
		//if($students_table != 'SCHOOLS')
		$options = array('-1'=>_('Last '),'1'=>_('First '));
		$holders = 0;
		//print_r($fields_array);

		foreach($fields_array as $key => $field)
		{
			if($field['PLAIN_TYPE']=='holder')
			{
				$holders++;
				if(!$field['TITLE'])
					$field['TITLE'] = _('Placeholder').' '.$holders;
			}
			$options[($field['SORT_ORDER']+1)] = _('After').' '.$field['TITLE'];
		}
		$header .= '<TD valign=bottom>'.SelectInput($array['SORT_ORDER'],'tables['.$_REQUEST['id'].'][SORT_ORDER]',_('Sort Order'),$options,false,'style="width:150;"').'</TD>';
		//$header .= '<TD>'.TextInput($array['SORT_ORDER'],'tables['.$_REQUEST['id'].'][SORT_ORDER]',_('Sort Order'),'size=3 maxlength=5').'</TD>';

		foreach($categories_array as $type)
			$categories_options[$type['ID']] = $type['TITLE'];
	
		if($_REQUEST['id']=='new')
		{
		//	$header .='';
		        $colspan_def_div = (SystemPreferences('APPLY_MODE')=='Y')?3:3;
			$header .= '<TD valign=bottom rowspan=1 colspan='.$colspan_def_div.' align=left><div id=default_text_div style="display:inline;"></div><div id=default_div style="display:inline;">'.CheckboxInput($array['DEFAULT_SELECTION'],'tables['.$_REQUEST['id'].'][DEFAULT_SELECTION]',$default_text.'','',true).'</div></TD>';
		}
		else
		{
                        $colspan_def_div = (SystemPreferences('APPLY_MODE')=='Y')?2:2;
                        $rowspan_def_div = (SystemPreferences('APPLY_MODE')=='Y')?1:1;
			switch($array['TYPE'])
			{
				case 'radio':
					$header .= '<TD valign=bottom colspan='.$colspan_def_div.' ><div id=default_div>'.CheckboxInput($array['DEFAULT_SELECTION'],'tables['.$_REQUEST['id'].'][DEFAULT_SELECTION]',''.$default_text.'','',false).'</div></TD>';
				break;

				case 'text':
				case 'select':
				case 'numeric':
				case 'multiple':
				case 'select_one':
					$header .= '<TD valign=bottom colspan='.$colspan_def_div.' rowspan=1><div id=default_div>'.TextInput($array['DEFAULT_SELECTION'],'tables['.$_REQUEST['id'].'][DEFAULT_SELECTION]',''.$default_text.'','','force').'</div></TD>';
				break;
				
				case 'date':
					$header .= '<TD valign=bottom colspan=2 rowspan=1><div id=default_div>'.TextInput($array['DEFAULT_SELECTION'],'tables['.$_REQUEST['id'].'][DEFAULT_SELECTION]','* '._('YYYY-MM-DD').' '.$default_text.'','','force').'</div></TD>';
				break;

				case 'textarea':
					$header .= '<TD valign=bottom style="border-width:3px;border-style:solid;border-color:'.Preferences('HIGHLIGHT').';"  rowspan=2><div id=default_div>'.TextAreaInput($array['DEFAULT_SELECTION'],'tables['.$_REQUEST['id'].'][DEFAULT_SELECTION]',''.$default_text.'','','force').'</div></TD>';
				break;

                                case 'faculty':
					$header .= '<TD valign=bottom colspan='.$colspan_def_div.'><div id=default_div>'.TextInput($array['DEFAULT_SELECTION'],'tables['.$_REQUEST['id'].'][DEFAULT_SELECTION]',''._('Default number of entry rows').'','','force').'</div></TD>';
				break;

				case 'log':
					$header .= '<TD valign=bottom colspan='.$colspan_def_div.'><div id=default_div>'.TextInput($array['DEFAULT_SELECTION'],'tables['.$_REQUEST['id'].'][DEFAULT_SELECTION]',''._('Default number of entry rows').'','','force').'</div></TD>';
				break;
				
			}
		}

		if($_REQUEST['id']=='new' && $_REQUEST['servicemod'] == 'mod_students/StuFieldsProperties.php')
		{
			$array['APPLICATION'] = 'Y';
			$array['USE_STUDENTS'] = 'Y';
		}
		elseif($_REQUEST['id']=='new' && $_REQUEST['servicemod'] == 'mod_apply/AppFieldsProperties.php')
		{
			if(SystemPreferences('APPLY_MODE')=='Y')
				$array['FOR_APPLICANTS'] = 'Y';
			$array['USE_APPLICANTS'] = 'Y';
		}
		
		$header .= '</TR><TR><TD valign=bottom colspan=1><div id=required_div>'.CheckboxInput($array['REQUIRED'],'tables['.$_REQUEST['id'].'][REQUIRED]',''._('Required to be filled').'&nbsp;','',($_REQUEST['id']=='new'?true:false)).'</div></TD>';
//		$header .= '<TD valign=bottom colspan=1><div id=application_div>'.CheckboxInput($array['APPLICATION'],'tables['.$_REQUEST['id'].'][APPLICATION]','','',($_REQUEST['id']=='new'?true:false)).'</div><small>'._('Display for adding new ').$plural_student.'</small></TD>';
		if($students_table == 'STUDENTS')
                {
            		$header .= '<TD valign=bottom><div id=display_div>'._('Display for adding new').':';
			$header .= '<div id=application_div>'.CheckboxInput($array['APPLICATION'],'tables['.$_REQUEST['id'].'][APPLICATION]',''._('students ').'','',($_REQUEST['id']=='new'?true:false)).'</div>';
                        if((SystemPreferences('APPLY_MODE')=='Y'))
//	                        $header .= '<TD valign=bottom><div id=for_applicants_div>'.CheckboxInput($array['FOR_APPLICANTS'],'tables['.$_REQUEST['id'].'][FOR_APPLICANTS]',''._('Display for adding applicants').'','',($_REQUEST['id']=='new'?true:false)).'</div></TD>';
	                        $header .= '<div id=for_applicants_div>'.CheckboxInput($array['FOR_APPLICANTS'],'tables['.$_REQUEST['id'].'][FOR_APPLICANTS]',''._('applicants ').'','',($_REQUEST['id']=='new'?true:false)).'</div>';
                         $header .= '</DIV></TD>';
                }                
		elseif($students_table == 'USERS')
			$header .= '<TD valign=bottom colspan=1><div id=application_div>'.CheckboxInput($array['APPLICATION'],'tables['.$_REQUEST['id'].'][APPLICATION]',''._('Display for adding new users').'','',($_REQUEST['id']=='new'?true:false)).'</div></TD>';
		elseif($students_table == 'SCHOOLS')
			$header .= '<TD valign=bottom colspan=1>&nbsp;</TD>';
		else
			$header .= '<TD valign=bottom colspan=1><div id=application_div>'.CheckboxInput($array['APPLICATION'],'tables['.$_REQUEST['id'].'][APPLICATION]',''._('Display for adding new students').'','',($_REQUEST['id']=='new'?true:false)).'</div></TD>';

		if($students_table == 'STUDENTS')
                {
            		$header .= '<TD valign=bottom><div id=usefor_div>'._('Use for').':';
			$header .= '<div id=application_div>'.CheckboxInput($array['USE_STUDENTS'],'tables['.$_REQUEST['id'].'][USE_STUDENTS]',''._('students ').'','',($_REQUEST['id']=='new'?true:false)).'</div>';
                        if((SystemPreferences('APPLY_MODE')=='Y'))
//	                        $header .= '<TD valign=bottom><div id=for_applicants_div>'.CheckboxInput($array['FOR_APPLICANTS'],'tables['.$_REQUEST['id'].'][FOR_APPLICANTS]',''._('Display for adding applicants').'','',($_REQUEST['id']=='new'?true:false)).'</div></TD>';
	                        $header .= '<div id=for_applicants_div>'.CheckboxInput($array['USE_APPLICANTS'],'tables['.$_REQUEST['id'].'][USE_APPLICANTS]',''._('applicants ').'','',($_REQUEST['id']=='new'?true:false)).'</div>';
                        $header .= '</DIV></TD>';
                }
		
		if($_REQUEST['id']=='new' || $array['TYPE']=='text' || $array['TYPE']=='numeric')
		{
			$header .= '<TD valign=bottom>'.TextInput($array['MAX_LENGTH'],'tables['.$_REQUEST['id'].'][MAX_LENGTH]',_('Max Length'),'size=3 maxlength=10',($_REQUEST['id']=='new'?true:'force')).'</TD>';
                        $header .= '<TD valign=bottom>'.TextInput($array['SIZE'],'tables['.$_REQUEST['id'].'][SIZE]',_('Input width'),'size=3 maxlength=10',($_REQUEST['id']=='new'?true:'force')).'</TD>';
			if($_REQUEST['id'] !=='new')
			{
				/* a new textarea for Rules of editing text */	
				$headerEditsRules .= '</TR><TR><TD colspan=8><div id=edit_text_div>'.TextAreaInput($array['FIELD_EDITS'],'tables['.$_REQUEST['id'].'][FIELD_EDITS]',_('Rules of editing'),'rows=7 cols=80', 'force').'</div></TD>';
			}
		}
		/* we need the edit rules textarea only for the Data, Text, Numeric, Textarea fields */
		elseif ($array['TYPE'] == 'date' || $array['TYPE'] == 'textarea')
		{
			/* a new textarea for Rules of editing text */	
			$headerEditsRules .= '</TR><TR><TD colspan=8><div id=edit_text_div>'.TextAreaInput($array['FIELD_EDITS'],'tables['.$_REQUEST['id'].'][FIELD_EDITS]',_('Rules of editing'),'rows=7 cols=80', 'force').'</div></TD>';
			$headerEditsRules .= '</TR><TR>';
		}
                elseif($array['TYPE'] == 'log')
                {
                    $header .= '<TD valign=bottom>'.TextInput($array['MAX_RECORD'],'tables['.$_REQUEST['id'].'][MAX_RECORD]',''._('Max amount of records in the field').'','','force').'</TD>';
                }
		else
                {
			$header .= '<TD valign=bottom>'.NoInput(_('N/A'),_('Max Length')).'</TD>';
                }

		if(isset($_REQUEST['id']) && $_REQUEST['id'] != 'new')
		{
			$sql = "SELECT * FROM ".$student_fields_join_categories." WHERE field_id=".$_REQUEST['id']." ORDER BY SORT_ORDER";
			$joinCategoriesArr = db_request(db_execute($sql), array(), array('CATEGORY_ID'));
		}
		
	
		$_SESSION['joinCategories'] = $joinCategoriesArr;
		$fieldMainCategory = $array['CATEGORY_ID']?$array['CATEGORY_ID']:$_REQUEST['category_id'];
		$opt = '||'.$fieldMainCategory.'||';
		
		//$_SESSION['multiple_field_num'] - this var will be set if it's the multiple field
		if(!empty($joinCategoriesArr) && $fieldMainCategory != $_REQUEST['category_id'])
			$_SESSION['multiple_field_num'] = $joinCategoriesArr;
		else 
			unset($_SESSION['multiple_field_num']);	

		/* save the default category num */
		$_SESSION['mainFieldsCategory'] = $fieldMainCategory;

		if(!$joinCategoriesArr) $joinCategoriesArr = array();
		foreach($categories_array as $catKey => $catItem)
		{
			if(array_key_exists($catItem['ID'], $joinCategoriesArr))
				$opt .= $catItem['ID'].'||';
		}
		$header .= '<TD>'.SelectMultipleInput($opt,'tables['.$_REQUEST['id'].'][CATEGORY_ID]',_('Current Field will be displayed in the chosen Categories'),$categories_options,null,null,'force',2).'</TD>';
		//$header .= '<TD>' . SelectInput($array['CATEGORY_ID']?$array['CATEGORY_ID']:$_REQUEST['category_id'],'tables['.$_REQUEST['id'].'][CATEGORY_ID]',_('Field Category'),$categories_options,false) . '
//		$array['USE_SOURCE'] = 'N';
		$header .= "<SCRIPT>
			function show_source()
			{
				if(document.getElementById('input".'tables_'.$_REQUEST['id'].'__USE_SOURCE_'."').checked)
				{
					document.getElementById(\"source_div\").style.visibility = \"visible\";
				}
				else
					document.getElementById(\"source_div\").style.visibility = \"hidden\";
				
//			 getElementById(\"source_div\").style.visibility\";
    			}				
			</SCRIPT>";
		if(($array['TYPE']=='select' || $array['TYPE']=='multiple' || $array['TYPE']=='select_one') && ($students_table == 'STUDENTS' || $students_table == 'USERS'))
		{
			if($array['USE_SOURCE'] == 'Y')
				$vtp = 'visible';
			else
				$vtp = 'hidden';
			$tables_options = array('SCHOOLS'=>'SCHOOLS','STUDENTS'=>'STUDENTS','USERS'=>'USERS','FACULTY'=>'FACULTY','SPECIALTY'=>'SPECIALTY','SPECIALIZATION'=>'SPECIALIZATION','APP_EXAMS'=>'APP_EXAMS','TYPE_OF_STUDY'=>'TYPE_OF_STUDY','APP_ADM_GROUPS'=>'APP_ADM_GROUPS','APP_EDU_FORMS'=>'APP_EDU_FORMS');
			$header .= '<TR><TD style="border:1px; border-top: 1px solid gray;">'; //solid black; border-size:1px; 
			$header .= makeCheckbox($array['USE_SOURCE'],'tables['.$_REQUEST['id'].'][USE_SOURCE]',_('Use Source'),'',false,_('Yes'),_('No'),true,'','onclick=\" show_source();\" ').'';
			$header .= '</TD>';
			$header .= '<TD colspan=4 style="border:1px; border-top: 1px solid gray;"><DIV id=source_div style="visibility:'.$vtp.';">';
			$header .= '<TABLE><TD>'.SelectInput($array['SOURCE_TABLE'],'tables['.$_REQUEST['id'].'][SOURCE_TABLE]',_('Source Table'),$tables_options,false,'style="width:150;"').'</TD>';
			$header .= '<TD>'.TextInput($array['VALUES_FIELD'],'tables['.$_REQUEST['id'].'][VALUES_FIELD]','&nbsp;&nbsp;'._('Values Field'),'size=10','force').'</TD>';
			$header .= '<TD>'.TextInput($array['CODES_FIELD'],'tables['.$_REQUEST['id'].'][CODES_FIELD]','&nbsp;&nbsp;'._('Codes Field'),'size=10','force').'</TD>';
//			$header .= '<TD valign=bottom>'..'</TD>';
			$header .= '</TABLE></DIV></TD>';
			$header .= '</TR>';
		}

		if($headerEditsRules)
			$header .= $headerEditsRules;

		$header .= '</TR>';
		if($errorString)
			$header .= '<TR><TD colspan=8>'.$errorString.'</TD></TR>';
		$header .= '<TR id=second_row>';

		$colspan = 2;
		if($array['TYPE']=='select' || $array['TYPE']=='multiple' || $array['TYPE']=='select_one')
		{
			$header .= '<TD colspan=1><div id=options_div>'.TextAreaInput($array['SELECT_OPTIONS'],'tables['.$_REQUEST['id'].'][SELECT_OPTIONS]','<BR>'._('List of Options for Pull-Down & Multiple Choices').' '._('one per line'),'rows=7 cols=45','force').'</div></TD>';
			$header .= '<TD colspan=2><div id=option_codes_div>'.TextAreaInput($array['SELECT_OPTION_CODES'],'tables['.$_REQUEST['id'].'][SELECT_OPTION_CODES]',_('List of Codes').' - '._('one per line'),' rows=7 cols=45','force').'</div></TD>';
			$header .= '<TD colspan=1 align=left valign=center><div id=option_default_code_div>'.TextInput($array['SELECT_OPTION_DEFAULT_CODE'],'tables['.$_REQUEST['id'].'][SELECT_OPTION_DEFAULT_CODE]',_('Default Code'),'rows=7 cols=40','force').'</div></TD>';
				
			if($array['TYPE']=='select') /* a new textarea for Rules of editing text */	
				$header .= '</TR><TR><TD colspan=8><div id=edit_text_div>'.TextAreaInput($array['FIELD_EDITS'],'tables['.$_REQUEST['id'].'][FIELD_EDITS]',_('Rules of editing'),'rows=5 cols=70', 'force').'</div></TD>';
			$header .= '</TR><TR>';
		}
		elseif($array['TYPE']=='log')
		{
			$new = true;
			$div = false;
			$header .= '<TD colspan=8><HR>'._('Setup the Logging Fields').':<TABLE cellspacing="0" border="0" cellpadding="0" width="100%"><TR id="loggingTable">';
			// IF THE NEW FIELDS ARE MODIFIED IN THE JS SECTION AT TOP, PASTE IN CHANGES HERE
			$header .= '<TD width="10%" height="30" valign=top><small><B>'._('Add a field').'&nbsp;&nbsp;&nbsp;</b></small></TD>';

			$typesFroLoggFields = array('' =>_('N/A'),
				'radio'=>_('Checkbox'),
				'text'=>_('Text'),
				'select'=>_('PullDown'),
				'numeric'=>_('Numeric'),
				'date'=>_('Date'),
				'textarea'=>_('Long Text'),
				'time'=>_('Time'));

			$loggingFields = _sortLogFieldsBySOrder($array);

			$header .= _makeLoggingEditInterface($loggingFields, $html_field_title, $typesFroLoggFields, $array['ID']);
			
			$header .= '</TR><TR>';
			$header .= '<TD valign=top align=center><BR>'.button('add', '', '#', 30, 'height=25 onclick="addNewLogField()"').'
					    <input type="hidden" name="tables['.$_REQUEST['id'].'][CATEGORY_ID_EMPTY]" value="'.$fieldMainCategory.'">
						</TD>';
			
			// END PASTE
			$header .= '</TR></TABLE></TD>';
		}
		elseif($_REQUEST['id']=='new')
	//		$header .= '<TD colspan=2 id="options_td"><div id=options_div></div></TD><TD colspan=1 id="option_codes_td"><div id=option_codes_div></div></TD><TD colspan=1 align=left valign=top></div></TD>';
			//need to check
			$header .= '<TD colspan=2 id="options_td"><div id=options_div></div></TD><TD colspan=1 id="option_codes_td"><div id=option_codes_div></div></TD><TD colspan=1 align=left valign=top><div id=edit_text_div></div></TD>';

		$header .= '</TR></TABLE><BR> ';
		
//		$header .= '<TR><TD colspan="8">';
		/*
		//<input type = "checkbox" name = "categoryIdChk[]" value = "'.$catItem['ID'].'"'.$checked.'>&nbsp;&nbsp;&nbsp;'.$catItem['TITLE']
		//'<input type = "hidden" name = "categoryHidden" value = "Y">';
		*/
//		$header .= '</TD></TR></TABLE>';
	}
	elseif($_REQUEST['category_id'])
	{
		echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&table=".$categories_table;
		if($_REQUEST['category_id']!='new')
		echo "&category_id=$_REQUEST[category_id]";
		echo " method=POST>";
		DisplayHeader($title,$delete_button.$submitButton->createSButton(_('Save')));
		$header .= '<TABLE cellpadding=3 width=100% border=0 cellspacing=0 align=center>';
		$header .= '<TR><TD colspan=3 background=themes/'.Preferences('HIGHLIGHT_FRAME').'/gline.png height=20></TD>';
		if($categories_table=='USER_FIELD_CATEGORIES')
		$header .= '<TD background=themes/'.Preferences('HIGHLIGHT_FRAME').'/gline.png height=20></TD><TD width=30 background=themes/'.Preferences('HIGHLIGHT_FRAME').'/gline.png height=20></TD>';
		$header .= '</TR><TR>';
//		$header .= '<TD colspan=2>'.TextInput($array['TITLE'],'tables['.$_REQUEST['category_id'].'][TITLE]',_('Field Title')).'</TD>';
		$header .= '<TD>'.TextInput($array['TITLE'],'tables['.$_REQUEST['category_id'].'][TITLE]',_('Category Title')).'</TD>';
		if($_REQUEST['category_id']=='new')
			$new = true;		
		if($students_table == 'STUDENTS')
		{
			$header .= '<TD ALIGN=LEFT>'.CheckboxInput($array['USED_APPLICANTS'],'tables['.$_REQUEST['category_id'].'][USED_APPLICANTS]',_('Category used for Applicants only'),'',$new,_('Yes'),_('No')).'</TD>';
		}
		if($students_table == 'USERS')
			$header .= '<TD ALIGN=RIGHT>'._('Choose profiles with permission to view this category: ').'</TD>';
		if($categories_table=='USER_FIELD_CATEGORIES')
			$header .= '<TD align=right>'.CheckboxInput($array['ADMIN'],'tables['.$_REQUEST['category_id'].'][ADMIN]',_('Administrator'),'',$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>').'</TD><TD width=30></TD>';
		if($categories_table!='SCHOOL_FIELD_CATEGORIES')
			$header .= '</TR><TR><TD>'.CheckboxInput($array['ALLOW_TEACHER_MODIFY'],'tables['.$_REQUEST['category_id'].'][ALLOW_TEACHER_MODIFY]',_('Allow Teachers to Modify this Category'),'',$new).'</TD>';
		$header .= '<TD>'.TextInput($array['SORT_ORDER'],'tables['.$_REQUEST['category_id'].'][SORT_ORDER]',_('Sort Order')).'</TD>';
		if($categories_table=='USER_FIELD_CATEGORIES')
			$header .= '<TD align=right>'.CheckboxInput($array['TEACHER'],'tables['.$_REQUEST['category_id'].'][TEACHER]',_('Teacher'),'',$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>').'</TD><TD width=30></TD> ';
		if($categories_table=='STUDENT_FIELD_CATEGORIES')
			$header .= '</TR><TR><TD>'.CheckboxInput($array['ALLOW_STUDENT_MODIFY'],'tables['.$_REQUEST['category_id'].'][ALLOW_STUDENT_MODIFY]',_('Allow Students to Modify this Category'),'',$new).'</TD>';
		//$header .= '<TD>'.SelectInput($array['COLUMNS'],'tables['.$_REQUEST['category_id'].'][COLUMNS]',_('Display Fields in a table with 1 or 3 Columns'),array('1'=>_('1'),'3'=>_('3')),false).'</TD>';
		$header .= '<TD></TD>';

		if($categories_table=='USER_FIELD_CATEGORIES')
		{
	//		$header .= '<TD>' .CheckboxInput($array['ADMIN'],'tables['.$_REQUEST['category_id'].'][ADMIN]',_('Administrator'),'',$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>').'</TD>';
	//		$header .= '<TD>' .CheckboxInput($array['TEACHER'],'tables['.$_REQUEST['category_id'].'][TEACHER]',_('Teacher'),'',$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>').'</TD>';
			$header .= '</TR><TR><TD align=right COLSPAN=3>'.CheckboxInput($array['PARENT'],'tables['.$_REQUEST['category_id'].'][PARENT]',_('Parent'),'',$new,'<IMG SRC=images/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=images/x.gif vspace=0 hspace=0 border=0>').'</TD><TD width=30></TD>';
		}
	
		$header .= '</TR>';
		$header .= '</TABLE>';
	}
	else
		$header = false;

	if($header)
	{
		DisplayHeader($header);
                echo '</FORM>';	
	}

	// display categories
	$Gridoutput_options = array('save'=>false,'search'=>false,'add'=>true,'xscroll'=>false);
	
	echo '<TABLE><TR>';
	
	if(count($categories_array))
	{
		if($_REQUEST['category_id'])
		{
			foreach($categories_array as $key=>$value)
			{
				if($value['ID']==$_REQUEST['category_id'])
					$categories_array[$key]['row_color'] = Preferences('HIGHLIGHT');
			}
		}
	}
		
	echo '<TD valign=top>';
//	echo $_REQUEST['servicemod'];
	$columns = array('TITLE'=>_('Name of Category'),'USED_APPLICANTS'=>_('Applicants Only'));
	if($_REQUEST['servicemod'] != 'mod_apply/AppFieldsProperties.php')
		unset($columns['USED_APPLICANTS']);
	$link = array();
	$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]";
	$link['TITLE']['variables'] = array('category_id'=>'ID');
	$link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&category_id=new";
	Gridoutput($categories_array,$columns,_('Field Categories'),_('Amount of Categories'),$link,array(),$Gridoutput_options);
	echo '</TD>';
	
	// FIELDS
	if($_REQUEST['category_id'] && $_REQUEST['category_id']!='new' && count($categories_array))
	{
		echo '<TD valign=top width=75%>';
		$category_array = db_request(db_execute("SELECT ID,TITLE,COLUMNS FROM ".$categories_table." WHERE ID='".$_REQUEST['category_id']."'"));
		if($category_array[1]['COLUMNS']==3)
		{
			$count = 0;
			$bgcolor = Preferences('COLOR');
			echo '<TABLE class=EntireBox width=90% cellpadding=6><TR bgcolor='.$bgcolor.'>';
			if(count($fields_array))
			{
				echo '<b>'.count($fields_array).' '.$plural.'</b><BR><BR>';
				foreach($fields_array as $key=>$value)
				{
					if($value['TITLE']=='')
						$value['TITLE'] = '-';
					if($value['ID']==$_REQUEST['id'])
						echo '<TD style="background-color:'.Preferences('HIGHLIGHT').';"><A HREF=modloader.php?servicemod='.$_REQUEST['servicemod'].'&category_id='.$_REQUEST['category_id'].'&id='.$value['ID'].'><font color=white>'.$value['TITLE'].'</font></A><BR><small><font color=white>';
					else
						echo '<TD><A HREF=modloader.php?servicemod='.$_REQUEST['servicemod'].'&category_id='.$_REQUEST['category_id'].'&id='.$value['ID'].'>'.$value['TITLE'].'</A><BR><small><font color=gray>';
					
					echo $value['TYPE'].'</font></small></TD>';
					echo '</TD>';
					$count++;
					if($count%3==0)
					{
						echo '</TR>';
						if($bgcolor==Preferences('COLOR'))
							$bgcolor = 'F8F8F9';
						else
							$bgcolor = Preferences('COLOR');
						echo '<TR bgcolor='.$bgcolor.'>';
					}
				}
			}
			if(AllowEdit())
			{
				if($count%3!==0)
				{
					if($count%3==2)
						echo '<TD></TD>';
					elseif($count%3==1)
						echo '<TD colspan=2></TD>';
	
					echo '</TR>';
					if($bgcolor==Preferences('COLOR'))
						$bgcolor = 'F8F8F9';
					else
						$bgcolor = Preferences('COLOR');
					echo '<TR bgcolor='.$bgcolor.'>';
				}
	
				if($_REQUEST['id']=='new')
				{
					$bgcolor = ' bgcolor=#'.Preferences('HIGHLIGHT');
					$font = '<FONT color=white>';
					$close_font = '</FONT>';
				}
				else
				{
					$bgcolor = '';
					$font = '';
					$close_font = '';
				}
				echo '<TD'.$bgcolor.' colspan=3>'.button('add',($font._('Add a field').$close_font),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&category_id='.$_REQUEST['category_id'].'&id=new').'</TD>';
			}
			echo '</TR></TABLE>';
		}
		else
		{
			if(count($fields_array))
			{
				if($_REQUEST['id'])
				{
					foreach($fields_array as $key=>$value)
					{
						if($value['ID']==$_REQUEST['id'])
							$fields_array[$key]['row_color'] = Preferences('HIGHLIGHT');
					}
				}
			}
//			$stitle = str_replace('Amount of ','',$singular);
			$stitle = _('Name of Field');
			$columns = array('TITLE'=>$stitle,'TYPE'=>_('Data Type of Field'),'ID'=>_('Field ID'));
			$link = array();
			$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&category_id=$_REQUEST[category_id]";
			$link['TITLE']['variables'] = array('id'=>'ID');
			$link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&category_id=$_REQUEST[category_id]&id=new";
		
//			Gridoutput($fields_array,$columns,$singular,$plural,$link,array(),$Gridoutput_options);
			Gridoutput($fields_array,$columns,$singular,$plural,$link,array(),$Gridoutput_options);
		}

		echo '</TD>';
	}
	
	echo '</TR></TABLE>';
}

function _makeType($value,$name)
{
	$options = array('radio'=>_('Checkbox'),
		'text'=>_('Text'),
		'select'=>_('PullDown'),
		'select_one'=>_('Select One'),
		'date'=>_('Date'),
		'numeric'=>_('Numeric'),
		'faculty'=>_('Static Type: Faculties'),
		'textarea'=>_('Long Text'),
		'multiple'=>_('Select Multiple'),
		'log'=>_('Logging Fields'),
		'holder'=>_('Placeholder'),
		'file'=>_('File Upload'));
	return $options[$value];
}

function _printText($value,$name)
{
	
	if(!$value)
		return _('No');
	else
		return _($value);
}

function _changeSelect($value)
{
	$types = array('select'=>_('PullDown'),
		'select_one'=>_('Select One'),
		'text'=>_('Text'));
	return SelectInput($value,'tables['.$_REQUEST['id'].'][TYPE]',_('Data Type of Field'),$types,false);
}
/*

*/
function _rearrangeSortOrders($category_id,$field_id,$old,$new=false,$moved=false)
{	global $custom_fields_table,$student_fields_join_categories;

	if($old===false && $new === false && $moved=== true)
	{
		if($_REQUEST['category_id'])
		{
			/*
				when we moved the field from one to another category, check, if this field
				already exists in the $custom_fields_table. If so, exit from the function and
				don't change the sort_order for it
			*/
			$fieldsIsset = db_request(db_execute("SELECT CATEGORY_ID FROM ".$custom_fields_table." WHERE ID=".$field_id));	
			
			if(($fieldsIsset[1]['CATEGORY_ID'] == $_REQUEST['category_id']) || ($fieldsIsset[1]['CATEGORY_ID']==$_SESSION['fieldParentCategoryId']))
				return 1;
		}
		$new = (_getMaxSortOrder($custom_fields_table, $student_fields_join_categories, $category_id)+1);
	}
	
	$issetMultipleFields = db_request(db_execute("SELECT * FROM ".$student_fields_join_categories." WHERE CATEGORY_ID = ".$category_id));

	// -1 indicates that the field should be placed at the end of the list
	if($new==-1)
	{
		$last_array = db_request(db_execute("SELECT COALESCE(MAX(SORT_ORDER),0) AS MAX FROM ".$custom_fields_table." WHERE CATEGORY_ID='$category_id'"));
		// SET THE SORT ORDER TO 1 MORE THAN THE CURRENT MAX, UNLESS THE NEW FIELD IS THE FIRST TO BE CREATED IN THIS TAB
		if($last_array[1]['MAX']!=-1)
			$new = ($last_array[1]['MAX']+1);
		else
			$new = 1;
	}

	// we're adding this field
	if(!$old)
	{
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER=(SORT_ORDER+1) WHERE SORT_ORDER>='$new' AND CATEGORY_ID='$category_id'");
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER='$new' WHERE ID='$field_id'");
	}
	// old has been deleted
	elseif($old && $new===false)
	{
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER=(SORT_ORDER-1) WHERE SORT_ORDER>'$old' AND CATEGORY_ID='$category_id'");	
	
		if($issetMultipleFields)
			db_execute("UPDATE ".$student_fields_join_categories." SET SORT_ORDER=(SORT_ORDER-1) WHERE SORT_ORDER>'$old' AND CATEGORY_ID='$category_id'");
	}
	// field hasn't been moved at all
	elseif($old==$new)
		return;
	// field has been pushed down the page
	elseif($old<$new)
	{
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER=(SORT_ORDER-1) WHERE SORT_ORDER>'$old' AND SORT_ORDER<'$new' AND CATEGORY_ID='$category_id'");
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER='".($new-1)."' WHERE ID='$field_id'");
		
		if($issetMultipleFields)
			db_execute("UPDATE ".$student_fields_join_categories." SET SORT_ORDER=(SORT_ORDER-1) WHERE SORT_ORDER>'$old' AND SORT_ORDER<'$new' AND CATEGORY_ID='$category_id'");
	}
	// field has been pushed up the page 
	elseif($old>$new)
	{
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER=(SORT_ORDER+1) WHERE SORT_ORDER<'$old' AND SORT_ORDER>='$new' AND CATEGORY_ID='$category_id'");
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER='$new' WHERE ID='$field_id'");

		if($issetMultipleFields)
			db_execute("UPDATE ".$student_fields_join_categories." SET SORT_ORDER=(SORT_ORDER+1) WHERE SORT_ORDER<'$old' AND SORT_ORDER>='$new' AND CATEGORY_ID='$category_id'");

	}
}

/*
	we will use this function for setting the correct sort_order, when are used the 
	multiple fields
*/

function _rearrangeSortOrderForMultipleField($field_id, $category_id, $oldSortOrder, $new=false)
{	global $custom_fields_table,$student_fields_join_categories;

	// -1 indicates that the field should be placed at the end of the list
	if($new==-1)
	{
		$last_array = db_request(db_execute("SELECT COALESCE(MAX(SORT_ORDER),0) AS MAX
			FROM ".$custom_fields_table."
				WHERE
			CATEGORY_ID='$category_id'"));
		
		// SET THE SORT ORDER TO 1 MORE THAN THE CURRENT MAX, UNLESS THE NEW FIELD IS THE FIRST TO BE CREATED IN THIS TAB
		if($last_array[1]['MAX']!=-1)
			$new = ($last_array[1]['MAX']+1);
		else
			$new = 1;
	}
	
	if(!$oldSortOrder)
	{
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER=(SORT_ORDER+1) WHERE SORT_ORDER>='$new' AND CATEGORY_ID='$category_id'");
		db_execute("UPDATE ".$student_fields_join_categories." SET SORT_ORDER='$new' WHERE FIELD_ID='$field_id'");
	}
	// old has been deleted
	elseif($oldSortOrder && $new===false)
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER=(SORT_ORDER-1) WHERE SORT_ORDER>'$oldSortOrder' AND CATEGORY_ID='$category_id'");	
	// field hasn't been moved at all
	elseif($oldSortOrder==$new)
		return;
	// field has been pushed down the page
	elseif($oldSortOrder<$new)
	{
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER=(SORT_ORDER-1) WHERE SORT_ORDER>'$oldSortOrder' AND SORT_ORDER<'$new' AND CATEGORY_ID='$category_id'");
		db_execute("UPDATE ".$student_fields_join_categories." SET SORT_ORDER=(SORT_ORDER-1) WHERE SORT_ORDER>'$oldSortOrder' AND SORT_ORDER<'$new' AND CATEGORY_ID='$category_id'  AND FIELD_ID != '$field_id'");

		db_execute("UPDATE ".$student_fields_join_categories." SET SORT_ORDER='".($new-1)."' WHERE FIELD_ID='$field_id' AND CATEGORY_ID='$category_id'");
	}
	// field has been pushed up the page 
	elseif($oldSortOrder>$new)
	{
		db_execute("UPDATE ".$custom_fields_table." SET SORT_ORDER=(SORT_ORDER+1) WHERE SORT_ORDER<'$oldSortOrder' AND SORT_ORDER>='$new' AND CATEGORY_ID='$category_id'");
		db_execute("UPDATE ".$student_fields_join_categories." SET SORT_ORDER=(SORT_ORDER+1) WHERE SORT_ORDER<'$oldSortOrder' AND SORT_ORDER>='$new' AND CATEGORY_ID='$category_id' AND FIELD_ID != '$field_id'");
		db_execute("UPDATE ".$student_fields_join_categories." SET SORT_ORDER='$new' WHERE FIELD_ID='$field_id' AND CATEGORY_ID='$category_id'");
	}
}

?>

<script>
function checkFieldType(value, fieldNum)
{
	var obj = document.getElementById('loggingDiv' + fieldNum);
	
	if(value == 'select')
	{	
		if(obj)
		{
			obj.innerHTML = "<TABLE><TR><TD><colspan><fieldset><legend><?php echo _('PullDown Choices:'); ?></legend><center><textarea id='textarealogging[SELECT_OPTIONS]["+ fieldNum +"]' name='logging[SELECT_OPTIONS]["+ fieldNum +"]' cols='10' rows='3'></textarea></center><small><?php echo _('* one per line');?></small></fieldset></TD></TR><TR><TD><fieldset><legend><?php echo _('PullDown Codes:'); ?></legend><center><textarea id='textarealogging[SELECT_CODES]["+ fieldNum +"]' name='logging[SELECT_CODES]["+ fieldNum +"]' cols='10' rows='3' onchange='CompareAmountOpCodes(this);'></textarea></center><small><?php echo _('* one per line'); ?></small></fieldset></TR></TD></TABLE><div><fieldset><center><input name='logging[VALUE]["+fieldNum+"_SIZE]' id='inputlogging[VALUE][" + fieldNum +"_SIZE]' value=\"\" type='text' class='numeric'></center><legend><?php echo _('Input width');?></legend></fieldset></div>";
		}
	}
	else if(value == 'date')
	{
		obj.innerHTML = "<div><fieldset><select name='logging[DATEVALUE][" + fieldNum +"]' id='inputlogging[DATEVALUE][" + fieldNum +"]'><option value='today' ><?php echo _('Today');?></option><option value='yesterday'><?php echo _('Yesterday');?></option><option value='tomorrow'><?php echo _('Tomorrow');?></option><option value='blank'><?php echo _('Blank');?></option></select>&nbsp;<legend><?php echo _('Default:'); ?></legend></fieldset></div>";
	}
        else if(value == 'text' || value == 'numeric')
        {
            obj.innerHTML =  "<div><fieldset><center><input name='logging[VALUE]["+fieldNum+"_SIZE]' id='inputlogging[VALUE][" + fieldNum +"_SIZE]' value=\"\" type='text' class='numeric'></center><legend><?php echo _('Input width');?></legend></fieldset></div><div><fieldset><center><input name='logging[VALUE]["+fieldNum+"_COUNT_TOTAL]' id='inputlogging[VALUE][" + fieldNum +"_COUNT_TOTAL]' value=\"Y\" type='checkbox'></center><legend><?php echo _('Sum Values');?></legend></fieldset></div>";
        }
        else
	{
		if(obj)
		{
			obj.innerHTML = "";
		}
	}
	
	return 1;
}

function addNewLogField()
{
	var table = document.getElementById('loggingTable');
	if(table)
	{
		if(table.hasChildNodes())
		{	
		  var children = table.childNodes;
          var length = children.length;
          
          for(var j = 1; j <= length; j++)
          {
          	var fieldObj = document.getElementById('inputlogging[TYPE][LOG_FIELD'+j+']');
          	
          	if(!fieldObj)
          	{
          		length = j;
          		continue;
          	}
          }
          
		/* to allow user to have only 10 log fields */
         if(length == 21)	
			return 0;
			
         var newCell = document.createElement("TD");
		 newCell.rowSpan = "2";
		 newCell.vAlign = "top";
		 newCell.width="10%";
         
		 innerHTMLText = "<BR><TABLE><TR><TD align=center><div align='center' style='width:70px;'><?php echo _('Field #');?>" + length + "</div></TD></TR><TR><TD align=center><fieldset>";
		 innerHTMLText += "<select name='logging[TYPE][LOG_FIELD" + length +"]' id='inputlogging[TYPE][LOG_FIELD" + length +"]' onchange='checkFieldType(this.options[this.selectedIndex].value, &quot;LOG_FIELD" + length +"&quot;)'><option value='' ><?php echo _('N/a');?></option><option value='radio'><?php echo _('Checkbox');?></option><option value='text'><?php echo _('Text');?></option><option value='select'><?php echo _('PullDown');?></option><option value='numeric'><?php echo _('Numeric');?></option><option value='date'><?php echo _('Date');?></option><option value='textarea'><?php echo _('Long Text');?></option><option value='time'><?php echo _('Time');?></option></select><br>";
                innerHTMLText += "<legend><?php echo _('Field Type');?></legend></fieldset></TD></TR><TR><TD><fieldset><center><input name='logging[VALUE][LOG_FIELD" + length +"_TITLE]' id='inputlogging[VALUE][LOG_FIELD" + length +"_TITLE]' size='10' type='text'></center><legend><?php echo _('Field Title');?></legend></fieldset></TD></TR><TR><TD align=center>";
                innerHTMLText += "<div id='loggingDivLOG_FIELD" + length +"'></div></TD></TR></TABLE>";
         
         newCell.innerHTML = innerHTMLText;
         //table.insertBefore(newCell, table.firstChild.nextSibling);
         table.appendChild(newCell);
		}
	}
}
</script>
<?php
if($_REQUEST['servicemod'] !== 'applicants_online'){
echo GetBaseJavaFunc();
echo GetAdvJavaFuncStuFields();
}
?>
