<?php

echo GetBaseJavaFunc();
$_SESSION['List_PHP_SELF'] = SetRequestOptions();
$course_section_id = get_user_coursesection();
$real_course_section_id = get_user_coursesection();
$course_id = db_request(db_execute("SELECT COURSE_ID,COURSE_CREDIT_TITLE,GRADE_TYPE_ID,SCHOOL_TERM_ID,MERGE_ID FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='".get_user_coursesection()."'"));
$course_credits = $course_id[1]['COURSE_CREDIT_TITLE'];
$grade_scale_id = $course_id[1]['GRADE_TYPE_ID'];
$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'];
if(SystemPreferences('WEIGHTS')=='Y')
	$course_title .= ' - '.$course_credits;

$types_array = db_request(db_execute("SELECT ASSIGNMENT_TYPE_ID,HCOLOR,TITLE,FINAL_GRADE_PERCENT FROM MARKBOOK_ASSIGNMENT_TYPES WHERE USER_ID='".get_user('USER_ID')."' AND COURSE_ID='".$course_id."' ORDER BY TITLE"));

include $staticpath.'functions/extra/MakeGrades.fnc.php';
if(($_REQUEST['assignment_id'] && $_REQUEST['assignment_id']!='student') && !$_REQUEST['values'])
{
	unset($_SESSION['student_id']);
	unset($_REQUEST['student_id']);
}
if($_REQUEST['assignment_id']!='totals')
	unset($_SESSION['_REQUEST_vars']['assignment_id']);

$_SYSTEM['allow_edit'] = true;
$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($_REQUEST['day_tables'] && $_POST['day_tables'])
{
	if($_REQUEST['day_tables']['DUE_DATE'] && $_REQUEST['month_tables']['DUE_DATE'] && $_REQUEST['year_tables']['DUE_DATE'])
		$_REQUEST['tables']['DUE_DATE'] = $_REQUEST['year_tables']['DUE_DATE'].'-'.$_REQUEST['month_tables']['DUE_DATE'].'-'.$_REQUEST['day_tables']['DUE_DATE'];
	if($_REQUEST['day_tables']['ASSIGNED_DATE'] && $_REQUEST['month_tables']['ASSIGNED_DATE'] && $_REQUEST['year_tables']['ASSIGNED_DATE'])
		$_REQUEST['tables']['ASSIGNED_DATE'] = $_REQUEST['year_tables']['ASSIGNED_DATE'].'-'.$_REQUEST['month_tables']['ASSIGNED_DATE'].'-'.$_REQUEST['day_tables']['ASSIGNED_DATE'];

	$_POST['tables'] = $_REQUEST['tables'];
}

if($_REQUEST['tables'] && $_POST['tables'] && $_REQUEST['tables']['TITLE'])
{
	if(!$_REQUEST['tables']['ASSIGNMENT_TYPE_ID'])
	{
		//$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,TITLE,";
		$values = db_seq_nextval('MARKBOOK_ASSIGNMENT_TYPES_SEQ').",'".get_user('USER_ID')."','$course_id','"._('Assignments')."',";

		$sql = "INSERT INTO MARKBOOK_ASSIGNMENT_TYPES ";
		$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
		db_execute($sql);
		$_REQUEST['tables']['ASSIGNMENT_TYPE_ID'] = db_seq_currval('MARKBOOK_ASSIGNMENT_TYPES_SEQ');
		$types_array = db_request(db_execute("SELECT ASSIGNMENT_TYPE_ID,TITLE,FINAL_GRADE_PERCENT FROM MARKBOOK_ASSIGNMENT_TYPES WHERE USER_ID='".get_user('USER_ID')."' AND COURSE_ID='".$course_id."' ORDER BY TITLE"));
	}

	$sql = "INSERT INTO MARKBOOK_ASSIGNMENTS ";

	//$id = db_request(db_execute("SELECT ".db_seq_nextval('MARKBOOK_ASSIGNMENTS_SEQ').' AS ID '.FROM_DUAL));
	//$id = $id[1]['ID'];
	$fields = "ASSIGNMENT_ID,USER_ID,SCHOOL_TERM_ID,";
	$values = db_seq_nextval('MARKBOOK_ASSIGNMENTS_SEQ').",'".get_user('USER_ID')."','".get_user_school_term()."',";

	$go = false;
	$multiple = false;
    $course_sections = array();

	if(!$_REQUEST['tables']['COURSE_ID'] && $_REQUEST['tables']['TITLE'])
		$_REQUEST['tables']['COURSE_ID'] = 'N';

	if(!$_REQUEST['tables']['POINTS'])
		$_REQUEST['tables']['POINTS'] = 0;

	foreach($_REQUEST['tables'] as $column=>$value)
	{
		if($column=='DUE_DATE' || $column=='ASSIGNED_DATE')
		{
			if($value && !VerifyDate($value))
				BackPrompt(_('Some dates were entered incorrectly.'));
		}
		elseif($column=='COURSE_ID' && $value=='Y')
		{
            $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}";
            $multiple = false; //not multiple, but also uses template for single COURSE_SECTION_ID
            $course_sections []= $course_section_id;
		}

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

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

			$go = true;
		}
		// Not sure the following else block is correct or not, to be used with Users->Gradebook Grades->Add an assignment
		elseif($DBType == 'mssql' && $column == 'COURSE_SECTION_ID' && !isset($value))
		{
			$fields .= $column.',';
			$values .= "NULL,";
			$go = true;
		}
	    else
		{
			$fields .= $column.',';
			$values .= "'||";
			//$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 flag is set - collect all course periods this teacher teaches
		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'])
			    	            $course_sections []= $cpid['COURSE_SECTION_ID'];
	    	        }
	    	} //if($multiple)

	        $assignments = array();

        if(count($course_sections))
        {
            foreach($course_sections as $cpid)
            {
                db_execute(str_replace("{COURSE_SECTION_ID}",$cpid, $sql));
                $assignments [] = db_seq_currval('MARKBOOK_ASSIGNMENTS_SEQ');
            }
        }
        else
        {
            db_execute($sql);
            $assignments [] = db_seq_currval('MARKBOOK_ASSIGNMENTS_SEQ');
        }

        //adding default full credit
        if(count($assignments) && is_numeric($_REQUEST['default_full_credit']))
        {
            $points = $_REQUEST['default_full_credit'];

            if($_REQUEST['tables']['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']);

            foreach($assignments as $id)
            {
                foreach($students_array as $student)
                {
                    db_execute("INSERT INTO STUDENT_MARKBOOK_GRADES (STUDENT_ID,COURSE_SECTION_ID,ASSIGNMENT_ID,POINTS) values('".$student['STUDENT_ID']."','".$student['COURSE_SECTION_ID']."','".$id."','".$points."')");
                }
            }
        } //if(count($assignments) && is_numeric($_REQUEST['default_full_credit']))
	} //if($go)
	unset($_REQUEST['tables']);
	unset($_SESSION['_REQUEST_vars']['tables']);
	unset($_REQUEST['day_tables']);
	unset($_SESSION['_REQUEST_vars']['day_tables']);
}
$colors_array = db_request(db_execute("SELECT HCOLOR,ASSIGNMENT_TYPE_ID,TITLE FROM MARKBOOK_ASSIGNMENT_TYPES"),array(),array('ASSIGNMENT_TYPE_ID'));
$assignments_array = db_request(db_execute("SELECT ASSIGNMENT_ID,TITLE,POINTS,ASSIGNMENT_TYPE_ID,ASSIGNED_DATE,DUE_DATE,DESCRIPTION FROM MARKBOOK_ASSIGNMENTS WHERE USER_ID='".get_user('USER_ID')."' AND ((COURSE_ID='$course_id' AND USER_ID='".get_user('USER_ID')."') OR COURSE_SECTION_ID='$course_section_id') AND SCHOOL_TERM_ID='".get_user_school_term()."' ORDER BY ".Preferences('ASSIGNMENT_SORTING','Gradebook')." DESC"));

$grid_columns = array('FULL_NAME'=>_('Student Name'),'STUDENT_ID'=>_('ID number'),'CLASSLEVEL_ID'=>_('Class Level'),'GROUP_ID'=>_('Class Group'));
if(Preferences('DISPLAY_STUDENT_ID')!='Y')
	unset($grid_columns['STUDENT_ID']);
if(Preferences('DISPLAY_CLASSLEVEL')!='Y')
	unset($grid_columns['CLASSLEVEL_ID']);
if(Preferences('DISPLAY_GROUP')!='Y')
	unset($grid_columns['GROUP_ID']);

if($_REQUEST['student_id'] || $_REQUEST['assignment_id']=='student')
{
	$_SESSION['student_id'] = $_REQUEST['student_id'];
	if(Preferences('MENU')=='Side')
		echo '<script language=JavaScript>parent.side.location="'.$_SESSION['Side_PHP_SELF'].'?modcat="+parent.side.document.forms[0].modcat.value;</script>';
//	$SESSION['List_PHP_SELF'] = 'modloader.php?servicemod=mod_grades/Grades.php&assignment_id=student';

	$current_array[$_REQUEST['student_id']] = db_request(db_execute("SELECT g.ASSIGNMENT_ID,g.POINTS,g.HIGHLIGHT,g.COMMENT FROM STUDENT_MARKBOOK_GRADES g,MARKBOOK_ASSIGNMENTS a WHERE a.ASSIGNMENT_ID=g.ASSIGNMENT_ID AND a.SCHOOL_TERM_ID='".get_user_school_term()."' AND g.STUDENT_ID='".get_student_id()."' AND g.COURSE_SECTION_ID='$course_section_id'"),array(),array('ASSIGNMENT_ID'));

	$addition['functions'] = array();
	foreach($assignments_array as $assignment)
	{
//                foreach($assignment as $ke=>$va)
//                $content .= $ke."=>".$va."<br />";
		$addition['SELECT'] .= ",'' AS G$assignment[ASSIGNMENT_ID]";
		$addition['functions'] += array('G'.$assignment['ASSIGNMENT_ID']=>'_makeExtraStuCols');
                $tooltip = '<span onMouseOver=\'stm(["'._('Course details').'","'.str_replace('"','\"',str_replace("'",'&rsquo;',$content)).'"],
                                                    ["white","#'.$color_head_td[$key].'","","","",,"black","#'.Preferences('COLOR').'","","","",,'.$width.',,2,"#'.Preferences('HIGHLIGHT_FRAME').'",2,,,,,"",,,,]);\'
                                                    onMouseOut=\'htm()\'"><img src="'.
                                                    'images/info-icon.png" style="cursor:hand;width:16px;height:16px" border="0" /></span>';
                $hed['G'.$assignment['ASSIGNMENT_ID']] = array('title'=>$assignment['TITLE'].$assignment_points.$tooltip,'color_head_td'=>$colors_array[$assignment['ASSIGNMENT_TYPE_ID']][1]['HCOLOR']);
                $grid_columns += $hed;
		//$grid_columns += array('G'.$assignment['ASSIGNMENT_ID']=>$assignment['TITLE']);
		$total_points[$assignment['ASSIGNMENT_ID']] = $assignment['POINTS'];
	}
}
elseif($_REQUEST['assignment_id']=='totals')
{
	$addition['SELECT'] .= ",'' AS POINTS,'' AS LETTER_GRADE,'' AS COMMENT";
	$addition['functions'] = array('POINTS'=>'_makeExtraAssnCols','LETTER_GRADE'=>'_makeExtraAssnCols');

	foreach($types_array as $type)
	{
		$addition['functions'] += array('POINTS_'.$type['ASSIGNMENT_TYPE_ID']=>'_makeExtraAssnCols');
		$grid_columns += array('POINTS_'.$type['ASSIGNMENT_TYPE_ID']=>$type['TITLE'].' ('.($type['FINAL_GRADE_PERCENT']*100).'%)');
		$addition['SELECT'] .= ",'' AS POINTS_".$type['ASSIGNMENT_TYPE_ID'].' ';
	}

	$grid_columns += array('POINTS'=>_('Total Points'),'LETTER_GRADE'=>_('Grade'));

	if($programconfig['WEIGHT']=='Y')
		$grid_columns['LETTER_GRADE'] = _('Weighted Grade');

	$current_array = db_request(db_execute("SELECT g.STUDENT_ID,sum(".db_case(array('g.POINTS',"'-1'","'0'",'g.POINTS')).") AS POINTS,sum(".db_case(array('g.POINTS',"'-1'","'0'",'a.POINTS')).") AS TOTAL_POINTS FROM STUDENT_MARKBOOK_GRADES g,MARKBOOK_ASSIGNMENTS a WHERE a.ASSIGNMENT_ID=g.ASSIGNMENT_ID AND a.SCHOOL_TERM_ID='".get_user_school_term()."' AND g.COURSE_SECTION_ID='$course_section_id' AND (a.COURSE_SECTION_ID='$course_section_id' OR a.COURSE_ID='$course_id') AND g.POINTS IS NOT NULL GROUP BY g.STUDENT_ID"),array(),array('STUDENT_ID'));
	$current_types_array = db_request(db_execute("SELECT a.ASSIGNMENT_TYPE_ID,g.STUDENT_ID,sum(".db_case(array('g.POINTS',"'-1'","'0'",'g.POINTS')).") AS POINTS,sum(".db_case(array('g.POINTS',"'-1'","'0'",'a.POINTS')).") AS TOTAL_POINTS FROM STUDENT_MARKBOOK_GRADES g,MARKBOOK_ASSIGNMENTS a WHERE a.ASSIGNMENT_ID=g.ASSIGNMENT_ID AND g.POINTS IS NOT NULL AND a.SCHOOL_TERM_ID='".get_user_school_term()."' AND g.COURSE_SECTION_ID='$course_section_id' AND (a.COURSE_SECTION_ID='$course_section_id' OR a.COURSE_ID='$course_id') AND (a.DUE_DATE<'".get_db_date('postgres')."' OR g.POINTS IS NOT NULL) GROUP BY g.STUDENT_ID,a.ASSIGNMENT_TYPE_ID"),array(),array('STUDENT_ID','ASSIGNMENT_TYPE_ID'));

	if($programconfig['WEIGHT']=='Y')
	{
		$percent_array = db_request(db_execute("SELECT gt.ASSIGNMENT_TYPE_ID,gt.FINAL_GRADE_PERCENT,gg.STUDENT_ID,".db_case(array("sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS')).")","'0'","'0'","(sum(".db_case(array('gg.POINTS',"'-1'","'0'",'gg.POINTS')).") * gt.FINAL_GRADE_PERCENT / sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS'))."))"))." AS PARTIAL_PERCENT,sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS')).") AS TOTAL_POINTS FROM STUDENT_MARKBOOK_GRADES gg, MARKBOOK_ASSIGNMENTS ga, MARKBOOK_ASSIGNMENT_TYPES gt WHERE gt.ASSIGNMENT_TYPE_ID=ga.ASSIGNMENT_TYPE_ID AND gt.USER_ID='".get_user('USER_ID')."' AND ga.ASSIGNMENT_ID=gg.ASSIGNMENT_ID AND ga.SCHOOL_TERM_ID IN (".get_all_school_term('QTR',get_user_school_term()).") AND gg.COURSE_SECTION_ID='$course_section_id' AND gt.COURSE_ID='$course_id' AND gg.POINTS IS NOT NULL AND ((ga.COURSE_ID='".$course_id."' AND ga.USER_ID='".get_user('USER_ID')."') OR ga.COURSE_SECTION_ID='".get_user_coursesection()."') GROUP BY gg.STUDENT_ID,gt.ASSIGNMENT_TYPE_ID,gt.FINAL_GRADE_PERCENT"),array(),array('STUDENT_ID','ASSIGNMENT_TYPE_ID'));
		foreach($percent_array as $student_id=>$types)
		{
			foreach($types_array as $type)
			{
				if(!$types[$type['ASSIGNMENT_TYPE_ID']])
					$percent_array[$student_id][$type['ASSIGNMENT_TYPE_ID']][1] = array('ASSIGNMENT_TYPE_ID'=>$type['ASSIGNMENT_TYPE_ID'],'FINAL_GRADE_PERCENT'=>$type['FINAL_GRADE_PERCENT'],'STUDENT_ID'=>$student_id,'PARTIAL_PERCENT'=>0,'TOTAL_POINTS'=>0);
			}
		}
	}

	foreach($assignments_array as $assignment)
		$total_points[$assignment['ASSIGNMENT_ID']] = $assignment['POINTS'];
}
elseif($_REQUEST['assignment_id'] && substr($_REQUEST['assignment_id'],0,3)!='cat')
{
	$total_points = db_request(db_execute("SELECT POINTS FROM MARKBOOK_ASSIGNMENTS WHERE ASSIGNMENT_ID='$_REQUEST[assignment_id]'"));
	$total_points = $total_points[1]['POINTS'];
	$addition['SELECT'] .= ",'' AS POINTS,'' AS LETTER_GRADE,'' AS COMMENT";
	$addition['functions'] = array('POINTS'=>'_makeExtraAssnCols','LETTER_GRADE'=>'_makeExtraAssnCols','COMMENT'=>'_makeExtraAssnCols');
	if(Preferences('LETTER_GRADES_NOT_POINTS','Gradebook')=='Y')
		$grid_columns += array('COMMENT'=>_('Grade'));
	else
	{
		if(!empty($total_points))
			$points_block = ' ('.$total_points.')';
		else
			$points_block = ' ';
		$grid_columns += array('POINTS'=>_('Points').$points_block,'LETTER_GRADE'=>_('Grade'),'COMMENT'=>_('Comment'));
	}
	$current_array = db_request(db_execute("SELECT STUDENT_ID,POINTS,HIGHLIGHT,COMMENT,ASSIGNMENT_ID FROM STUDENT_MARKBOOK_GRADES WHERE ASSIGNMENT_ID='$_REQUEST[assignment_id]' AND COURSE_SECTION_ID='$course_section_id'"),array(),array('STUDENT_ID','ASSIGNMENT_ID'));
}
else
{
	if($_SESSION['student_id'])
	{
		unset($_SESSION['student_id']);
		if(Preferences('MENU')=='Side')
			echo '<script language=JavaScript>parent.side.location="'.$_SESSION['Side_PHP_SELF'].'?modcat="+parent.side.document.forms[0].modcat.value;</script>';
	}

	$current_array = db_request(db_execute("SELECT g.STUDENT_ID,g.ASSIGNMENT_ID,g.POINTS,g.HIGHLIGHT,g.COMMENT FROM STUDENT_MARKBOOK_GRADES g,MARKBOOK_ASSIGNMENTS a WHERE a.ASSIGNMENT_ID=g.ASSIGNMENT_ID AND a.SCHOOL_TERM_ID='".get_user_school_term()."' AND g.COURSE_SECTION_ID='$course_section_id'"),array(),array('STUDENT_ID','ASSIGNMENT_ID'));
	$count_extra = array('SELECT_ONLY'=>'ssm.STUDENT_ID');
	$count_students = get_student_list($count_extra);
	$count_students = count($count_students);

	$addition['functions'] = array();
	if(count($assignments_array))
	{
		if($_SYSTEM['direction']=='RTL')
		{
			$arrow_right = '<IMG SRC='.$_SYSTEM['uri'].'images/arrow_left.gif height=14 border=0>';
			$arrow_left = '<IMG SRC='.$_SYSTEM['uri'].'images/arrow_right.gif height=14 border=0>';
		}
		else
		{
			$arrow_right = '<IMG SRC='.$_SYSTEM['uri'].'images/arrow_right.gif height=14 border=0>';
			$arrow_left = '<IMG SRC='.$_SYSTEM['uri'].'images/arrow_left.gif height=14 border=0>';
		}

		if($_REQUEST['all_assignments']=='true')
		{
			$end = count($assignments_array);
			$all_assignments_link = '<A HREF='.SetRequestOptions('',array('all_assignments','search_servicefunction','tables','values')).'&all_assignments=false style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';"><b>'._('Show First 9 Assignments').'</b> '.$arrow_left.'</A>';
		}
		else
		{
			if(count($assignments_array)>9)
			{
				$end = 9;
				$all_assignments_link = '<A HREF='.SetRequestOptions('',array('all_assignments','search_servicefunction','tables','values')).'&all_assignments=true style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';"><b>'._('Show All Assignments').'</b> '.$arrow_right.'</A>';
			}
			else
				$end = count($assignments_array);
		}
		//foreach($assignments_array as $assignment)

		for($i=1;$i<=$end;$i++)
		{
			$assignment = $assignments_array[$i];
			if(substr($_REQUEST['assignment_id'],0,3)!='cat' || $assignment['ASSIGNMENT_TYPE_ID']==substr($_REQUEST['assignment_id'],3))
			{
				$addition['SELECT'] .= ",'' AS G$assignment[ASSIGNMENT_ID]";
				$addition['functions'] += array('G'.$assignment['ASSIGNMENT_ID']=>'_makeExtraCols');

				if(!empty($assignment['POINTS']))
					$assignment_points = ' ('.$assignment['POINTS'].')';
				else
					$assignment_points = '';
				if($assignment['DESCRIPTION'])
					$width = 450;
				else
					$width = 250;
				$content = '<TABLE>';
		                $content .= '<TR><TD align='.ALIGN_RIGHT.'><font color=#666666>'._('Assignment Title').'</font></TD><TD>'.$assignment['TITLE'].'</TD></TR>';
		                $content .= '<TR><TD align='.ALIGN_RIGHT.'><font color=#666666>'._('Assignment Category').'</font></TD><TD>'.$colors_array[$assignment['ASSIGNMENT_TYPE_ID']][1]['TITLE'].'</TD></TR>';
		                $content .= '<TR><TD align='.ALIGN_RIGHT.'><font color=#666666>'._('Max Points').'</font></TD><TD>'.$assignment['POINTS'].'</TD></TR>';
		                $content .= '<TR><TD align='.ALIGN_RIGHT.'><font color=#666666>'._('Assigned Date').'</font></TD><TD>'.$assignment['ASSIGNED_DATE'].'</TD></TR>';
		                $content .= '<TR><TD align='.ALIGN_RIGHT.'><font color=#666666>'._('Due Date').'</font></TD><TD>'.$assignment['DUE_DATE'].'</TD></TR>';
		                if($assignment['DESCRIPTION'])
	                		$content .= '<TR><TD align='.ALIGN_RIGHT.'><font color=#666666>'._('Description').'</font></TD><TD>'.$assignment['DESCRIPTION'].'</TD></TR>';
				$content .= '</TABLE>';
					
                                $tooltip = '<span onMouseOver=\'stm(["'._('Assignment details').'","'.str_replace('"','\"',str_replace("'",'&rsquo;',$content)).'"],
                                                    ["white","#'.Preferences('HIGHLIGHT').'","","","",,"black","#'.Preferences('COLOR').'","","","",,'.$width.',,2,"#'.Preferences('HIGHLIGHT_FRAME').'",2,,,,,"",,,,]);\'
                                                    onMouseOut=\'htm()\'"><img src="'.
                                                    'images/info-icon.png" style="cursor:hand;width:16px;height:16px" border="0" /></span>';
                            $hed['G'.$assignment['ASSIGNMENT_ID']] = array('title'=>$assignment['TITLE'].$assignment_points.$tooltip,'color_head_td'=>$colors_array[$assignment['ASSIGNMENT_TYPE_ID']][1]['HCOLOR']);
                            $grid_columns += $hed;
//				$grid_columns += array(=>$assignment['TITLE'].$assignment_points,
  //                                                     "color_head_td"=>$colors_array[$assignment['ASSIGNMENT_TYPE_ID']][1]['HCOLOR']
    //                             );
                                $color_array[$assignment['TITLE']] = $colors_array[$assignment['ASSIGNMENT_TYPE_ID']][1]['HCOLOR'];
				$total_points[$assignment['ASSIGNMENT_ID']] = $assignment['POINTS'];
			}
		}
	}
}
if($_REQUEST['values'] && $_POST['values'] && $_REQUEST['current_used_coursesection']==get_user_coursesection())
{
	foreach($_REQUEST['values'] as $student_id=>$assignments)
	{
		foreach($assignments as $assignment_id=>$columns)
		{
			if($columns['POINTS'])
			{
				if($columns['POINTS']=='*' || $columns['POINTS']=='Y')
					$columns['POINTS'] = '-1';
				$columns['POINTS'] = ereg_replace("[^0-9.-]",'',$columns['POINTS']);
			}
			$sql = false;
			if($current_array[$student_id][$assignment_id])
			{
                            if(AllowUse('mod_messaging/Internal_mail.php'))
                            //{
                               // $sql_upd_queue="UPDATE sms_queue SET estimate='".$columns['POINTS']."' WHERE date='".date('Y-m-d')."' AND student_id='$student_id' AND discipline='$course_title' AND item=(SELECT title FROM markbook_assignments WHERE assignment_id='$assignment_id')";
                               // db_execute($sql_upd_queue);
                           // }
                                //echo $assignment_id;
				$sql = "UPDATE STUDENT_MARKBOOK_GRADES SET ";
				foreach($columns as $column=>$value)
				{
					$sql .= $column."='".str_replace("\'","''",$value)."',";
				}
				$sql = substr($sql,0,-1) . " WHERE STUDENT_ID='$student_id' AND ASSIGNMENT_ID='$assignment_id' AND COURSE_SECTION_ID='$course_section_id'";
			}
			else
                        {
                            if(AllowUse('mod_messaging/Internal_mail.php') && Preferences('CURENT_STUDENT_SMS_FIELD'))
                            {
                                $sql_get_phone="SELECT CFIELD_".Preferences('CURENT_STUDENT_SMS_FIELD')." as phone FROM students WHERE student_id='$student_id'";
                                $row_phone=db_request(db_execute($sql_get_phone));
                                $phone=$row_phone[1]['PHONE'];
                                if($phone)
                                {
                                $sql_add_queue="INSERT INTO sms_queue(student_id,phone,date,discipline,item,estimate)
                                    VALUES('$student_id','$phone','".date('Y-m-d')."','$course_title',(SELECT title FROM markbook_assignments WHERE assignment_id='$assignment_id'),'".$columns['POINTS']."')";
                                db_execute($sql_add_queue);
                                }
                            }
                                //var_dump($_REQUEST);
                                //echo "<script>alert('".$student_id."->".$phone."');</script>";
				$sql = "INSERT INTO STUDENT_MARKBOOK_GRADES (STUDENT_ID,SCHOOL_PERIOD_ID,COURSE_SECTION_ID,ASSIGNMENT_ID,POINTS,COMMENT,HIGHLIGHT) values('$student_id','".get_user_schoolperiod()."','".$course_section_id."','".$assignment_id."','".$columns['POINTS']."','".$columns['COMMENT']."','".$columns['HIGHLIGHT']."')";
                        }

			if($sql)
				db_execute($sql);
		}
                
	}
	if($_REQUEST['student_id'])
		$current_array = db_request(db_execute("SELECT ASSIGNMENT_ID,POINTS,HIGHLIGHT,COMMENT,STUDENT_ID FROM STUDENT_MARKBOOK_GRADES WHERE STUDENT_ID='".get_student_id()."' AND COURSE_SECTION_ID='$course_section_id'"),array(),array('STUDENT_ID','ASSIGNMENT_ID'));
	elseif($_REQUEST['assignment_id'] && substr($_REQUEST['assignment_id'],0,3)!='cat')
		$current_array = db_request(db_execute("SELECT STUDENT_ID,POINTS,HIGHLIGHT,COMMENT,ASSIGNMENT_ID FROM STUDENT_MARKBOOK_GRADES WHERE ASSIGNMENT_ID='$_REQUEST[assignment_id]' AND COURSE_SECTION_ID='$course_section_id'"),array(),array('STUDENT_ID','ASSIGNMENT_ID'));
	else
		$current_array = db_request(db_execute("SELECT g.STUDENT_ID,g.ASSIGNMENT_ID,g.POINTS,g.HIGHLIGHT,g.COMMENT FROM STUDENT_MARKBOOK_GRADES g,MARKBOOK_ASSIGNMENTS a WHERE a.ASSIGNMENT_ID=g.ASSIGNMENT_ID AND a.SCHOOL_TERM_ID='".get_user_school_term()."' AND g.COURSE_SECTION_ID='$course_section_id'"),array(),array('STUDENT_ID','ASSIGNMENT_ID'));

	unset($_REQUEST['values']);
	unset($_SESSION['_REQUEST_vars']['values']);
}
elseif($_REQUEST['values'] && $_POST['values']) // check this condition, probably need to change it.
{
	unset($_REQUEST['values']);
	unseft($_SESSION['_REQUEST_vars']['values']);
}

		$school_term_extra = "AND ga.SCHOOL_TERM_ID ='".get_user_school_term()."'";

		if(Preferences('LETTER_GRADES_NOT_POINTS','Gradebook')!='Y')
		{
			if($programconfig['WEIGHT']=='Y')
				$partial_percent_select = "(sum(".db_case(array('gg.POINTS',"'-1'","'0'",'gg.POINTS')).") * gt.FINAL_GRADE_PERCENT) AS PARTIAL_PERCENT_TOP, (sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS')).")) AS PARTIAL_PERCENT_BOTTOM ";
			else
				$partial_percent_select = "(sum(".db_case(array('gg.POINTS',"'-1'","'0'",'gg.POINTS')).")) AS PARTIAL_PERCENT_TOP,(sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS')).")) AS PARTIAL_PERCENT_BOTTOM ";
			$null_extra = " AND gg.POINTS IS NOT NULL ";
		}
		else
		{
			$max_gpa_value = db_request(db_execute("SELECT max(GPA_VALUE) AS MAX FROM GRADES_CARD_SETTINGS WHERE SCALE_ID='".$grade_scale_id."'"));
			$max_gpa_value = $max_gpa_value[1]['MAX'];

			if($programconfig['WEIGHT']=='Y')
				$partial_percent_select = "(sum(".db_case(array('gg.COMMENT',"'-1'","'0'",'rcg.GPA_VALUE * ga.POINTS')).") * gt.FINAL_GRADE_PERCENT) AS PARTIAL_PERCENT_TOP, (sum(".db_case(array('gg.COMMENT',"'-1'","'0'",'ga.POINTS')).")*'".$max_gpa_value."') AS PARTIAL_PERCENT_BOTTOM ";
			else
				$partial_percent_select = "(sum(".db_case(array('gg.COMMENT',"'-1'","'0'",'rcg.GPA_VALUE*ga.POINTS')).")) AS PARTIAL_PERCENT_TOP,(sum(".db_case(array('gg.COMMENT',"'-1'","'0'",'ga.POINTS')).")*'".$max_gpa_value."') AS PARTIAL_PERCENT_BOTTOM ";
			$where_extra = " AND rcg.TITLE=gg.COMMENT AND rcg.SCALE_ID='".$grade_scale_id."'";
			$from_extra = ",GRADES_CARD_SETTINGS rcg";
			$null_extra = " AND gg.COMMENT IS NOT NULL ";
		}

		if($programconfig['WEIGHT']=='Y')
		{
			$points_array = db_request(db_execute("SELECT gt.ASSIGNMENT_TYPE_ID,gg.STUDENT_ID,gt.FINAL_GRADE_PERCENT,".$partial_percent_select."
											FROM STUDENT_MARKBOOK_GRADES gg, MARKBOOK_ASSIGNMENTS ga, MARKBOOK_ASSIGNMENT_TYPES gt, STUDENT_SCHEDULE s".$from_extra."
											WHERE s.COURSE_SECTION_ID=gg.COURSE_SECTION_ID AND s.STUDENT_ID=gg.STUDENT_ID".$where_extra."
											AND ('".get_db_date()."' BETWEEN s.START_DATE AND s.END_DATE OR (s.END_DATE IS NULL AND '".get_db_date()."'>=s.START_DATE))
											AND gt.ASSIGNMENT_TYPE_ID=ga.ASSIGNMENT_TYPE_ID AND ga.ASSIGNMENT_ID=gg.ASSIGNMENT_ID ".$school_term_extra."
											AND gg.COURSE_SECTION_ID='$course_section_id' AND gt.COURSE_ID='$course_id' AND gt.USER_ID='".get_user('USER_ID')."'
											AND (ga.COURSE_SECTION_ID='$course_section_id' OR ga.COURSE_ID='$course_id')
											".$end_date_extra.$null_extra."
											GROUP BY gg.STUDENT_ID,gt.ASSIGNMENT_TYPE_ID,gt.FINAL_GRADE_PERCENT"),array(),array('STUDENT_ID','ASSIGNMENT_TYPE_ID'));
			$totals_types_array = db_request(db_execute("SELECT ASSIGNMENT_TYPE_ID,FINAL_GRADE_PERCENT FROM MARKBOOK_ASSIGNMENT_TYPES WHERE COURSE_ID='".$course_id."' AND USER_ID='".get_user('USER_ID')."'"));
		}
		else
			$points_array = db_request(db_execute("SELECT '-1' AS ASSIGNMENT_TYPE_ID,gg.STUDENT_ID,".$partial_percent_select."
											FROM STUDENT_MARKBOOK_GRADES gg, MARKBOOK_ASSIGNMENTS ga, STUDENT_SCHEDULE s".$from_extra."
											WHERE gg.COURSE_SECTION_ID=s.COURSE_SECTION_ID AND gg.STUDENT_ID=s.STUDENT_ID".$where_extra."
											AND ('".get_db_date()."' BETWEEN s.START_DATE AND s.END_DATE OR (s.END_DATE IS NULL AND '".get_db_date()."'>=s.START_DATE))
											AND ga.ASSIGNMENT_ID=gg.ASSIGNMENT_ID ".$school_term_extra."
											AND gg.COURSE_SECTION_ID='$course_section_id' AND (ga.COURSE_SECTION_ID='$course_section_id' OR ga.COURSE_ID='$course_id')
											".$end_date_extra.$null_extra."
											GROUP BY gg.STUDENT_ID"),array(),array('STUDENT_ID','ASSIGNMENT_TYPE_ID'));
//		var_dump($points_array);
		if(count($points_array))
		{
			foreach($points_array as $student_id=>$types)
			{
				$total = 0;
//				var_dump($types);
				foreach($types as $type_id=>$type)
				{
					if($type[1]['PARTIAL_PERCENT_BOTTOM'])
						$total += ($type[1]['PARTIAL_PERCENT_TOP'] / $type[1]['PARTIAL_PERCENT_BOTTOM']);
				}
//				echo $total;
				if($programconfig['WEIGHT']=='Y')
				{
//				echo "vvvv";
					$empty_type_adjustment_divisor = 0;
					foreach($totals_types_array as $type)
					{
//					echo "<br>ccc";
						if(!$types[$type['ASSIGNMENT_TYPE_ID']] || $types[$type['ASSIGNMENT_TYPE_ID']][1]['PARTIAL_PERCENT_BOTTOM']==0)
							$empty_type_adjustment_divisor += $type['FINAL_GRADE_PERCENT'];
//					echo  $type['FINAL_GRADE_PERCENT'];
					}
					if($empty_type_adjustment_divisor)
						$total /= (1-$empty_type_adjustment_divisor);
				}
//				echo "--".$total;
//				echo ceil($total*100)."<br>";
//				echo count($points_array);
				if($programconfig['ROUNDING']=='UP')
					$total_column_percent[$student_id] = ceil($total*100);
				elseif($programconfig['ROUNDING']=='DOWN')
					$total_column_percent[$student_id] = floor($total*100);
				else
					$total_column_percent[$student_id] = round($total*100,0);
			}
		}

if(!$_REQUEST['assignment_id'])
	unset($_SESSION['assignment_id']);
else
	$_SESSION['assignment_id'] = $_REQUEST['assignment_id'];

$assignment_select = '<SELECT name=assignment_id onchange="document.location.href=\''.SetRequestOptions(null,array('assignment_id','search_servicefunction','student_id','stuid','values','tables')).'&amp;assignment_id=\'+this.options[selectedIndex].value" ignorered="ignorered"><OPTION value="">'._('All Assignments').'</OPTION>';

if(Preferences('LETTER_GRADES_NOT_POINTS','Gradebook')!='Y')
	$assignment_select .= '<OPTION value="totals"'.($_REQUEST['assignment_id']=='totals'?' SELECTED':'').'>'._('Totals').'</OPTION>';

if($_REQUEST['student_id'])
	$assignment_select .= '<OPTION value=student SELECTED>'._('Student').'</OPTION>';

if(Preferences('LETTER_GRADES_NOT_POINTS','Gradebook')!='Y')
{
	if(count($types_array))
	{
		$assignment_select .= '<OPTGROUP label="'._('Categories').'">';
		foreach($types_array as $type)
		{
			$assignment_select .= '<OPTION value=cat'.$type['ASSIGNMENT_TYPE_ID'].(($_REQUEST['assignment_id']==('cat'.$type['ASSIGNMENT_TYPE_ID']))?' SELECTED':'').'>'.$type['TITLE'].'</OPTION>';
			if($_REQUEST['assignment_id']==('cat'.$type['ASSIGNMENT_TYPE_ID']))
				$title = $type['TITLE'];
		}
		$assignment_select .= '</OPTGROUP>';
	}
}
/*
if(count($benchmarks_array))
{
	foreach($benchmarks_array as $type)
	{
		$assignment_select .= '<OPTION value=b'.$type['ID'].(($_REQUEST['assignment_id']==('b'.$type['ID']))?' SELECTED':'').'>'._('Benchmark: ').$type['TITLE'].'</OPTION>';
		if($_REQUEST['assignment_id']==('b'.$type['ID']))
			$title = $type['TITLE'];
	}
	$assignment_select .= '<OPTION value="">---</OPTION>';
}
*/
if(count($assignments_array))
{
	$assignment_select .= '<OPTGROUP label="'._('Assignments').'">';
	foreach($assignments_array as $assignment)
		$assignment_select .= '<OPTION value='.$assignment['ASSIGNMENT_ID'].(($_REQUEST['assignment_id']==$assignment['ASSIGNMENT_ID'])?' SELECTED':'').'>'.$assignment['TITLE'].'</OPTION>';
	$assignment_select .= '</OPTGROUP>';
}
$assignment_select .= '</SELECT>';
//if($_REQUEST['servicemod'])
	$header .= '<TD width=10></TD><TD><A HREF=javascript:switchMenu("add_div",false);doOnresize(); style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'._('Add an Assignment').'</A></TD>';

/*
$programs = array('mod_grades/GrdBookAssignments.php'=>_('Modify Assignments'),'mod_grades/GrdBookConfiguration.php'=>_('Gradebook Configuration'));
foreach($programs as $servicemod=>$title)
{

	if(AllowUse($servicemod))
	{
		$header .= '<TD width=10></TD><TD><A HREF=modloader.php?servicemod='.$servicemod.' style="text-decoration:none;font-weight:bold;color:#666666;" onmouseover="this.style.color=\'#000000\';" onmouseout="this.style.color=\'#666666\';">'.$title.'</A></TD>';
	}
}
*/
//if($all_assignments_link)
//	$header .= '<TD width=10></TD><TD>'.$all_assignments_link.'</TD>';
		$_SYSTEM['_makeLetterGrade']['grades'] = db_request(db_execute("SELECT TITLE,ID,DEFAULT_BREAKOFF FROM GRADES_CARD_SETTINGS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' AND SCALE_ID='".$grade_scale_id."' ORDER BY SORT_ORDER"));
//var_dump($_SYSTEM['_makeLetterGrade']['grades']);
if(!$_REQUEST['CREATEPDF'])
{
	echo '<SCRIPT language=javascript>';
	echo 'id_comments_box = false;

	assignment_points = new Array;';

	foreach($assignments_array as $assignment)
	{
		echo "assignment_points[".$assignment['ASSIGNMENT_ID']."] = '".$assignment['POINTS']."';";
	}

	if(!$_SYSTEM['_makeLetterGrade']['grades'])
		$_SYSTEM['_makeLetterGrade']['grades'] = db_request(db_execute("SELECT TITLE,ID,DEFAULT_BREAKOFF FROM GRADES_CARD_SETTINGS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' AND SCALE_ID='".$grade_scale_id."' ORDER BY SORT_ORDER"));

	foreach($_SYSTEM['_makeLetterGrade']['grades'] as $grade)
	{
		if($programconfig[$course_section_id.'-'.$grade['ID']])
		{
			$custom = true;
			break;
		}
	}

	if(!$custom || SystemPreferences("OVERRIDE_SCORE_BREAKOFFS")!="Y")
	{
		foreach($_SYSTEM['_makeLetterGrade']['grades'] as $grade)
			$programconfig[$course_section_id.'-'.$grade['ID']] = $grade['DEFAULT_BREAKOFF'];
	}

	echo "grade_values = new Array;
		grade_titles = new Array;";
	$i = 0;
	foreach($_SYSTEM['_makeLetterGrade']['grades'] as $grade)
	{
		if(is_numeric($programconfig[$course_section_id.'-'.$grade['ID']]))
		{
			echo "grade_values[".$i."] = ".$programconfig[$course_section_id.'-'.$grade['ID']].";";
			echo "grade_titles[".$i."] = \"".$grade['TITLE']."\";";
			$i++;
		}
	}

	echo '
	red = new Array;
	';
	if($programconfig['PERCENT_MODE']=='Y')
		echo 'percent_mode = true;';
	else
		echo 'percent_mode = false;';
	echo '
	function doOnPointsChange(id,assignment_id)
	{
		var letter_grade;
		var points = document.getElementById(id).value;

		var symbol_pos = points.indexOf("%");
		if(symbol_pos!=-1)
		{
			percent_mode = true;
			//document.getElementById("percent_mode_div").style.display = "block";

			points = points.substring(0,symbol_pos);
		}

		if(percent_mode==true && points && points!="*")
		{
			points = points * assignment_points[assignment_id] / 100;
			document.getElementById(id).value = points;
		}

		if(points=="*")
			letter_grade = "'._("Dld.").'";
		else if(points=="")
			letter_grade = "'._("UG").'";
		else if(assignment_points[assignment_id]=="0" || assignment_points[assignment_id]=="")
			letter_grade = "'._("EC").'";
		else
		{
			percent = Math.round(points*100/assignment_points[assignment_id]);
//			alert(points+"-"+percent);
			for(i=0;i<grade_values.length;i++)
			{
				if(percent>=grade_values[i])
				{
					';
					if(Preferences('DISPLAY_GRADEBOOK_PERCENTAGES','Gradebook')=='Y')
					{
						echo 'if(assignment_points[assignment_id]!=100 && assignment_points[assignment_id]!=10)
							percent_extra = percent+"%&nbsp;";
							else
								percent_extra = "";';
					}
					else
						echo 'percent_extra = "";';
					echo '
					letter_grade = percent_extra+grade_titles[i];
					break;
				}
			}
		}

		if(points>0 && points>assignment_points[assignment_id]*2)
		{
			document.getElementById(id).parentNode.parentNode.nextSibling.nextSibling.style.color="#FF0000";
			document.getElementById(id).parentNode.parentNode.nextSibling.nextSibling.style.fontWeight="bold";
			document.getElementById(id).style.borderSize="2px";
			document.getElementById(id).style.borderColor="#FF0000";
			if(highlighted[id])
				red[id] = "highlighted";
			else
				red[id] = true;

		}
		else if(red[id]==true)
		{
			document.getElementById(id).parentNode.parentNode.nextSibling.nextSibling.style.color="#000000";
			document.getElementById(id).parentNode.parentNode.nextSibling.nextSibling.style.fontWeight="normal";
			document.getElementById(id).style.borderSize="";
			document.getElementById(id).style.borderColor="";
		}
		else if(red[id]=="highlighted")
		{
			document.getElementById(id).parentNode.parentNode.nextSibling.nextSibling.style.color="#'.Preferences('HIGHLIGHT').'";
			document.getElementById(id).parentNode.parentNode.nextSibling.nextSibling.style.fontWeight="bold";
			document.getElementById(id).style.borderColor="#'.Preferences('HIGHLIGHT').'";
			document.getElementById(id).style.borderSize="2px";
		}
		document.getElementById(id).parentNode.parentNode.nextSibling.nextSibling.innerHTML = letter_grade;
		doOnload();
	}';

	if(Preferences('LETTER_GRADES_NOT_POINTS','Gradebook')=='Y')
	{
		echo '
		function validateLetterGrade(id)
		{
			var value = document.getElementById(id).value;
			if(value=="" || value=="*")
				return;
			var matched = false;
			for(i=0;i<grade_titles.length;i++)
			{
				if(grade_titles[i].toUpperCase()==value.toUpperCase())
				{
					matched = true;
					if(grade_titles[i]!=value)
						document.getElementById(id).value = grade_titles[i];
					break;
				}
			}

			if(!matched)
			{
				document.getElementById(id).style.borderSize="2px";
				document.getElementById(id).style.borderColor="#FF0000";
				document.getElementById(id).value = "";
				red[id] = true;
			}
			else if(red[id]==true)
			{
				document.getElementById(id).style.borderSize="";
				document.getElementById(id).style.borderColor="";
			}
		}
		';
	}

	echo 'comments = new Array;
	highlighted = new Array;
';
	foreach($current_array as $student_id=>$assignments)
	{
		foreach($assignments as $assignment_id=>$assignment)
		{
			if($assignment[1]['COMMENT'])
				echo "comments['inputvalues[".$student_id."][".$assignment_id."][POINTS]'] = '".str_replace("'","\'",$assignment[1]['COMMENT'])."';";
			if($assignment[1]['HIGHLIGHT']=='Y')
				echo "highlighted['inputvalues[".$student_id."][".$assignment_id."][POINTS]'] = true;";
		}
	}

	echo '
		function nextInput(e,form,tabindexdown,tabindexup)
		{
			var key;
			var count_elements = form.length;
			var next_field = 0;

			if(e && e.which)
				key = e.which;
			else if(window.event) // ie
				key = window.event.keyCode;

			if(key==13 || key==40)
			{
				while (tabindexdown<count_all_elements)
				{
					for(i=0;i<count_elements;i++)
					{
						if(form[i].tabIndex == tabindexdown)
						{
							next_field = i;
							form[next_field].focus();
							break;
						}
					}
				if(next_field==0)
					tabindexdown++;
				else
					break;
				}
				return false;
			}
			else if(key==38)
			{
                while (tabindexup>0)
				{
					for(i=0;i<count_elements;i++)
					{
						if(form[i].tabIndex == tabindexup)
						{
							next_field = i;
							form[next_field].focus();
							break;
						}
					}
					if(next_field==0)
						tabindexup--;
					else
						break;
				}
				return false;
			}
			else if(key==33)
			{
				openCommentsBox(form,tabindex);
				return false;
			}
		}

		function openCommentsBox(form,tabindex)
		{
			var count_elements;
			count_elements = form.length;
			for(i=0;i<count_elements;i++)
			{
				if(form[i].tabIndex == (tabindex-1))
				{
					if(id_comments_box)
					{
						if((!document.getElementById(id_comments_box.replace("[POINTS]","[HIGHLIGHT]")) || document.getElementById(id_comments_box.replace("[POINTS]","[HIGHLIGHT]")).value!="Y") && !highlighted[id_comments_box])
						{
							document.getElementById(id_comments_box).style.borderColor="";
							document.getElementById(id_comments_box).style.borderSize="";
						}
					}
					id_comments_box = form[i].id;

					document.getElementById("comment_add_div").style.top=getYPos(id_comments_box)-7;
					document.getElementById("comment_add_div").style.left=getXPos(id_comments_box)+25;
					document.getElementById("comment_add_div").style.display="block";
					if(red[id_comments_box]!==true)
					{
						document.getElementById(id_comments_box).style.borderColor="#'.Preferences('HIGHLIGHT').'";
						document.getElementById(id_comments_box).style.borderSize="2px";
					}

					existing_value = document.getElementById(id_comments_box).value.replace("!","");
					if(existing_value)
					{
						document.getElementById("comment_add_points_input").value=existing_value;
						document.getElementById("comment_add_points_input").focus();
						document.getElementById("comment_add_points_input").select();
					}
					else
					{
						document.getElementById("comment_add_points_input").value="";
						document.getElementById("comment_add_points_input").focus();
					}

					if(document.getElementById(id_comments_box.replace("[POINTS]","[COMMENT]")))
						document.getElementById("comment_add_comment_input").value=document.getElementById(id_comments_box.replace("[POINTS]","[COMMENT]")).value;
					else if(comments[id_comments_box])
						document.getElementById("comment_add_comment_input").value=comments[id_comments_box];
					else
						document.getElementById("comment_add_comment_input").value="";

					if(document.getElementById(id_comments_box.replace("[POINTS]","[HIGHLIGHT]")) && document.getElementById(id_comments_box.replace("[POINTS]","[HIGHLIGHT]")).value=="Y")
						document.getElementById("comment_add_highlight_input").checked = true;
					else if(highlighted[id_comments_box])
						document.getElementById("comment_add_highlight_input").checked = true;
					else
						document.getElementById("comment_add_highlight_input").checked = false;

					break;
				}
			}
		}

		function commentsNextInput(e)
		{
			var key;

			if(e && e.which)
				key = e.which;
			else if(window.event) // ie
				key = window.event.keyCode;

			if(key==13)
			{
				saveComments();
				return false;
			}
		}

		function cancelComments()
		{
			if(document.getElementById("comment_add_div").style.display!="none")
			{
				document.getElementById("comment_add_div").style.display="none";
				if(!highlighted[id_comments_box] && red[id_comments_box]!==true)
				{
					document.getElementById(id_comments_box).style.borderColor="";
					document.getElementById(id_comments_box).style.borderSize="";
				}
			}
		}

		function saveComments()
		{
			var existing_element;
			var new_comment = document.getElementById(\'comment_add_comment_input\').value;

			document.getElementById(id_comments_box).value = document.getElementById("comment_add_points_input").value;

			if(existing_element = document.getElementById(id_comments_box.replace("[POINTS]","[COMMENT]")))
				existing_element.value = document.getElementById("comment_add_comment_input").value.replace("\'","&rsquo;");
			else
				document.getElementById("hidden_comments_div").innerHTML = document.getElementById("hidden_comments_div").innerHTML + "<INPUT type=hidden name=\'"+id_comments_box.replace("input","").replace("[POINTS]","[COMMENT]")+"\' id=\'"+id_comments_box.replace("[POINTS]","[COMMENT]")+"\' value=\'"+document.getElementById("comment_add_comment_input").value.replace("\'","&rsquo;")+"\'>";

//alert(document.getElementById(id_comments_box.replace("[POINTS]","[COMMENT_MOUSEOVER]")));
			if(new_comment.length>0)
			{
//				alert("1");
//				document.getElementById(id_comments_box.replace("[POINTS]","[COMMENT_MOUSEOVER]")).onmouseover = function() { stm(["",new_comment],["white","#'.Preferences('HIGHLIGHT').'","","","",,"black","#'.Preferences('COLOR').'","","","",,100,,2,"#'.Preferences('HIGHLIGHT').'",2,,,,,"",,,,]); }
//				alert("2");
			}
			else
			{
//				alert("3");
//				document.getElementById(id_comments_box.replace("[POINTS]","[COMMENT_MOUSEOVER]")).onmouseover = null;
//				alert("4");
			}

			if(document.getElementById("comment_add_highlight_input").checked)
			{
				if(existing_element = document.getElementById(id_comments_box.replace("input","").replace("[POINTS]","[HIGHLIGHT]")))
					existing_element.value = "Y";
				else
					document.getElementById("hidden_comments_div").innerHTML = document.getElementById("hidden_comments_div").innerHTML + "<INPUT type=hidden name=\'"+id_comments_box.replace("input","").replace("[POINTS]","[HIGHLIGHT]")+"\' id=\'"+id_comments_box.replace("[POINTS]","[HIGHLIGHT]")+"\' value=Y>";
				document.getElementById(id_comments_box).parentNode.parentNode.nextSibling.nextSibling.style.color="#'.Preferences('HIGHLIGHT').'";
				document.getElementById(id_comments_box).parentNode.parentNode.nextSibling.nextSibling.style.fontWeight="bold";
				if(red[id_comments_box]!==true)
				{
					document.getElementById(id_comments_box).style.borderColor="#'.Preferences('HIGHLIGHT').'";
					document.getElementById(id_comments_box).style.borderSize="2px";
				}
				highlighted[id_comments_box] = true;
			}
			else
			{
				document.getElementById(id_comments_box).parentNode.parentNode.nextSibling.nextSibling.style.color="#000000";
				document.getElementById(id_comments_box).parentNode.parentNode.nextSibling.nextSibling.style.fontWeight="normal";
				if(existing_element = document.getElementById(id_comments_box.replace("[POINTS]","[HIGHLIGHT]")))
					existing_element.value = "N";
				else
					document.getElementById("hidden_comments_div").innerHTML = document.getElementById("hidden_comments_div").innerHTML + "<INPUT type=hidden name=\'"+id_comments_box.replace("input","").replace("[POINTS]","[HIGHLIGHT]")+"\' id=\'"+id_comments_box.replace("[POINTS]","[HIGHLIGHT]")+"\' value=N>";
				if(red[id_comments_box]!==true)
				{
					document.getElementById(id_comments_box).style.borderColor="";
					document.getElementById(id_comments_box).style.borderSize="";
				}
				highlighted[id_comments_box] = false;
			}
			document.getElementById("comment_add_div").style.display="none";
		}

		';
		echo '</SCRIPT>';
}

if($_REQUEST['servicemod'])
	DisplayHeader(".:".ProgramTitle().":.");
echo "<FORM action=".SetRequestOptions(null,array('tables','search_servicefunction','values','tables'))."&current_used_coursesection=".get_user_coursesection()." id=red_button_form method=POST>";
$_REQUEST['DrawAlign'] = 'LEFT';
if(!$_REQUEST['CREATEPDF'])
	DisplayHeader('<TABLE border=0 cellpadding=0 cellspacing=0 height=14 style="display:inline;"><TR><TD>'.$assignment_select.'</TD><TD>'.$header.'</TR></TABLE>',$all_assignments_link.' &nbsp; &nbsp; <INPUT style="width:100px;" type=submit id=top_submit onclick="rb_submit=true;" value='._('Save').' accesskey="S">',null,null,null,null,array(''));
unset($_REQUEST['DrawAlign']);
//if(!$_REQUEST['CREATEPDF'])
//	echo TabsHeader($header);

$array = array();
if(!$_REQUEST['CREATEPDF'])
{
	$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"));
	echo "<DIV id=add_div style=\"display:none;width:100%;\">";

	if(count($benchmarks_array))
		$style_width = 'style="width:1250px;"';
	else
		$style_width = 'style="width:1024px;"';
	echo '<TABLE width=100% ><TR><TD '.$style_width.'>';
	echo '<TABLE width=100%  cellpadding=0><TR>';

        echo '<TD colspan=4 align=center height=35 valign=top>' . CheckboxInput($array['COURSE_ID'],'tables[COURSE_ID]',sprintf(_('Add this assignment to all sections of %s that I teach'),$course_title),'',true) . '</TD></TR><TR>';

	echo '<TD>'.TextInput($array['TITLE'],'tables[TITLE]',_('Assignment Title')) . '</TD>';
	echo '<TD>'.TextInput($array['POINTS'],'tables[POINTS]',_('Points Equal Highest Grade'),' size=4 maxlength=4').'</TD>';
	if(Preferences('APPLY_ALL_DEFAULT','Gradebook')=='Y')
		$array['COURSE_ID'] = 'Y';
//1    echo '<TD>' . CheckboxInput($array['COURSE_ID'],'tables[COURSE_ID]',sprintf(_('Add this assignment to all sections of  %s that I teach'),$course_title),'',true) . '</TD>';
	//echo '<TD>' . CheckboxInput('','default_full_credit',_('Give all Students Full Credit'),'',true) . '</TD>';
    $dfc_title = _('Auto-Fill Points');
    echo '<TD>'.TextInput('','default_full_credit',$dfc_title,'',true).'</TD>';
	foreach($types_array as $type)
		$assignment_type_options[$type['ASSIGNMENT_TYPE_ID']] = $type['TITLE'];

	echo '<TD>' . SelectInput($array['ASSIGNMENT_TYPE_ID']?$array['ASSIGNMENT_TYPE_ID']:$_REQUEST['assignment_type_id'],'tables[ASSIGNMENT_TYPE_ID]',_('Assignment Category'),$assignment_type_options,false) . '</TD>';
	echo '</TR><TR><TD colspan=5><HR></TD></TR><TR>';

	if(Preferences('DEFAULT_DUE_DATE','Gradebook')=='tomorrow')
		$default_due_date = get_db_date('postgres',(time()+86400));
	else
		$default_due_date = get_db_date('postgres');


	echo '<TD valign=middle  colspan=2 align=center><Table><TR><TD>'._('Assigned Date').'</TD><TD>'.DateInput(get_db_date(),'tables[ASSIGNED_DATE]','',false).'</TD></TR>';
//	if(!count($benchmarks_array))
//		echo '</Table></TD>';
//	else
		echo '<TR>';
	echo '<TD>'._('Expiring Date').'</Td><Td>' .DateInput($default_due_date,'tables[DUE_DATE]','',false) . '</TD><TR></TABLE></TD>';
	echo '<TD valign=middle align=center>' . TextareaInput($array['DESCRIPTION'],'tables[DESCRIPTION]') . '<BR>'._('Description').'</TD>';
	if(count($benchmarks_array))
	{
		$options = array();
		foreach($benchmarks_array as $benchmark)
			$options[$benchmark['ID']] = $benchmark['TITLE'];
		echo '<TD colspan=2 align=center>' . SelectMultipleInput($array['BENCHMARKS'],'tables[BENCHMARKS]',_('Benchmarks'),$options,null,null,$div,3).'</TD>';
	}
	echo '</TR>';

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

	echo '</DIV>';
	//окошко о специальной отметке.
	echo '<DIV id=comment_add_div style="position:absolute;display:none;"><TABLE cellpadding=0 cellspacing=0><TR><TD valign=top><IMG SRC='.$_SYSTEM['uri'].'images/arrow_left.gif style="padding-top:10px;" border=0 align=bottom></TD><TD valign=top>';
	$content = '<TABLE style="background-color:#'.Preferences('HIGHLIGHT').';border:2px solid #CCCCCC;">';
	$content .= '<TR><TD align=right style="color:white;">'._('Points').'</TD><TD><INPUT type=text id=comment_add_points_input onkeypress="return commentsNextInput(event);" name=points size=4 maxlength=4 tabindex=1000></TD></TR>';
	$content .= '<TR><TD align=right style="color:white;">'._('Specified').'</TD><TD><INPUT type=checkbox id=comment_add_highlight_input name=highlight></TD></TR>';
	$content .= '<TR><TD align=right style="color:white;">'._('Comments').'</TD><TD><INPUT type=text id=comment_add_comment_input onkeypress="return commentsNextInput(event);" name=comment size=20 maxlength=100 tabindex=1001></TD></TR>';
	$content .= '<TR><TD colspan=2 align=center><INPUT style="width:100px;" type=button value="'._('OK').'" onclick="saveComments();"> &nbsp; &nbsp; <INPUT type=button value="'._('Cancel').'" onclick="cancelComments();"></TD></TR>';
	$content .= '</TABLE>';
	echo $content;
	echo '</TD></TR></TABLE>';
	echo '</DIV>';

	echo '<DIV id=hidden_comments_div> </DIV>';
}
if(!$_REQUEST['student_id'])
{
	if(!$_REQUEST['student_id'] && $_REQUEST['assignment_id']!='totals')
		$addition['functions']['FULL_NAME'] = '_makeName';
	$stu_array = get_student_list($addition);
//        var_dump($stu_array);
//        die();
        //,'row_color'=>$assignment['HCOLOR']
	if(!$_REQUEST['student_id'])
	{
		/*
		if($_REQUEST['servicemod'])
			$link['FULL_NAME']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&assignment_id=student";
		else
			$link['FULL_NAME']['link'] = "index.php?id=".$_REQUEST['id']."&assignment_id=student";

		$link['FULL_NAME']['variables'] = array('student_id'=>'STUDENT_ID');
		*/
	}
	if(!$_REQUEST['student_id'] && !$_REQUEST['assignment_id'])
		$options = array('yscroll'=>true,'cellpadding'=>1,'split_pages'=>true);
	echo "".'<SCRIPT language=javascript>count_all_elements = '.(count($stu_array)*(count($grid_columns)-1)+1).';</SCRIPT>';
	foreach($addition['functions'] as $col=>$name)
		$link['add']['html'][$col] = _makeAverage($col);
	$link['add']['html']['FULL_NAME']='<b>'._('Average Value').'</b>';
	Gridoutput($stu_array,$grid_columns,_('Students'),_('Amount of Students'),$link,array(),$options);
}
else
{
	$_REQUEST['course_section_id'] = get_user_coursesection();
	include($staticpath.'/modules/mod_grades/GrdBook.php');
}
echo '<CENTER><INPUT type=submit id=bottom_submit style="width:100;" onclick="rb_submit=true;" value='._('Save').'></CENTER>';
//if(!$_REQUEST['student_id'])
//	echo '<script language=javascript>document.getElementById("GridScaley_layer").innerHTML += \'<INPUT style="width:100px;" type=submit style=\"width:300;\" value='._('Save').'>\'</script>';
//	echo '<script language=javascript>document.getElementById("GridScaley_layer").innerHTML += \'<INPUT style="width:100px;" type=submit style="width:300;" value='._('Save').'>\'</script>';
//	echo '<INPUT style="width:100px;" type=submit style="width:300;" value='._('Save').'>';
//echo '<IMG SRC=images/pixel_trans.gif width=160 height=1><INPUT type=submit value='._('Save').'>';
echo '</FORM>';
// so that teachers will be able to scroll down further ... this way the column headings will float closer to the current student.
echo '<BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>';

function _makeAverage($col)
{	global $_SYSTEM,$total_points;

	if($total_points[substr($col,1)] && $_SYSTEM['avg_total_included'][$col])
		return Percent($_SYSTEM['avg_total_points'][$col] / $total_points[substr($col,1)] / $_SYSTEM['avg_total_included'][$col]);
}

function _makeExtraAssnCols($value,$column)
{	global $THIS_array,$total_points,$current_array,$current_types_array,$percent_array,$programconfig,$tabindex;

	switch($column)
	{
		case 'LETTER_GRADE':
			if($_REQUEST['assignment_id']=='totals' && !$_REQUEST['student_id'])
			{
				if($programconfig['WEIGHT']=='Y' && count($percent_array[$THIS_array['STUDENT_ID']]))
				{
					$total = 0;
					$empty_type_adjustment_divisor = 1;
					foreach($percent_array[$THIS_array['STUDENT_ID']] as $type_id=>$type)
					{
						$total += $type[1]['PARTIAL_PERCENT'];
						if($type[1]['TOTAL_POINTS']==0)
							$empty_type_adjustment_divisor -= $type[1]['FINAL_GRADE_PERCENT'];
					}
					if($empty_type_adjustment_divisor!=1)
						$total /= $empty_type_adjustment_divisor;
				}
				elseif($current_array[$THIS_array['STUDENT_ID']][1]['TOTAL_POINTS'])
					$total = $current_array[$THIS_array['STUDENT_ID']][1]['POINTS'] / $current_array[$THIS_array['STUDENT_ID']][1]['TOTAL_POINTS'];
				else
					$total = 0;

				$percent = $total;

				if($programconfig['ROUNDING']!='UP' && $programconfig['ROUNDING']!='DOWN')
					$display_percent = round(($percent*100),2); // in case the percentage is 79.46 --> 79.5 could be interpreted as 80, so we must display at least 2 decimal points
				else
					$display_percent = false;

				if($programconfig['ROUNDING']=='UP')
					$percent = ceil($percent*100);
				elseif($programconfig['ROUNDING']=='DOWN')
					$percent = floor($percent*100);
				else
					$percent = round($percent*100);

				if($display_percent === false)
					$display_percent = $percent;

				return Percent(($display_percent/100),2).'&nbsp;'._makeLetterGrade(($percent/100),get_user_coursesection());
			}
			else
			{
				if($total_points=='0')
					return '<!-- 2 -->'._('NP');
				if($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']!='*')
					return '<!-- '.($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']/$total_points).' -->'.Percent($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']/$total_points,0) .'&nbsp;'. _makeLetterGrade($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']/$total_points,get_user_coursesection());
//					return Percent($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']/$total_points,0) .'&nbsp;'. _makeLetterGrade($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']/$total_points,get_user_coursesection());
				else
					return '<!-- 3 -->'._('N/A').'&nbsp;'._('N/A');
//					return _('N/A').'&nbsp;'._('N/A');
			}
		break;

		case 'COMMENT':
			if(Preferences('LETTER_GRADES_NOT_POINTS','Gradebook')=='Y')
			{
				$tabindex++;
				$addition = ' onchange="validateLetterGrade(this.id);" maxlength=100 size=5 tabindex='.($tabindex);
			}
			else
				$addition = ' maxlength=100 size=30 tabindex='.(500+$tabindex);
			return TextInput($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['COMMENT'],'values['.$THIS_array['STUDENT_ID'].']['.$_REQUEST['assignment_id'].'][COMMENT]','',$addition);
		break;

		case 'POINTS':
		default:
			if($column!='POINTS')
				$assignment_type_id = substr($column,7);

			$tabindex++;
			if($_REQUEST['assignment_id']=='totals' && !$_REQUEST['student_id'] && $column=='POINTS')
				$total_points = $current_array[$THIS_array['STUDENT_ID']][1]['TOTAL_POINTS'];
			elseif($_REQUEST['assignment_id']=='totals' && !$_REQUEST['student_id'])
				$total_points = $current_types_array[$THIS_array['STUDENT_ID']][$assignment_type_id][1]['TOTAL_POINTS'];

			if($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']==-1)
				$current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'] = '*';

			if($_REQUEST['assignment_id']!='totals')
			{
				$val = ereg_replace('\.$','',(ereg_replace('\.$','',((strpos($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'],'.')===false)?$current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']:rtrim($current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'],'0')))));
				if(!$THIS_array['STUDENT_ID'] || !$val)
					$size = ' size=2';
				return '<!-- '.$current_array[$THIS_array['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS'].' -->'.TextInput($val,'values['.$THIS_array['STUDENT_ID'].']['.$_REQUEST['assignment_id'].'][POINTS]','',$size.' maxlength=7 tabindex='.$tabindex.' ondblclick="return openCommentsBox(this.form,'.($tabindex+1).');" onkeydown="return nextInput(event,this.form,'.($tabindex+1).','.($tabindex-1).');"');
				//return ''.TextInput($val,'values['.$THIS_array['STUDENT_ID'].']['.$_REQUEST['assignment_id'].'][POINTS]','',$size.' maxlength=7 tabindex='.$tabindex.' ondblclick="return openCommentsBox(this.form,'.($tabindex+1).');" onkeydown="return nextInput(event,this.form,'.($tabindex+1).','.($tabindex-1).');"');
			}
			else
			{
				if($column=='POINTS')
					$points = $current_array[$THIS_array['STUDENT_ID']][1]['POINTS'];
				else
					$points = $current_types_array[$THIS_array['STUDENT_ID']][$assignment_type_id][1]['POINTS'];

				if(!$total_points)
					return '<!-- '.$points.' --><TABLE border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD>'.(ereg_replace('\.$','',((strpos($points,'.')===false)?$points:rtrim($points,'0')))*1).'</TD><TD> / </TD><TD>0</TD><TD> &nbsp; &nbsp;</TD></TR></TABLE>';
					//return '<TABLE border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD>'.(ereg_replace('\.$','',((strpos($points,'.')===false)?$points:rtrim($points,'0')))*1).'</TD><TD> / </TD><TD>0</TD><TD> &nbsp; &nbsp;</TD></TR></TABLE>';
				else
					return '<TABLE border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD>'.(ereg_replace('\.$','',((strpos($points,'.')===false)?$points:rtrim($points,'0')))*1).'</TD><TD> / </TD><TD>'.$total_points.'</TD><TD> &nbsp; '.Percent($points/$total_points,0) .'&nbsp;'. _makeLetterGrade(($points/$total_points),get_user_coursesection()).'</TD></TR></TABLE>';
			}
		break;
	}

}

/*
function _makeExtraStuCols($value,$column)
{	global $THIS_array,$total_points,$current_array;

	$assignment_id = substr($column,1);
	if($current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS']=='-1')
		$current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS'] = '*';

	$current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS'] = ereg_replace('\.$','',((strpos($current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS'],'.')!==false)?rtrim($current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS'],'0'):$current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS']));

	// IF THE NAME OF THE TEXT FIELDS EVER CHANGES, GrdBook.php will also have to be changed to reflect this.  Current value: 'values['.$_REQUEST['student_id'].']['.$assignment_id.'][POINTS]'
	if($current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS']!='*')
		return '<TABLE border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD>'.TextInput($current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS'],'values['.$_REQUEST['student_id'].']['.$assignment_id.'][POINTS]','',' size=2 maxlength=7').'</TD><TD> / </TD><TD>'.$total_points[$assignment_id].'</TD><TD>&nbsp;'.Percent($current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS']/$total_points[$assignment_id],0) .'&nbsp;'. _makeLetterGrade($current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS']/$total_points[$assignment_id],get_user_coursesection()).'</TD></TR></TABLE>';
	elseif($total_points[$assignment_id]=='0')
		return '<TABLE border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD>'.TextInput($current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS'],'values['.$_REQUEST['student_id'].']['.$assignment_id.'][POINTS]','',' size=2 maxlength=7').'</TD><TD> / </TD><TD>'.$total_points[$assignment_id].'</TD><TD>&nbsp;'._('N/A').'&nbsp;'._('N/A').'</TD></TR></TABLE>';
	else
		return '<TABLE border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD>'.TextInput($current_array[$_REQUEST['student_id']][$assignment_id][1]['POINTS'],'values['.$_REQUEST['student_id'].']['.$assignment_id.'][POINTS]','',' size=2 maxlength=7').'</TD><TD> / </TD><TD>'.$total_points[$assignment_id].'</TD><TD>&nbsp;'._('N/A').'&nbsp;'._('N/A').'</TD></TR></TABLE>';
}
*/


function _makeExtraCols($value,$column)
{	global $THIS_array,$total_points,$current_array,$old_student_id,$student_count,$tabindex,$count_students,$_SYSTEM;

	if($THIS_array['STUDENT_ID']!=$old_student_id)
	{
		$student_count++;
		$tabindex=$student_count;
		$old_student_id = $THIS_array['STUDENT_ID'];
	}
	else
		$tabindex += $count_students;

	$assignment_id = substr($column,1);
	if($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS']=='-1')
		$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'] = '*';
	elseif(isset($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS']))
	{
		$_SYSTEM['avg_total_points']['G'.$assignment_id] += $current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'];
		$_SYSTEM['avg_total_included']['G'.$assignment_id]++;
	}

	$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'] = ereg_replace('\.$','',((strpos($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'],'.')!==false)?rtrim($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'],'0'):$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS']));

	if($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['HIGHLIGHT']=='Y')
	{
		$highlight_style = ' style="color:#'.Preferences('HIGHLIGHT').';font-weight:bold;"';
		$input_style = ' style="border:2px solid #'.Preferences('HIGHLIGHT').';"';
	}
	$js_onchange = $_SYSTEM['set_js_onchange'];

	$_SYSTEM['set_js_onchange'] = false;
	$doCommands = ' ondblclick="return openCommentsBox(this.form,'.($tabindex+1).');" onkeydown="return nextInput(event,this.form,'.($tabindex+1).','.($tabindex-1).');" onChange="doOnPointsChange(this.id,'.$assignment_id.');'.($js_onchange?" run_rb_submit();":"").'" onfocus="cancelComments();"';
	//.','.($tabindex+$count_students).','.($tabindex-$count_students)
	if($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS']=='*' && $total_points[$assignment_id]==NULL)
		$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.CheckboxInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][POINTS]','',false,'','','',false).'</TD><TD width=10> &nbsp; </TD><TD align=right'.$highlight_style.'>&nbsp;</TD></TR></TABLE>';
	elseif($total_points[$assignment_id]==NULL)
		$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.CheckboxInput('', 'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][POINTS]','',false,'','','',false).'</TD><TD width=10> &nbsp; </TD><TD align=right'.$highlight_style.'>&nbsp;</TD></TR></TABLE>';//&nbsp;'._('Exc.').'
	elseif($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS']=='*')
		$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][POINTS]','',' size=2 maxlength=7 tabindex='.$tabindex.$doCommands.$input_style).'</TD><TD width=10> &nbsp; </TD><TD align=right'.$highlight_style.'>&nbsp;'._('Dld.').'</TD></TR></TABLE>';
		// the extra div tag here is for saveComments since it expects parentNode.parentNode to work
	elseif(!$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'] && $current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS']!=='0')
		$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'><div>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][POINTS]','',' size=2 maxlength=7 tabindex='.$tabindex.$doCommands.$input_style).'</div></TD><TD width=10> &nbsp; </TD><TD align=right'.$highlight_style.'>&nbsp;'._('UG').'</TD></TR></TABLE>'; // the extra div tag here is for saveComments since it expects parentNode.parentNode to work
	elseif($total_points[$assignment_id]==0)
		$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][POINTS]','',' size=2 maxlength=7 tabindex='.$tabindex.$doCommands.$input_style).'</TD><TD width=10> &nbsp; </TD><TD align=right'.$highlight_style.'>&nbsp;'._('EC').'</TD></TR></TABLE>';
	else
	{
		if($total_points[$assignment_id]==100 || $total_points[$assignment_id]==10 || Preferences('DISPLAY_GRADEBOOK_PERCENTAGES','Gradebook')!='Y') // if the assignment is worth 100 points or 10 points, it doesn't make sense to display the percentage, since it takes up room, and is easily calculated
			$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][POINTS]','',' maxlength=7 tabindex='.$tabindex.$doCommands.$input_style).'</TD><TD> </TD><TD align=right'.$highlight_style.'>&nbsp;'. _makeLetterGrade($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS']/$total_points[$assignment_id],get_user_coursesection()).'</TD></TR></TABLE>';
		else
			$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][POINTS]','',' maxlength=7 tabindex='.$tabindex.$doCommands.$input_style).'</TD><TD> </TD><TD align=right'.$highlight_style.'>&nbsp;'.Percent($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS']/$total_points[$assignment_id],0) .'&nbsp;'. _makeLetterGrade($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS']/$total_points[$assignment_id],get_user_coursesection()).'</TD></TR></TABLE>';
	}

	$comment = '<!-- '.$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['POINTS'].' -->';

	if(Preferences('COMMENTS_NOT_POINTS','Gradebook')=='Y')
	{
		if(!$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'])
			// the extra div tag here is for saveComments since it expects parentNode.parentNode to work
			$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'><div>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][COMMENT]','',' size=15 maxlength=100 tabindex='.$tabindex.$input_style).'</div></TD></TR></TABLE>';
		else
//			$return = '<!-- '.$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'].' --><TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][COMMENT]','',' size=15 maxlength=100 tabindex='.$tabindex.$doCommands.$input_style).'</TD></TR></TABLE>';
			$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][COMMENT]','',' size=15 maxlength=100 tabindex='.$tabindex.$doCommands.$input_style).'</TD></TR></TABLE>';

		return $return;
	}
	if(Preferences('LETTER_GRADES_NOT_POINTS','Gradebook')=='Y')
	{
		$doCommands = ' onchange="validateLetterGrade(this.id)"';
		if(!$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'])
			$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'><div>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][COMMENT]','',' size=3 maxlength=100 tabindex='.$tabindex.$doCommands.$input_style).'</div></TD></TR></TABLE>'; // the extra div tag here is for saveComments since it expects parentNode.parentNode to work
		else
//			$return = '<!-- '.$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'].' --><TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][COMMENT]','',' size=3 maxlength=100 tabindex='.$tabindex.$doCommands.$input_style).'</TD></TR></TABLE>';
			$return = '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD'.$highlight_style.'>'.TextInput($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'],'values['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][COMMENT]','',' size=3 maxlength=100 tabindex='.$tabindex.$doCommands.$input_style).'</TD></TR></TABLE>';

		return $return;
	}
	$_SYSTEM['set_js_onchange'] = $js_onchange;
	if($current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT'] && !$_REQUEST['CREATEPDF'])
		return $comment.'<DIV id="inputvalues['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][COMMENT_MOUSEOVER]" onmouseover=\'stm(["","'.str_replace('"','\"',$current_array[$THIS_array['STUDENT_ID']][$assignment_id][1]['COMMENT']).'"],["white","#'.Preferences('HIGHLIGHT').'","","","",,"black","#'.Preferences('COLOR').'","","","",,100,,2,"#'.Preferences('HIGHLIGHT').'",2,,,,,"",,,,]);\' onmouseout=\'htm()\'>'.$return.'</DIV>';
	else
		return $comment.'<DIV id="inputvalues['.$THIS_array['STUDENT_ID'].']['.$assignment_id.'][COMMENT_MOUSEOVER]" onmouseout=\'htm()\'>'.$return.'</DIV>';
}

function _makeName($null,$col)
{	global $THIS_array,$total_column_percent,$_SYSTEM;

	if($total_column_percent[$THIS_array['STUDENT_ID']])
	{
		if(Preferences('LETTER_GRADES_NOT_POINTS','Gradebook')=='Y')
			$total = _makeLetterGrade(($total_column_percent[$THIS_array['STUDENT_ID']]/100),get_user_coursesection());
		else
			$total = Percent($total_column_percent[$THIS_array['STUDENT_ID']]/100).' &nbsp;'._makeLetterGrade(($total_column_percent[$THIS_array['STUDENT_ID']]/100),get_user_coursesection());
	}
	else
		$total = _('UG');

		if($_REQUEST['servicemod'])
			$link = "modloader.php?servicemod=$_REQUEST[servicemod]&assignment_id=student&student_id=".$THIS_array['STUDENT_ID'];
		else
			$link = "index.php?id=".$_REQUEST['id']."&assignment_id=student&student_id=".$THIS_array['STUDENT_ID'];

	$name = '<A class="Grid_hlink" HREF='.$link.'>'.$THIS_array['FULL_NAME'].'</A>';

	return '<TABLE width=100% border=0 cellspacing=0 cellpadding=0 class=GridOutput_fieldint><TR><TD NOWRAP>'.$name.'</TD><TD align=right NOWRAP>&nbsp;'.$total.' &nbsp;</TD></TR></TABLE>';
}

?>
