<?php
echo '<script type="text/javascript" src="js/jquery.maskedinput-1.2.2.min.js" ></script>';
include_once($staticpath . 'classes/InputButton.php');
$submitButton = new InputButton;

echo GetBaseJavaFunc();

if($_REQUEST['values'] && $_POST['values'] && AllowEdit())
{
//var_dump($_REQUEST['values']);
    foreach($_REQUEST['values'] as $id => $columns)
    {
/*
        if($columns['START_TIME'])
          $columns['START_TIME'] = substr($columns['START_TIME'],0,-3);
          if($columns['END_TIME'])
          $columns['END_TIME'] = substr($columns['END_TIME'],0,-3);
*/
        if(is_array($columns['START_TIME']))
        {
	          foreach($columns['START_TIME'] as $dw=>$dtime)
	          {
	        	$columns['START_TIME_'.$dw] = $dtime;
	          }
	          unset($columns['START_TIME']);
	          foreach($columns['END_TIME'] as $dw=>$dtime)
	          {
	        	$columns['END_TIME_'.$dw] = $dtime;
	          }
	          unset($columns['END_TIME']);
	}
/*
          if($columns['START_TIME']['SUN'])
          {
        	$columns['START_TIME_SUN'] = $columns['START_TIME_SUN'];
          }
          if($columns['END_TIME_SUN'])
          $columns['END_TIME_SUN'] = substr($columns['END_TIME_SUN'],0,-3);
          if($columns['START_TIME_MON'])
          $columns['START_TIME_MON'] = substr($columns['START_TIME_MON'],0,-3);
          if($columns['END_TIME_MON'])
          $columns['END_TIME_MON'] = substr($columns['END_TIME_MON'],0,-3);
          if($columns['START_TIME_TUE'])
          $columns['START_TIME_TUE'] = substr($columns['START_TIME_TUE'],0,-3);
          if($columns['END_TIME_TUE'])
          $columns['END_TIME_TUE'] = substr($columns['END_TIME_TUE'],0,-3);
          if($columns['START_TIME_WED'])
          $columns['START_TIME_WED'] = substr($columns['START_TIME_WED'],0,-3);
          if($columns['END_TIME_WED'])
          $columns['END_TIME_WED'] = substr($columns['END_TIME_WED'],0,-3);
          if($columns['START_TIME_THU'])
          $columns['START_TIME_THU'] = substr($columns['START_TIME_THU'],0,-3);
          if($columns['END_TIME_THU'])
          $columns['END_TIME_THU'] = substr($columns['END_TIME_THU'],0,-3);
          if($columns['START_TIME_FRI'])
          $columns['START_TIME_FRI'] = substr($columns['START_TIME_FRI'],0,-3);
          if($columns['END_TIME_FRI'])
          $columns['END_TIME_FRI'] = substr($columns['END_TIME_FRI'],0,-3);
          if($columns['START_TIME_SAT'])
          $columns['START_TIME_SAT'] = substr($columns['START_TIME_SAT'],0,-3);
          if($columns['END_TIME_SAT'])
          $columns['END_TIME_SAT'] = substr($columns['END_TIME_SAT'],0,-3);
          }          
*/          
        if($id != 'new'){
            $sql = "UPDATE SCHOOL_PERIODS SET ";

            foreach($columns as $column => $value)
            {
                $sql .= $column."='".str_replace("\'", "''", $value)."',";
            }
            $sql = substr($sql, 0, -1)." WHERE SCHOOL_PERIOD_ID='$id'";
            db_execute($sql);
        }else{
            $sql = "INSERT INTO SCHOOL_PERIODS ";

            $fields = 'SCHOOL_PERIOD_ID,SCHOOL_ID,SCHOOL_YEAR,';
            $values = db_seq_nextval('SCHOOL_PERIODS_SEQ').",'".get_school_id()."','".get_school_year()."',";

            $go = 0;
            foreach($columns as $column => $value){
                if($value){
                    $fields .= $column.',';
                    $values .= "'".str_replace("\'", "''", $value)."',";
                    $go = true;
                }
            }
            $sql .= '('.substr($fields, 0, -1).') values('.substr($values, 0, -1).')';

            if($go)
                db_execute($sql);
        }
    }
}

if(!$_REQUEST['CREATEPDF']){
    //echo '<script language="javascript" src="js/jstime/mootools.v1.11.js"></script>';
    //echo '<script language="javascript" src="js/jstime/nogray_time_picker.js"></script>';
    echo '
		<style>
			.table_list {border-collapse:collapse;
				border:solid #cccccc 1px;
				width:100%;}
			
			.table_list td {padding:5px;
				border:solid #efefef 1px;}
			
			.table_list th {background:#75b2d1;
				padding:5px;
				color:#ffffff;}
			
			.table_list tr.odd {background:#e1eff5;}
			
			.time_picker_div {padding:5px;
				background:#'.Preferences('ROLLOVER_HIGHLIGHT').';
				border: 1px solid #'.Preferences('HIGHLIGHT').';
				}
				
		</style>';

    echo '<script language=javascript>';

    echo "
            function date12(id)
            {
                var hour = jQuery('#'+id).val().substr(0,2);
                var min = jQuery('#'+id).val().substr(3,2);
                var utype = jQuery('#'+id).val().substr(6,2);
                if(utype =='')
                    var type = (hour=12)?'PM':'';
                else
                    var type = utype;

                hour = (hour>12)?hour-12:hour;
                jQuery('#'+id).val(hour+':'+min+' '+type);
            }
            function date24(id)
            {

            }
            ";
    
    echo "jQuery.mask.definitions['g']='[ ]';";
    echo "jQuery.mask.definitions['T']='[aApP]';";
    echo "jQuery.mask.definitions['L']='[mM]';";
    if(Preferences('LOGIN_DATE_FORMAT') == '12')
    {
        echo "jQuery.mask.definitions['H']='[01]';";
    }
    else
    {
        echo "jQuery.mask.definitions['H']='[012]';";
    }
    echo "jQuery.mask.definitions['M']='[012345]';";
    if(SystemPreferences('VARIABLE_PERIOD_LENGTH') != 'Y'){

                        echo "function makeLength(id,col)
                            {
				if(document.getElementById('innerdivvalues['+id+'][START_TIME]'))
                                    document.getElementById('innerdivvalues['+id+'][START_TIME]').onclick();
                                if(document.getElementById('innerdivvalues['+id+'][END_TIME]'))
                                    document.getElementById('innerdivvalues['+id+'][END_TIME]').onclick();
                                if(document.getElementById('innerdivvalues['+id+'][LENGTH]'))
                                    document.getElementById('innerdivvalues['+id+'][LENGTH]').onclick();
                                if(document.getElementById('inputvalues_'+id+'_START_TIME').value && document.getElementById('inputvalues_'+id+'_END_TIME').value)
                                {
                                    if(document.getElementById('innerdivvalues['+id+'][LENGTH]'))
                                        document.getElementById('innerdivvalues['+id+'][LENGTH]').onclick();

                                    stime = document.getElementById('inputvalues_'+id+'_START_TIME').value;
                                    etime = document.getElementById('inputvalues_'+id+'_END_TIME').value;

                                    shour = stime.substr(0,2)*1;
                                    smins = stime.substr(3,2)*1;

                                    ehour = etime.substr(0,2)*1;
                                    emins = etime.substr(3,2)*1;

                                    if(ehour>shour || (ehour==shour && emins>smins))
                                    {
                                        plength = ((ehour-shour)*60) - smins + emins;
                                        document.getElementById('inputvalues['+id+'][LENGTH]').value = plength;
                                    }
                                }
			}";
    }else{
        echo '
                        function makeLength(id,col)
			{
			
				col = col.substring(col.indexOf("][")+2);
				col = col.substring(0,col.length-1);
				start_col = "START_TIME_"+col.substring(col.length-3);
				end_col = "END_TIME_"+col.substring(col.length-3);
				length_col = "LENGTH_"+col.substring(col.length-3);

				if(document.getElementById(\'innerdivvalues[\'+id+\'][\'+start_col+\']\'))
					document.getElementById(\'innerdivvalues[\'+id+\'][\'+start_col+\']\').onclick();
				if(document.getElementById(\'innerdivvalues[\'+id+\'][\'+end_col+\']\'))
					document.getElementById(\'innerdivvalues[\'+id+\'][\'+end_col+\']\').onclick();
				if(document.getElementById(\'inputvalues\'+id+\'_\'+start_col).value && document.getElementById(\'inputvalues[\'+id+\'][\'+end_col+\']\').value)
				{
					if(document.getElementById(\'innerdivvalues[\'+id+\'][\'+length_col+\']\'))
						document.getElementById(\'innerdivvalues[\'+id+\'][\'+length_col+\']\').onclick();
					stime = document.getElementById(\'inputvalues_\'+id+\'_\'+start_col).value;
					etime = document.getElementById(\'inputvalues_\'+id+\'_\'+end_col).value;
			
					shour = stime.substr(0,2)*1;
					smins = stime.substr(3,2)*1;
					
					ehour = etime.substr(0,2)*1;
					emins = etime.substr(3,2)*1;
                                        
					if(ehour>shour || (ehour==shour && emins>smins))
					{
						plength = ((ehour-shour)*60) - smins + emins;
						document.getElementById(\'inputvalues[\'+id+\'][\'+length_col+\']\').value = plength;
					}
				}
				
			}';
    }

    echo '
	</script>';
}

DisplayHeader(".:".ProgramTitle().":.");

if($_REQUEST['servicefunction'] == 'remove' && AllowEdit()){
    if(DeletePrompt(_('period'))){
        db_execute("DELETE FROM SCHOOL_PERIODS WHERE SCHOOL_PERIOD_ID='$_REQUEST[id]'");
        unset($_REQUEST['servicefunction']);
    }
}

if($_REQUEST['servicefunction'] != 'remove'){
    if(Preferences('LOGIN_DATE_FORMAT') == '12')
        $sql = "SELECT SCHOOL_PERIOD_ID,TITLE,SHORT_NAME,SORT_ORDER,LENGTH,".db_to_char('START_TIME', 'HH12:MI AM')." AS START_TIME,".db_to_char('END_TIME', 'HH12:MI AM')." AS END_TIME," .
                db_to_char('START_TIME_SUN', 'HH12:MI AM')." AS START_TIME_SUN,".db_to_char('END_TIME_SUN', 'HH12:MI AM')." AS END_TIME_SUN,".db_to_char('START_TIME_MON', 'HH12:MI AM')." AS START_TIME_MON,".db_to_char('END_TIME_MON', 'HH12:MI AM')." AS END_TIME_MON,".db_to_char('START_TIME_TUE', 'HH12:MI AM')." AS START_TIME_TUE,".db_to_char('END_TIME_TUE', 'HH12:MI AM')." AS END_TIME_TUE,".db_to_char('START_TIME_WED', 'HH12:MI AM')." AS START_TIME_WED,".db_to_char('END_TIME_WED', 'HH12:MI AM')." AS END_TIME_WED,".db_to_char('START_TIME_THU', 'HH12:MI AM')." AS START_TIME_THU,".db_to_char('END_TIME_THU', 'HH12:MI AM')." AS END_TIME_THU,".db_to_char('START_TIME_FRI', 'HH12:MI AM')." AS START_TIME_FRI,".db_to_char('END_TIME_FRI', 'HH12:MI AM')." AS END_TIME_FRI,".db_to_char('START_TIME_SAT', 'HH12:MI AM')." AS START_TIME_SAT,".db_to_char('END_TIME_SAT', 'HH12:MI AM')." AS END_TIME_SAT,
			BLOCK,ATTENDANCE,
			LENGTH_SUN,LENGTH_MON,LENGTH_TUE,LENGTH_WED,LENGTH_THU,LENGTH_FRI,LENGTH_SAT
			FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER";
    else
        $sql = "SELECT SCHOOL_PERIOD_ID,TITLE,SHORT_NAME,SORT_ORDER,LENGTH,".db_to_char('START_TIME', 'HH24:MI')." AS START_TIME,".db_to_char('END_TIME', 'HH24:MI')." AS END_TIME," .
                db_to_char('START_TIME_SUN', 'HH24:MI')." AS START_TIME_SUN,".db_to_char('END_TIME_SUN', 'HH24:MI')." AS END_TIME_SUN," .
                db_to_char('START_TIME_MON', 'HH24:MI')." AS START_TIME_MON,".db_to_char('END_TIME_MON', 'HH24:MI')." AS END_TIME_MON," .
                db_to_char('START_TIME_TUE', 'HH24:MI')." AS START_TIME_TUE,".db_to_char('END_TIME_TUE', 'HH24:MI')." AS END_TIME_TUE," .
                db_to_char('START_TIME_WED', 'HH24:MI')." AS START_TIME_WED,".db_to_char('END_TIME_WED', 'HH24:MI')." AS END_TIME_WED," .
                db_to_char('START_TIME_THU', 'HH24:MI')." AS START_TIME_THU,".db_to_char('END_TIME_THU', 'HH24:MI')." AS END_TIME_THU," .
                db_to_char('START_TIME_FRI', 'HH24:MI')." AS START_TIME_FRI,".db_to_char('END_TIME_FRI', 'HH24:MI')." AS END_TIME_FRI," .
                db_to_char('START_TIME_SAT', 'HH24:MI')." AS START_TIME_SAT,".db_to_char('END_TIME_SAT', 'HH24:MI')." AS END_TIME_SAT,
			BLOCK,ATTENDANCE,
			LENGTH_SUN,LENGTH_MON,LENGTH_TUE,LENGTH_WED,LENGTH_THU,LENGTH_FRI,LENGTH_SAT
			FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER";

    $functions = array('TITLE' => '_makeTextInput', 'SHORT_NAME' => '_makeTextInput', 'SORT_ORDER' => '_makeTextInput', 'BLOCK' => '_makeTextInput', 'LENGTH' => '_makeTextInput', 'START_TIME' => '_makeTimeInput', 'END_TIME' => '_makeTimeInput', 'ATTENDANCE' => '_makeCheckboxInput');
    if(SystemPreferences('VARIABLE_PERIOD_LENGTH') == 'Y')
        $functions['LENGTH'] = '_makeLength';
    $periods_array = db_request(db_execute($sql), $functions);
    if(SystemPreferences('VARIABLE_PERIOD_LENGTH') == 'Y')
        $columns = array('TITLE' => _('Period Title'),
            'SHORT_NAME' => _('Short Name'),
            'SORT_ORDER' => _('Sort Order'),
            'START_TIME' => _('School Period Start Time By Days'),
            'END_TIME' => _('School Period End Time By Days'),
            'LENGTH' => _('School Period Duration By Days'),
            'BLOCK' => _('Block Title'),
            'ATTENDANCE' => _('Attendance Control'));
    else
        $columns = array('TITLE' => _('Period Title'),
            'SHORT_NAME' => _('Short Name'),
            'SORT_ORDER' => _('Sort Order'),
            'START_TIME' => _('School Period Start Time'),
            'END_TIME' => _('School Period End Time'),
            'LENGTH' => _('School Period Duration'),
            'BLOCK' => _('Block Title'),
            'ATTENDANCE' => _('Attendance Control'));

    $link['add']['html'] = array('TITLE' => _makeTextInput('', 'TITLE'), 'SHORT_NAME' => _makeTextInput('', 'SHORT_NAME'), 'LENGTH' => _makeTextInput('', 'LENGTH'), 'SORT_ORDER' => _makeTextInput('', 'SORT_ORDER'), 'BLOCK' => _makeTextInput('', 'BLOCK'), 'START_TIME' => _makeTimeInput('', 'START_TIME'), 'END_TIME' => _makeTimeInput('', 'END_TIME'), 'ATTENDANCE' => _makeCheckboxInput('', 'ATTENDANCE'));
    if(SystemPreferences('VARIABLE_PERIOD_LENGTH') == 'Y')
        $link['add']['html']['LENGTH'] = _makeLength('', 'LENGTH');

    $link['remove']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=remove";
    $link['remove']['variables'] = array('id' => 'SCHOOL_PERIOD_ID');
    echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=update method=POST>";
    DisplayHeader('', $submitButton->createSButton(_('Save')));
    Gridoutput($periods_array, $columns, _('Data'), _('Amount of School Periods'), $link);
    echo '<CENTER>'.$submitButton->createSButton(_('Save')).'</CENTER>';
    echo '</FORM>';

}

function _makeTextInput($value, $name)
{
    global $THIS_array;

    if($THIS_array['SCHOOL_PERIOD_ID']){
        $id = $THIS_array['SCHOOL_PERIOD_ID'];
        $div = 'force';
    }else{
        $id = 'new';
        $div = false;
    }

    if($name != 'TITLE')
        $addition = 'size=5 maxlength=10';

    return TextInput($value, 'values['.$id.']['.$name.']', '', $addition, $div);
}

function _makeCheckboxInput($value, $name)
{
    global $THIS_array;

    if($THIS_array['SCHOOL_PERIOD_ID'])
        $id = $THIS_array['SCHOOL_PERIOD_ID'];
    else
        $id = 'new';

    return CheckboxInput($value, 'values['.$id.']['.$name.']', '', '', ($id == 'new' ? true : false), '<IMG SRC=images/check.gif height=15>', '<IMG SRC=images/x.gif>');
}

function _makeTimeInput($value, $name)
{
    global $THIS_array, $_SYSTEM;

    if($THIS_array['SCHOOL_PERIOD_ID']){
        $id = $THIS_array['SCHOOL_PERIOD_ID'];
        $div = 'force';
    }else{
        $id = 'new';
        $div = false;
        $cellpadding_extra = ' cellpadding=0 cellspacing=0 border=0';
    }
    if(SystemPreferences('VARIABLE_PERIOD_LENGTH') == 'Y')
    {
        if(Preferences('CALENDAR') == 'Mon')
            $days = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
        else
            $days = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');

        $empty = true;
        foreach($days as $day){
            if($THIS_array[$name.'_'.strtoupper($day)]){
                $empty = false;
                break;
            }
        }
        if($empty){
            $div = false;
            $cellpadding_extra = ' cellpadding=0 cellspacing=0 border=0';
        }

        $header .= '<TABLE class=GridOutput_fieldint width=310'.$cellpadding_extra.'><TR>';
        foreach($days as $day)
        {
            $value = $THIS_array[$name.'_'.strtoupper($day)];
            $header .= '<TD>'.TimejQueryInput($value, 'values['.$id.']['.$name.']['.strtoupper($day).']','values_'.$id.'_'.$name.'_'.strtoupper($day),_($day), 'makeLength('.$id.',"values['.$id.']['.$name.'_'.strtoupper($day).']");', $div);
        }
        $header .= '</TR></TABLE>';

        return $header;
    }
    else
        return TimejQueryInput($value, 'values['.$id.']['.$name.']', 'values_'.$id.'_'.$name,$day, (($id=='new')?'makeLength(\''.$id.'\',this.id);':'makeLength('.$id.',this.id);').((Preferences('LOGIN_DATE_FORMAT') == '12')?'date12(this.id);':''), $div);
}

function _makeLength($na, $name)
{
    global $THIS_array;

    if($THIS_array['SCHOOL_PERIOD_ID']){
        $id = $THIS_array['SCHOOL_PERIOD_ID'];
        $div = 'force';
    }else{
        $id = 'new';
        $div = false;
        $cellpadding_extra = ' cellpadding=0 cellspacing=0 border=0';
    }

    $header .= '<TABLE class=GridOutput_fieldint'.$cellpadding_extra.'><TR>';
    if(Preferences('CALENDAR') == 'Mon')
        $days = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
    else
        $days = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
    foreach($days as $day){
        $value = $THIS_array['LENGTH_'.strtoupper($day)];

        $header .= '<TD>'.TextInput($value, 'values['.$id.'][LENGTH_'.strtoupper($day).']', _($day), 'size=2 maxlength=3', $div).'</TD>';
    }
    $header .= '</TR></TABLE>';

    return $header;
}
?>