<?php

if(!$_REQUEST['CREATEPDF'])
{
	echo GetBaseJavaFunc();
}
DisplayHeader(".:".ProgramTitle().":.",false,false,false,false,false,false,false,'no');
$course_section_id = get_user_coursesection();
$course_id = db_request(db_execute("SELECT COURSE_ID,COURSE_CREDIT_TITLE,SCHOOL_TERM_ID,MERGE_ID FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='".get_user_coursesection()."'"));
$course_credits = $course_id[1]['COURSE_CREDIT_TITLE'];
$school_term_id = $course_id[1]['SCHOOL_TERM_ID'];
$merge_id = $course_id[1]['MERGE_ID'];
//Checking for merged sections and return main course_section_id
if($merge_id)
	if(strpos($merge_id,','))
		$course_section_id = substr($merge_id,0,strpos($merge_id,','));
	else
		$course_section_id = $merge_id;
$course_id = $course_id[1]['COURSE_ID'];
$course_title = db_request(db_execute("SELECT TITLE FROM COURSES WHERE COURSE_ID='".$course_id."'"));
$course_title = $course_title[1]['TITLE'];

$_SYSTEM['allow_edit'] = true;
unset($_SESSION['_REQUEST_vars']['assignment_type_id']);
unset($_SESSION['_REQUEST_vars']['assignment_id']);

$config_array = db_request(db_execute("SELECT TITLE,VALUE FROM SYSTEM_USER_SETTINGS WHERE USERNAME='".get_user('USERNAME')."' AND PROGRAM='Gradebook'"),array(),array('TITLE'));
if(count($config_array))
{
	foreach($config_array as $title=>$value)
		$programconfig[$title] = $value[1]['VALUE'];
	if($programconfig['WEIGHT']=='')
	    if(Preferences('WEIGHT','Gradebook') == 'Y')
		$programconfig['WEIGHT'] = Preferences('WEIGHT','Gradebook');
}
else
{
	if($programconfig['WEIGHT']=='')
	    if(Preferences('WEIGHT','Gradebook') == 'Y')
		$programconfig['WEIGHT'] = Preferences('WEIGHT','Gradebook');

}

if($_REQUEST['day_tables'] && $_POST['day_tables'])
{
	foreach($_REQUEST['day_tables'] as $id=>$values)
	{
		if($_REQUEST['day_tables'][$id]['DUE_DATE'] && $_REQUEST['month_tables'][$id]['DUE_DATE'] && $_REQUEST['year_tables'][$id]['DUE_DATE'])
			$_REQUEST['tables'][$id]['DUE_DATE'] = $_REQUEST['year_tables'][$id]['DUE_DATE'].'-'.$_REQUEST['month_tables'][$id]['DUE_DATE'].'-'.$_REQUEST['day_tables'][$id]['DUE_DATE'];
		if($_REQUEST['day_tables'][$id]['ASSIGNED_DATE'] && $_REQUEST['month_tables'][$id]['ASSIGNED_DATE'] && $_REQUEST['year_tables'][$id]['ASSIGNED_DATE'])
			$_REQUEST['tables'][$id]['ASSIGNED_DATE'] = $_REQUEST['year_tables'][$id]['ASSIGNED_DATE'].'-'.$_REQUEST['month_tables'][$id]['ASSIGNED_DATE'].'-'.$_REQUEST['day_tables'][$id]['ASSIGNED_DATE'];
	}
	$_POST['tables'] = $_REQUEST['tables'];
}

if($_REQUEST['tables'] && $_POST['tables'])
{
	$table = $_REQUEST['table'];

	foreach($_REQUEST['tables'] as $id=>$columns)
	{
		if($table=='MARKBOOK_ASSIGNMENT_TYPES' && $programconfig['WEIGHT']=='Y' && $columns['FINAL_GRADE_PERCENT'])
			$columns['FINAL_GRADE_PERCENT'] = preg_replace('[^0-9.]','',str_replace(",",".",$columns['FINAL_GRADE_PERCENT']/100));

		if($id!='new')
		{
			if($columns['ASSIGNMENT_TYPE_ID'] && $columns['ASSIGNMENT_TYPE_ID']!=$_REQUEST['assignment_type_id'])
				$_REQUEST['assignment_type_id'] = $columns['ASSIGNMENT_TYPE_ID'];

			$sql = "UPDATE $table SET ";

			//if(!$columns['COURSE_ID'] && $table=='MARKBOOK_ASSIGNMENTS')
			//	$columns['COURSE_ID'] = 'N';
			$go = false;
			foreach($columns as $column=>$value)
			{
				if($column=='DUE_DATE' || $column=='ASSIGNED_DATE')
		 		{
					if(!VerifyDate($value))
			 			BackPrompt(_('Some dates were entered incorrectly.'));
				}
				elseif($column=='COURSE_ID' && $value=='Y' && $table=='MARKBOOK_ASSIGNMENTS')
				{
					$value = $course_id;
					$sql .= 'COURSE_SECTION_ID=NULL,';
				}
				elseif($column=='COURSE_ID' && $table=='MARKBOOK_ASSIGNMENTS')
				{
					$column = 'COURSE_SECTION_ID';
					$value = $course_section_id;
					$sql .= 'COURSE_ID=NULL,';
				}
				elseif($column=='DEFAULT_FULL_CREDIT' && $table=='MARKBOOK_ASSIGNMENTS')// && $value == 'Y')
					$DEFAULT_FULL_CREDIT = $value;

				if(!is_array($value))
				{
                  	/* Save NULL if POINTS == / or \ */
					if($column == 'POINTS' && ($value == '/' || (get_magic_quotes_gpc() ? stripcslashes($value) == '\\' : $value == '\\'))) //'
					{
						$sql .= $column."='',";
						$go = true;
					}
					elseif($column <> 'DEFAULT_FULL_CREDIT')
					{
						$sql .= $column."='".str_replace("\'","''",$value)."',";
						$go = true;
					}
				}
				else
				{
					$sql .= $column."='||";
					foreach($value as $val)
					{
						if($val)
							$sql .= str_replace("\'","''",str_replace('``','"',$val)).'||';
					}
					$sql .= "',";
					$go = true;
				}
			}
			$sql = substr($sql,0,-1) . " WHERE ".substr($table,9,-1)."_ID='$id'";
			$go_insert = false;
		}
		else
		{
			$sql = "INSERT INTO $table ";
			if($table=='MARKBOOK_ASSIGNMENTS')
			{
				if($columns['ASSIGNMENT_TYPE_ID'])
				{
					$_REQUEST['assignment_type_id'] = $columns['ASSIGNMENT_TYPE_ID'];
					unset($columns['ASSIGNMENT_TYPE_ID']);
				}
				if(!$columns['SCHOOL_TERM_ID'])
					$columns['SCHOOL_TERM_ID'] = get_user_school_term();

				//$id = db_request(db_execute("SELECT ".db_seq_nextval('MARKBOOK_ASSIGNMENTS_SEQ').' AS ID '.FROM_DUAL));
				//$id = $id[1]['ID'];
				$fields = "ASSIGNMENT_ID,ASSIGNMENT_TYPE_ID,USER_ID,";
				$values = db_seq_nextval($table.'_SEQ').",'".$_REQUEST['assignment_type_id']."','".get_user('USER_ID')."',";
				//$_REQUEST['assignment_id'] = $id;
			}
			elseif($table=='MARKBOOK_ASSIGNMENT_TYPES')
			{
				//$id = db_request(db_execute("SELECT ".db_seq_nextval('MARKBOOK_ASSIGNMENT_TYPES_SEQ').' AS ID '.FROM_DUAL));
				//$id = $id[1]['ID'];
				$fields = "ASSIGNMENT_TYPE_ID,USER_ID,COURSE_ID,";
				$values = db_seq_nextval($table.'_SEQ').",'".get_user('USER_ID')."','$course_id',";
				//$_REQUEST['assignment_type_id'] = $id;
			}

			$go = false;
	                $multiple = false;

			if(!$columns['COURSE_ID'] && $_REQUEST['table']=='MARKBOOK_ASSIGNMENTS')
				$columns['COURSE_ID'] = 'N';

			if(!$columns['POINTS'] && $table=='MARKBOOK_ASSIGNMENTS')
			{
				$columns['POINTS'] = $_SESSION['POINTS'];
				unset($_SESSION['POINTS']);
			}
			foreach($columns as $column=>$value)
			{
				if($column=='DUE_DATE' || $column=='ASSIGNED_DATE')
		 		{
					if(!VerifyDate($value))
			 			BackPrompt(_('Some dates were entered incorrectly.'));
				}
				elseif($column=='COURSE_ID' && $value=='Y')
				{
                	//$value = $course_id;
            	        $column = "COURSE_SECTION_ID";
                	$value = "{COURSE_SECTION_ID}"; //template for multiple assignments
        	        $multiple = true;
                }
				elseif($column=='COURSE_ID')
				{
					$column = 'COURSE_SECTION_ID';
					$value = $course_section_id;
				}
                elseif($column=='DEFAULT_FULL_CREDIT')// && $value == 'Y')
				   $DEFAULT_FULL_CREDIT = $value;

				if(isset($value) && !is_array($value))
				{
					if($column <> 'DEFAULT_FULL_CREDIT')
					   $fields .= $column.',';

					/* Save NULL if POINTS == / or \ */
					if($column == 'POINTS' && ($value == '/' || stripcslashes($value) == '\\' || $value == '\\') && $value != '0') //'
						$values .= "'',";
					elseif($column <> 'DEFAULT_FULL_CREDIT')
						$values .= "'".str_replace("\'","''",$value)."',";

					$go = true;
					$go_insert = true;
				}
				else
				{
					if($column <> 'DEFAULT_FULL_CREDIT')
						$fields .= $column.',';
					$values .= "'||";
					foreach($value as $val)
					{
						if($val)
							$values .= str_replace("\'","''",str_replace('``','"',$val)).'||';
					}
					$values .= "',";
				}
			}
			$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
		}

		if($go)
		{
			if($multiple)
	                {
        			    //add assignments for all COURSE PERIODS this teacher teaches
		                $cp_array = db_request(db_execute("SELECT COURSE_SECTION_ID FROM COURSE_SECTIONS WHERE COURSE_ID='".$course_id."' AND TEACHER_ID='".get_user('USER_ID')."' AND SCHOOL_TERM_ID='".$school_term_id."'"));
	    	                foreach($cp_array as $cpid)
		                {
		                        if($cpid['COURSE_SECTION_ID'])
                		        db_execute(str_replace("{COURSE_SECTION_ID}",$cpid['COURSE_SECTION_ID'], $sql));
		                }
	                }
        		else
	                {
		                db_execute($sql);
	                }
			if($go_insert==true)
			{
				if($table=='MARKBOOK_ASSIGNMENTS')
					$_REQUEST['assignment_id'] = db_seq_currval($table.'_SEQ');
				elseif($table=='MARKBOOK_ASSIGNMENT_TYPES')
					$_REQUEST['assignment_type_id'] = db_seq_currval($table.'_SEQ');
			}
		}
		if($table=='MARKBOOK_ASSIGNMENTS' && is_numeric($DEFAULT_FULL_CREDIT))
		{
			if($columns['COURSE_ID']=='Y')
			{
				$_REQUEST['_search_all_periods'] = 'Y';
				$addition_dfc['WHERE'] = " AND cp.COURSE_ID='".$course_id."' ";
			}
			$students_array = get_student_list($addition_dfc);
			unset($_REQUEST['_search_all_periods']);
			//Find students which allready have points at this assigment
//			if(!$go_insert) // we are not inserting a new record, so we might need to query the points for this assignment
//			{
//				$dfc_points_array = db_request(db_execute("SELECT POINTS FROM MARKBOOK_ASSIGNMENTS WHERE ASSIGNMENT_ID='".$_REQUEST['assignment_id']."'"));
//				$columns['POINTS'] = $dfc_points_array[1]['POINTS'];
//			}
			$StudentsHavePoint_array = db_request(db_execute("SELECT STUDENT_ID,POINTS FROM STUDENT_MARKBOOK_GRADES WHERE ASSIGNMENT_ID='".$_REQUEST['assignment_id']."'"),null,array('STUDENT_ID'));
	                $points = $DEFAULT_FULL_CREDIT;
			foreach($students_array as $student)
			{
				if(!$StudentsHavePoint_array[$student['STUDENT_ID']])
					db_execute("INSERT INTO STUDENT_MARKBOOK_GRADES (STUDENT_ID,COURSE_SECTION_ID,ASSIGNMENT_ID,POINTS) values('".$student['STUDENT_ID']."','".$student['COURSE_SECTION_ID']."','".$_REQUEST['assignment_id']."','".$points."')");
				elseif($StudentsHavePoint_array[$student['STUDENT_ID']][1]['POINTS']=='')
					db_execute("UPDATE STUDENT_MARKBOOK_GRADES SET POINTS='".$points."' WHERE STUDENT_ID='".$student['STUDENT_ID']."' AND ASSIGNMENT_ID='".$_REQUEST['assignment_id']."'");
			}
		}
	}
	unset($_REQUEST['tables']);
	unset($_SESSION['_REQUEST_vars']['tables']);
}

if($_REQUEST['servicefunction']=='delete')
{
	if($_REQUEST['assignment_id'])
	{
		$delete_button_title = _('Delete Assignment');
		$sql = "DELETE FROM MARKBOOK_ASSIGNMENTS WHERE ASSIGNMENT_ID='$_REQUEST[assignment_id]'";
		$question = '<b>'._('Do you want to delete this assignment?').'</b>';
		$grades_array = db_request(db_execute("SELECT '' FROM STUDENT_MARKBOOK_GRADES WHERE ASSIGNMENT_ID='$_REQUEST[assignment_id]' AND POINTS IS NOT NULL"));
		if(count($grades_array))
		{
//			$second_confirm = ErrorMessage(array(_('This assignment has been graded. Deleting the assignment will also delete the grades.')),'warning');
			$second_confirm = ErrorMessage(array(_('The grades were posted for this assignment. If you delete the assignment, you will also delete the grades.')),'warning');
		}
	}
	else
	{
		$delete_button_title = _('Delete Category');
		$sql = "DELETE FROM MARKBOOK_ASSIGNMENT_TYPES WHERE ASSIGNMENT_TYPE_ID='$_REQUEST[assignment_type_id]'";
		$question = '<b>'._('Do you want to delete this assignment category?').'</b>';
		$assignments_array = db_request(db_execute("SELECT ASSIGNMENT_ID FROM MARKBOOK_ASSIGNMENTS WHERE ASSIGNMENT_TYPE_ID='$_REQUEST[assignment_type_id]'"));
		if(count($assignments_array))
		{
			$second_confirm = ErrorMessage(array(_('This category contains some assignments.If you delete the category, you will also delete the assignments in this category.')),'warning');
		}
	}

	if(Prompt(_("Delete Confirmation"), "<b>".$question."</b>", "", '', $delete_button_title, null, $second_confirm))
	{
		if(!$_REQUEST['assignment_id'])
		{
			$assignments_array = db_request(db_execute("SELECT ASSIGNMENT_ID FROM MARKBOOK_ASSIGNMENTS WHERE ASSIGNMENT_TYPE_ID='$_REQUEST[assignment_type_id]'"));
			if(count($assignments_array))
			{
				foreach($assignments_array as $assignment_id)
					db_execute("DELETE FROM STUDENT_MARKBOOK_GRADES WHERE ASSIGNMENT_ID='".$assignment_id['ASSIGNMENT_ID']."'");
			}
			db_execute("DELETE FROM MARKBOOK_ASSIGNMENTS WHERE ASSIGNMENT_TYPE_ID='$_REQUEST[assignment_type_id]'");
			unset($_REQUEST['assignment_type_id']);
		}
		else
		{
			db_execute("DELETE FROM STUDENT_MARKBOOK_GRADES WHERE ASSIGNMENT_ID='$_REQUEST[assignment_id]'");
			unset($_REQUEST['assignment_id']);
		}
		db_execute($sql);
		unset($_REQUEST['servicefunction']);
	}
}

if(!$_REQUEST['servicefunction'] && $course_id)
{
//echo $course_id."<br>";
//echo $course_section_id."<br>";
//echo $merge_id."<br>";
//echo $_REQUEST['assignment_type_id']."<br>";
//echo $_REQUEST['assignment_id']."<br>";
//var_dump($_REQUEST);
	// работа с типами заданий
	$types_array = db_request(db_execute("SELECT ASSIGNMENT_TYPE_ID,TITLE,FINAL_GRADE_PERCENT,FINAL_GRADE_PERCENT AS FINAL_GRADE_PERCENT_PRINT FROM MARKBOOK_ASSIGNMENT_TYPES WHERE USER_ID='".get_user('USER_ID')."' AND COURSE_ID='".$course_id."' ORDER BY TITLE"),array('FINAL_GRADE_PERCENT_PRINT'=>'Percent'));
//	var_dump($types_array);
	if(count($types_array)==1 && !$_REQUEST['assignment_type_id'])
		$_REQUEST['assignment_type_id'] = $types_array[1]['ASSIGNMENT_TYPE_ID'];

	if($_REQUEST['assignment_id']!='new' && $_REQUEST['assignment_type_id']!='new')
		$delete_button = "<INPUT style='width:100px;' type=button value="._('Delete')." onClick='javascript:window.location=\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete&assignment_type_id=$_REQUEST[assignment_type_id]&assignment_id=$_REQUEST[assignment_id]\"'>";

	// редактирование и добавление заданий
	if($_REQUEST['assignment_id'] && $_REQUEST['assignment_id']!='new')
	{
		$sql = "SELECT ASSIGNMENT_TYPE_ID,TITLE,ASSIGNED_DATE,DUE_DATE,POINTS,COURSE_ID,DESCRIPTION,SCHOOL_TERM_ID,BENCHMARKS
				FROM MARKBOOK_ASSIGNMENTS
				WHERE ASSIGNMENT_ID='$_REQUEST[assignment_id]'";
		$QI = db_execute($sql);
		$array = db_request($QI);
		$array = $array[1];
		$title = $array['TITLE'];
	}
	elseif($_REQUEST['assignment_type_id'] && $_REQUEST['assignment_type_id']!='new' && $_REQUEST['assignment_id']!='new')
	{
		$sql = "SELECT TITLE,HCOLOR,FINAL_GRADE_PERCENT
				FROM MARKBOOK_ASSIGNMENT_TYPES
				WHERE ASSIGNMENT_TYPE_ID='$_REQUEST[assignment_type_id]'";
		$QI = db_execute($sql);

		$array = db_request($QI,array('FINAL_GRADE_PERCENT'=>'_makePercent'));
		$array = $array[1];
		$title = $array['TITLE'];
	}
	elseif($_REQUEST['assignment_id']=='new')
		$title = _('New Assignment');
	elseif($_REQUEST['assignment_type_id']=='new')
		$title = _('New Assignment Category');

	if($_REQUEST['assignment_id'])
	{
		echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&assignment_type_id=$_REQUEST[assignment_type_id]";
		if($_REQUEST['assignment_id']!='new')
			echo "&assignment_id=$_REQUEST[assignment_id]";
		echo "&table=MARKBOOK_ASSIGNMENTS method=POST>";
		$_REQUEST['DrawAlign'] = 'LEFT';
		DisplayHeader('<B>'.$title.'</B>',$delete_button.' &nbsp; &nbsp;<INPUT style="width:100px;" type=submit value='._('Save').'>',false,false,false,false,false,false,'no');
		unset($_REQUEST['DrawAlign']);
		//Панель ввода и отображения данных начинает формироваться тут
		$header .= '<TABLE border=0 cellpadding=3 cellspacing=0 width=100%>';

		if($array['POINTS'] == NULL && $_REQUEST['assignment_id'] != 'new')
			$retPoints = '/';
		elseif($_REQUEST['assignment_id'] == 'new')
		{
			$_SESSION['POINTS'] = '5';
			$retPoints = '5';
		}
		else
			$retPoints = $array['POINTS'];


		$header .= '<TR><Td height=35 colspan=5 align=center valign=top style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;">';

	        if($_REQUEST['assignment_id']=='new')
	        	$header .= ''.CheckboxInput($array['COURSE_ID'],'tables['.$_REQUEST['assignment_id'].'][COURSE_ID]',sprintf(_('Add this assignment to all sections of %s that I teach'),$course_title),null,($_REQUEST['assignment_id']=='new'),'<IMG SRC=images/check.gif height=12>','<IMG SRC=images/x_small.gif>') . '</TD>';


                $header .= '</TD></TR><TR>';



//		$header .=<>
		$header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;" align=center>'.TextInput($array['TITLE'],'tables['.$_REQUEST['assignment_id'].'][TITLE]',_('Assignment Title'),' size=20') . '</TD>';
		$header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;">'.TextInput($retPoints,'tables['.$_REQUEST['assignment_id'].'][POINTS]',_('Points Equal Highest Grade'),' size=4 maxlength=4').'</TD>';
		if(Preferences('APPLY_ALL_DEFAULT','Gradebook')=='Y')
			$array['COURSE_ID'] = 'Y';

		$dfc_title = _('Auto-Fill Points');
	    $header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;">' . TextInput('','tables['.$_REQUEST['assignment_id'].'][DEFAULT_FULL_CREDIT]',$dfc_title,'',true).'<BR>';

        $header .= '</TD>';

		$mps_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,TITLE FROM SCHOOL_QUARTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
		foreach($mps_array as $mp)
			$mps_options[$mp['SCHOOL_TERM_ID']] = $mp['TITLE'];

		$header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;" VALIGN=TOP>'.SelectInput($array['SCHOOL_TERM_ID']?$array['SCHOOL_TERM_ID']:get_user_school_term(),'tables['.$_REQUEST['assignment_id'].'][SCHOOL_TERM_ID]',_('School Term'),$mps_options,false) . '</TD>';

		foreach($types_array as $type)
			$assignment_type_options[$type['ASSIGNMENT_TYPE_ID']] = $type['TITLE'];

		$header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;">' . SelectInput($array['ASSIGNMENT_TYPE_ID']?$array['ASSIGNMENT_TYPE_ID']:$_REQUEST['assignment_type_id'],'tables['.$_REQUEST['assignment_id'].'][ASSIGNMENT_TYPE_ID]',_('Assignment Category'),$assignment_type_options,false) . '</TD>';

		$header .= '</TR><TR>';
		if($_REQUEST['assignment_id']!='new')
		{
			$header .= '<TD align=center><TABLE border=0 ><TR>';
			$header .= '<TD valign=top ALIGN=RIGHT>'.DateInput($array['ASSIGNED_DATE'],'tables['.$_REQUEST['assignment_id'].'][ASSIGNED_DATE]',_('Assigned Date'));
			if(!count($benchmarks_array))
				$header .= '</TD></TR><TR><TD valign=top ALIGN=RIGHT><HR>';
			else
				$header .= '<BR>';
			$header .=  DateInput($array['DUE_DATE'],'tables['.$_REQUEST['assignment_id'].'][DUE_DATE]',_('Expiring Date')).'</TD></TR></TABLE></TD>';
			$div = 'force';
		}
		else
		{
			if(Preferences('DEFAULT_DUE_DATE','Gradebook')=='tomorrow')
				$default_due_date = get_db_date('postgres',(time()+86400));
			else
				$default_due_date = get_db_date('postgres');

			$header .= '<TD align=center><TABLE border=0><TR>';
			$header .= '<TD valign=top>' . DateInput(get_db_date(),'tables['.$_REQUEST['assignment_id'].'][ASSIGNED_DATE]',_('Assigned Date'),false);
			if(!count($benchmarks_array))
				$header .= '</TD></TR><TR><TD valign=top ALIGN=RIGHT>';
			else
				$header .= '<BR>';
			$header .= DateInput($default_due_date,'tables['.$_REQUEST['assignment_id'].'][DUE_DATE]',_('Expiring Date'),false).'</TD></TR></TABLE></TD>';
			$div = 'false';
		}

		if($_REQUEST['assignment_id']!='new')
			$div = 'force';
		else
			$div = 'false';
		$header .= '<TD colspan=2 valign=top>'.TextAreaInput($array['DESCRIPTION'],'tables['.$_REQUEST['assignment_id'].'][DESCRIPTION]','<BR>'._('Assignment Description'),null,$div).'</TD>';

	        $benchmarks_array = db_request(db_execute("SELECT ID,TITLE FROM GRADES_CARD_EVALUATION WHERE COURSE_ID='".$course_id."' AND COURSE_CREDIT_TITLE='".$course_credits."' ORDER BY STANDARD_ID,SORT_ORDER"));
		if(count($benchmarks_array))
		{
			$options = array();
			foreach($benchmarks_array as $benchmark)
				$options[$benchmark['ID']] = $benchmark['TITLE'];
			$header .= '<TD colspan=2 style="max-width:600px;">' . SelectMultipleInput($array['BENCHMARKS'],'tables['.$_REQUEST['assignment_id'].'][BENCHMARKS]',_('Benchmarks'),$options,null,null,$div,3) . '</TD>';
		}

		$header .= '</TR>';
		$header .= '</TABLE><HR>';
	}
	elseif($_REQUEST['assignment_type_id'])
	{
		echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&table=MARKBOOK_ASSIGNMENT_TYPES";
		if($_REQUEST['assignment_type_id']!='new')
			echo "&assignment_type_id=$_REQUEST[assignment_type_id]";
		echo " method=POST>";
		$_REQUEST['DrawAlign'] = 'ALIGN_LEFT';
		DisplayHeader($title,$delete_button.' &nbsp; &nbsp;<INPUT style="width:100px;" type=submit value='._('Save').'>',false,false,false,false,false,false,'no');
		unset($_REQUEST['DrawAlign']);
		//прорисовка заголовков категорий заданий
		$header .= '<TABLE  border=0 cellpadding=3 width=100%>';
		$header .= '<TR>';

		$header .= '<TD>'.TextInput($array['TITLE'],'tables['.$_REQUEST['assignment_type_id'].'][TITLE]',_('Aissignment Category Title')).'</TD>';
                $header .= _('Color:').'<div id="colorSelector"><div style="background-color:#'.$array['HCOLOR'].';"></div></div><input type="hidden" name="tables['.$_REQUEST['assignment_type_id'].'][HCOLOR]" value="'.$array['HCOLOR'].'" id="HCOLOR">';
		if($programconfig['WEIGHT']=='Y')
 			$header .= '<TD>'.TextInput($array['FINAL_GRADE_PERCENT'],'tables['.$_REQUEST['assignment_type_id'].'][FINAL_GRADE_PERCENT]',_('Percent of Final Grade')).'</TD>';


		$header .= '</TR>';
		$header .= '</TABLE>';
	}
	else
		$header = false;

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

	if($programconfig['WEIGHT']=='Y')
	{
		foreach($types_array as $type)
		{
			$weight_sum += $type['FINAL_GRADE_PERCENT'];
		}
		if(Percent($weight_sum)!=Percent(1))
			echo ErrorMessage(array(_('Category Weights do not add up to 100%. The sum of the Percent of Final Grade fields for your categories is ').Percent($weight_sum).'.'),_('Warning'));
	}

	// DISPLAY THE MENU
	$Gridoutput_options = array('save'=>false,'search'=>false,'add'=>true,'xscroll'=>false);

	echo '<TABLE><TR>';

	if(count($types_array))
	{
		if($_REQUEST['assignment_type_id'])
		{
			foreach($types_array as $key=>$value)
			{
				if($value['ASSIGNMENT_TYPE_ID']==$_REQUEST['assignment_type_id'])
					$types_array[$key]['row_color'] = Preferences('HIGHLIGHT');
			}
		}
	}

	echo '<TD valign=top>';
	$columns = array('TITLE'=>_('Assignment Category'));
	if($programconfig['WEIGHT']=='Y')
		$columns['FINAL_GRADE_PERCENT_PRINT'] = _('Weight');
	$link =array();
	$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]";
	$link['TITLE']['variables'] = array('assignment_type_id'=>'ASSIGNMENT_TYPE_ID');
	$link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&assignment_type_id=new";

	Gridoutput($types_array,$columns,_('Assignment Categories'),_('Amount of Assignment Categories'),$link,array(),$Gridoutput_options);
	echo '</TD>';


	// ASSIGNMENTS
	if($_REQUEST['assignment_type_id'] && $_REQUEST['assignment_type_id']!='new' && count($types_array))
	{
		$QI = db_execute("SELECT ASSIGNMENT_ID,TITLE,POINTS,DUE_DATE FROM MARKBOOK_ASSIGNMENTS WHERE USER_ID='".get_user('USER_ID')."' AND (COURSE_ID='".$course_id."' OR COURSE_SECTION_ID='".$course_section_id."') AND ASSIGNMENT_TYPE_ID='".$_REQUEST['assignment_type_id']."' AND SCHOOL_TERM_ID='".get_user_school_term()."' ORDER BY DUE_DATE,TITLE");
		$assn_array = db_request($QI,array('TITLE'=>'_makeAssignmentTitle','DUE_DATE'=>'ProperDate'));

		if(count($assn_array))
		{
			if($_REQUEST['assignment_id'] && $_REQUEST['assignment_id']!='new')
			{
				foreach($assn_array as $key=>$value)
				{
					if($value['ASSIGNMENT_ID']==$_REQUEST['assignment_id'])
						$assn_array[$key]['row_color'] = Preferences('HIGHLIGHT');
				}
			}
		}

		echo '<TD valign=top>';
		$columns = array('TITLE'=>_('Assignment Title'),'DUE_DATE'=>_('Expiring Date'));
		$link = array();
		$link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&assignment_type_id=$_REQUEST[assignment_type_id]";
		$link['TITLE']['variables'] = array('assignment_id'=>'ASSIGNMENT_ID');
		$link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&assignment_type_id=$_REQUEST[assignment_type_id]&assignment_id=new";

		Gridoutput($assn_array,$columns,_('Assignments'),_('Amount of Assignments'),$link,array(),$Gridoutput_options);

		echo '</TD>';
	}

	echo '</TR></TABLE>';
}
elseif(!$course_id)
	echo '<BR>'.ErrorMessage(array(_('There is no courses assigned for you at this period.')),'error');
	// You don\'t have a course this period

function _makePercent($value,$column)
{
	return Percent($value,2);
}

function _makeAssignmentTitle($value,$column)
{	global $THIS_array;

	if(!empty($THIS_array['POINTS']))
		return $value.' ('.$THIS_array['POINTS'].')';
	else
		return $value;

}
?>