<?php

include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;
// THIS PROGRAM RELIES ON fckEditor
//	- editor/dialog/fck_template.php
if($_REQUEST['servicefunction']!='iqy_setup' && $_REQUEST['servicemod']!='mod_apply/AppPrintSpecDocs.php' && $_REQUEST['servicemod']!='mod_students/StuPrintSpecDocs.php')
{
	echo GetBaseJavaFunc();
	$item = _('Document Title');
	DisplayHeader(".:".ProgramTitle().":.");
}
//echo "-->".$_REQUEST['servicemod'];
//var_dump($_REQUEST['servicefunction']);
//var_dump($_REQUEST);


//die('kkkkk');

$updated = false;
if($_REQUEST['servicefunction']=='update' && AllowEdit() && !$_REQUEST['new_title'])
{


	$buffered_array = $array;
	$array = db_request(db_execute("SELECT HEADER,FOOTER,TITLE,SCHOOL_ID,DEFAULT_SM,PAGE_BREAKS,DEFAULT_USERS_SM FROM DOCS_TEMPLATES WHERE ID='".$_REQUEST['doc_id']."'"));
//echo "++>".$_REQUEST['doc_id'];


	$title_extra = '';
	if($_REQUEST['values']['title'])
		$title_extra .= ", TITLE='".str_replace("\'","''",$_REQUEST['values']['title'])."'";
	if(isset($_REQUEST['values']['orientation']))
		$title_extra .= ", ORIENTATION='".str_replace("\'","''",$_REQUEST['values']['orientation'])."'";
	if(isset($_REQUEST['values']['school_id']))
	{
		$title_extra .= ", SCHOOL_ID='".str_replace("\'","''",$_REQUEST['values']['school_id'])."'";
		$array[1]['SCHOOL_ID'] = $_REQUEST['values']['school_id'];
	}
	if(isset($_REQUEST['values']['default_sm']))
	{
		$title_extra .= ", DEFAULT_SM='".str_replace("\'","''",$_REQUEST['values']['default_sm'])."'";

		if($array[1]['SCHOOL_ID']!='0')
			$default_array = db_request(db_execute("SELECT TITLE FROM DOCS_TEMPLATES WHERE DEFAULT_SM='".$_REQUEST['values']['default_sm']."' AND ID!='".$_REQUEST['doc_id']."' AND SCHOOL_ID='".$array[1]['SCHOOL_ID']."'"));	
		else
			$default_array = db_request(db_execute("SELECT TITLE FROM DOCS_TEMPLATES WHERE DEFAULT_SM='".$_REQUEST['values']['default_sm']."' AND ID!='".$_REQUEST['doc_id']."' AND SCHOOL_ID='0'"));	
	}

	if(isset($_REQUEST['values']['default_users_sm']))
	{
		$title_extra .= ", DEFAULT_USERS_SM='".str_replace("\'","''",$_REQUEST['values']['default_users_sm'])."'";

		if($array[1]['SCHOOL_ID']!='0')
			$default_teachers_array = db_request(db_execute("SELECT TITLE FROM DOCS_TEMPLATES WHERE DEFAULT_USERS_SM='".$_REQUEST['values']['default_users_sm']."' AND ID!='".$_REQUEST['doc_id']."' AND SCHOOL_ID='".$array[1]['SCHOOL_ID']."'"));	
		else
			$default_teachers_array = db_request(db_execute("SELECT TITLE FROM DOCS_TEMPLATES WHERE DEFAULT_USERS_SM='".$_REQUEST['values']['default_users_sm']."' AND ID!='".$_REQUEST['doc_id']."' AND SCHOOL_ID='0'"));	
	}
	if(isset($_REQUEST['values']['page_breaks_options']))
		$title_extra .= ", PAGE_BREAKS='".str_replace("\'","''",$_REQUEST['values']['page_breaks_options'])."'";
        if(isset($_REQUEST['values']['SCHOOL_DEP']))
		$title_extra .= ", SCHOOL_DEP='".str_replace("\'","''",$_REQUEST['values']['SCHOOL_DEP'])."'";
        if(isset($_REQUEST['values']['SCHOOL_YEAR_DEP']))
		$title_extra .= ", SCHOOL_YEAR_DEP='".str_replace("\'","''",$_REQUEST['values']['SCHOOL_YEAR_DEP'])."'";
	
	if($default_array)
	{
		$text1 = _('Confirm Default');
		$text2 = $default_array[1]['TITLE'];
	}
	if($default_teachers_array)
	{
		$text1 = _('Confirm Default for Teachers, Parents & Students');
		$text2 = $default_teachers_array[1]['TITLE'];
	}
	
	if((!isset($_REQUEST['values']['default_sm']) && !isset($_REQUEST['values']['default_users_sm'])) || (!count($default_array) && !count($default_teachers_array)) || (Prompt(_($text1),sprintf(_('A different template, %s, is already set as the default for %s. Are you sure that you want to overwrite this default?'),$text2,ProgramTitle($_REQUEST['values']['default_sm'])))))
	{
		if(isset($_REQUEST['values']['default_sm']))
			db_execute("UPDATE DOCS_TEMPLATES SET DEFAULT_SM=NULL WHERE DEFAULT_SM='".$_REQUEST['values']['default_sm']."' AND SCHOOL_ID='".$array[1]['SCHOOL_ID']."' AND ID!='".$_REQUEST['doc_id']."'");
			
		if(isset($_REQUEST['values']['default_users_sm']))
			db_execute("UPDATE DOCS_TEMPLATES SET DEFAULT_USERS_SM=NULL WHERE DEFAULT_USERS_SM='".$_REQUEST['values']['default_users_sm']."' AND SCHOOL_ID='".$array[1]['SCHOOL_ID']."' AND ID!='".$_REQUEST['doc_id']."'");
		$sql = "UPDATE DOCS_TEMPLATES SET HEADER='".str_replace("\'","''",$_REQUEST['header'])."',FOOTER='".str_replace("\'","''",$_REQUEST['footer'])."'".$title_extra." WHERE ID='".$_REQUEST['doc_id']."'";
		db_execute($sql);
		unset($_REQUEST['header']);
		unset($_REQUEST['footer']);
		unset($_REQUEST['servicefunction']);
		unset($_REQUEST['values']);
		unset($_SESSION['_REQUEST_vars']['header']);
		unset($_SESSION['_REQUEST_vars']['footer']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['values']);		
	}
	$updated = true;
	if($_REQUEST['servicemod']=='mod_apply/AppPrintSpecDocs.php' || $_REQUEST['servicemod']=='mod_students/StuPrintSpecDocs.php')
	{
		$_REQUEST['servicefunction'] = 'open_doc';
	}
}

if($_REQUEST['new_title'] && AllowEdit())
{
	$id = db_request(db_execute("SELECT ".db_seq_nextval('DOCS_TEMPLATES_SEQ')." AS ID".FROM_DUAL));
	$id = $id[1]['doc_id'];
	db_execute("INSERT INTO DOCS_TEMPLATES (ID,TITLE,SCHOOL_ID) values('$id','".str_replace("\'","''",$_REQUEST['new_title'])."','".get_school_id()."')");

	$_REQUEST['doc_id'] = $id;
	unset($_REQUEST['new_title']);
	unset($_SESSION['_REQUEST_vars']['new_title']);
	unset($_REQUEST['servicefunction']);
	unset($_SESSION['_REQUEST_vars']['servicefunction']);
}

/*
if($_REQUEST['servicefunction']=='delete' && AllowEdit())
{
	if(DeletePrompt(_('Document Template')))
	{
		db_execute("DELETE FROM DOCS_TEMPLATES WHERE ID='".$_REQUEST['id']."'");
		unset($_REQUEST['servicefunction']);
		unset($_REQUEST['id']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['id']);
	}
}
*/
$iqy_saved = false;
//save tables
if($_REQUEST['tables'] && (($_POST && $_REQUEST['servicefunction']!='remove' && $_REQUEST['servicefunction']!='delete' && $_REQUEST['servicefunction']!='open_doc' && $_REQUEST['servicefunction']!='update') || ($_POST && $_REQUEST['servicefunction']=='iqy_setup' && ($_REQUEST['servicemod']=='mod_apply/AppPrintSpecDocs.php' || $_REQUEST['servicemod']=='mod_students/StuPrintSpecDocs.php'))) && AllowEdit())
{
	foreach($_REQUEST['tables'] as $table=>$tid)
	{
    	        foreach($tid as $id=>$columns)
        	{
                    if($columns['SCHOOLS'])
                    {
                        foreach($columns['SCHOOLS'] as $school_id=>$yes)
                        {
                            if($yes=='Y')
                                $schools .= ','.$school_id;
                            if(!empty($yes) && $yes != 'Y')
                                $schools .= ','.$yes[0];
                        }
                        if($schools)
                            $columns['SCHOOLS'] = $schools.',';
                        else
                            $columns['SCHOOLS'] = '';
                    }
	    	        if($id!='new')
    			{                
	            	        $sql = "UPDATE $table SET ";
	                        foreach($columns as $column=>$value)
		                {
                                    $sql .= $column."='".str_replace("'","''",$value)."',";
    			        }
	                        $sql = substr($sql,0,-1)." WHERE ID='$id'";
				db_execute($sql);
	                }
            	        else
                	{
		                $sql = "INSERT INTO $table ";
		                $fields = 'ID,SCHOOL_ID,USER_ID,SERVICEMOD,';
                                if($table == 'DOCS_TEMPLATES_CATEGORIES' && $_REQUEST['servicemod'] !== 'mod_ssetup/SchDocsWorkspace.php')
                                    $fields .= "SCHOOLS,";
		    		$values = db_seq_nextval('DOCS_TEMPLATES_CATEGORIES_SEQ').",'".get_school_id()."','".get_user('USER_ID')."','".$_REQUEST['servicemod']."',";
                                if($table == 'DOCS_TEMPLATES_CATEGORIES' && $_REQUEST['servicemod'] !== 'mod_ssetup/SchDocsWorkspace.php')
                                    $values .= " ',".get_school_id().",', ";
		    		if($_REQUEST['doc_cat_id'] && $table == 'DOCS_TEMPLATES')
		    		{
		    			$fields .= 'DOCUMENT_CATEGORY_ID,';
		    			$values .= "'".$_REQUEST['doc_cat_id']."',";
		    		}
		                $go = 0;
	                        foreach($columns as $column=>$value)
	                        {
	                                if($value || $value == '0')
	                                {
		                                $fields .= $column.',';
		                                $values .= "'".str_replace("'","''",$value)."',";
		                                $go = true;
	                                }
	                        }
    			        $sql .= '('.substr($fields,0,-1).') values('.substr($values,0,-1).')';
		                if($go)
		                {
		                        db_execute($sql);
		                }
		                if($table == 'DOCS_TEMPLATES_CATEGORIES')
		                {
					$id = db_request(db_execute("SELECT MAX(ID) AS ID FROM DOCS_TEMPLATES_CATEGORIES WHERE SCHOOL_ID = '".get_school_id()."'"));
					$_REQUEST['doc_cat_id'] = $id[1]['ID'];
				}
                	}
	        }
	}
	unset($_REQUEST['tables']);
	if($_REQUEST['servicemod']=='mod_apply/AppPrintSpecDocs.php' || $_REQUEST['servicemod']=='mod_students/StuPrintSpecDocs.php')
	{
		unset($_REQUEST['doc_id']);
		unset($_REQUEST['doc_cat_id']);
		$iqy_saved = true;
	}
}
$save_exit = false;
if($_REQUEST['save_exit'])
{
	unset($_REQUEST['servicefunction']);
	unset($_REQUEST['save_exit']);
	$updated = false;
	if($_REQUEST['servicemod'] != 'mod_ssetup/SchDocsWorkspace.php' && $_REQUEST['servicemod'] != 'mod_apply/AppDocTemplate.php' && $_REQUEST['servicemod'] != 'mod_students/StuDocTemplate.php')
		$save_exit = true;
}

// deleting doc temp
if($_REQUEST['servicefunction']=='remove')
{
	if($_REQUEST['doc_id'])
	{
		$delete_button_title = _('Delete Document');
		$question = '<b>'._('Do you want to delete this document?').'</b>';
//		$groups_array = db_request(db_execute("SELECT '' FROM STUDENT_REGISTRATION WHERE GROUP_ID='$_REQUEST[doc_id]'"));
//		if(count($groups_array))
//		{
//			$second_confirm = ErrorMessage(array(_('This group has been assigned to some students. If you delete the group, you will also lost the group in student information.')),'warning');
//		}
	}
	if(Prompt(_("Delete Confirmation"), "<b>".$question."</b>", "", '', $delete_button_title, null, $second_confirm))
//        if(DeletePrompt(_('this class group'),'delete'))
        {
            db_execute("DELETE FROM DOCS_TEMPLATES WHERE ID='$_REQUEST[doc_id]'");
            unset($_REQUEST['delete_ok']);
            unset($_REQUEST['servicefunction']);
            unset($_SESSION['_REQUEST_vars']['servicefunction']);
        }
}
//deleting doc cat
$after_delete = false;
if($_REQUEST['servicefunction']=='delete')
{
//	$groups_array = db_request(db_execute("SELECT '' FROM STUDENT_REGISTRATION WHERE GROUP_ID IN (SELECT ID FROM DOCS_TEMPLATES WHERE ID = '$_REQUEST[doc_cat_id]')"));
//	if(count($groups_array))
//	{
//		$second_confirm = ErrorMessage(array(_('Groups in this category have been assigned to some students. If you delete category and groups, you will also lost the group in student information.')),'warning');
//	}
	$delete_button_title = _('Delete Document Category');
	$question = '<b>'._('Do you want to delete this document category?').'</b>';
	$docs_templ_array = db_request(db_execute("SELECT ID FROM DOCS_TEMPLATES_CATEGORIES WHERE ID='$_REQUEST[doc_cat_id]'"));
//	if(count($docs_templ_array))
//	{
//		$second_confirm .= ErrorMessage(array(_('This category contains some groups. If you delete the category, you will also delete the groups in this category.')),'warning');
//	}
	if(Prompt(_("Delete Confirmation"), "<b>".$question."</b>", "", '', $delete_button_title, null, $second_confirm))
	{
		if($_REQUEST['doc_cat_id'])
		{
			$docs_templ_array = db_request(db_execute("SELECT ID FROM DOCS_TEMPLATES WHERE DOCUMENT_CATEGORY_ID='$_REQUEST[doc_cat_id]'"));
			if(count($docs_templ_array))
			{
//				foreach($docs_templ_array as $doc_id)
					db_execute("DELETE FROM DOCS_TEMPLATES WHERE DOCUMENT_CATEGORY_ID='".$_REQUEST['doc_cat_id']."'");
			}
			db_execute("DELETE FROM DOCS_TEMPLATES_CATEGORIES WHERE ID='$_REQUEST[doc_cat_id]'");
			unset($_REQUEST['doc_cat_id']);
		}
		unset($_REQUEST['servicefunction']);
//		$_REQUEST['doc_cat_id']=='new';
		$after_delete = true;
		$group_tid = 'new';
	}
}
if($_REQUEST['servicefunction']=='open_doc' || $updated === true || ($_REQUEST['servicefunction']=='doc_edit' && AllowEdit()))
{
	if($_SYSTEM['direction'])
		$arrow_right = 'arrow_left';
	else
		$arrow_right = 'arrow_right';
//echo "===>".$_REQUEST['servicemod'];
//var_dump($_REQUEST['servicefunction']);

	echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=update&doc_id=$_REQUEST[doc_id]&doc_cat_id=$_REQUEST[doc_cat_id] method=POST>";
	DisplayHeader('<DIV style="width:800;padding-left:10px;">'._('To create a document template use the formatting palette above the text area. Document templates have').
			_(' three types: a header which appears above the reports content, a footer which appears below the content and header & footer at once.').'<BR><BR>'.
			_('If you want to add students data into your letterhead templates, you have to click the Insert Field button ').
			'<IMG SRC=modules/mod_students/assets/insert.gif>'._(' in the bottom right of the formatting palette and choose any field.').
			'</DIV>',$submitButton->createSButton(_('Save & Exit'),'save_exit','','submit').'   '.$submitButton->createSButton(_('Save'),'btn_save_doc'));
	echo '<BR>';
/*
	echo '<TABLE width=100%><TR><TD valign=top width=200>';
	echo '<TABLE border=0 cellpadding=0 cellspacing=0 width=100%>';
	echo $_REQUEST['id'];
	echo ">".$_REQUEST['doc_id'];
///	$schools = substr(str_replace(",","','",get_user('SCHOOLS')),2,-2);
//	else
//		$schools_extra = '';
	$letterhead_array = db_request(db_execute("SELECT ID,TITLE FROM DOCS_TEMPLATES ".$schools_extra." ORDER BY TITLE"));
	echo '<TR><TD colspan=3 style="border-width:1; border-style: none none solid none;"><b><small>'._('Letterhead Templates').'</small></b></TD></TR>';
	if(count($letterhead_array))
	{
		foreach($letterhead_array as $template)
		{
			if($template['ID']==$_REQUEST['id'])
			{
				echo '<TR id=selected_tr onmouseover="" onmouseout="" bgcolor="#'.Preferences('HIGHLIGHT').'" style="color:white;"><TD width=20 align='.ALIGN_RIGHT.$style.'>'.button('remove','',"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete&id=$template[ID]",20).'</TD><TD '.$style.' onclick="document.location.href=\'modloader.php?servicemod='.$_REQUEST['servicemod'].'&id='.$template['ID'].'\';">';
				$this_title = $template['TITLE'];
			}
			else
				echo '<TR onmouseover=\'this.style.backgroundColor="#'.Preferences('HIGHLIGHT').'"; this.style.color="white";\' onmouseout=\'this.style.cssText="background-color:transparent; color:black;";\'><TD width=20 align='.ALIGN_RIGHT.$style.'>'.button('remove','',"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete&id=$template[ID]",20).'</TD><TD'.$style.' onclick="document.location.href=\'modloader.php?servicemod='.$_REQUEST['servicemod'].'&id='.$template['ID'].'\';">';
			echo '<A style="cursor:pointer;"><small>'.$template['TITLE'].' &nbsp; </small></A>';
			echo '</TD>';
			echo '<TD'.$style.'><A style="cursor:pointer;"><IMG SRC=images/'.$arrow_right.'.gif></A></TD>';
			echo '</TR>';
			$style = ' style="border-width:1; border-style: dashed none none none;"';
		}
	}
	if(!count($letterhead_array) || !$_REQUEST['id'])
		echo '<TR id=selected_tr><TD height=0></TD></TR>';

	echo '<TR id=new_tr onmouseover=\'this.style.backgroundColor="#'.Preferences('HIGHLIGHT').'"; this.style.color="white";\' onmouseout=\'this.style.cssText="background-color:transparent; color:black;";\'><TD width=20 align='.ALIGN_RIGHT.$style.'>'.button('add','','',20).'</TD><TD'.$style.'>';
	echo '<A style="cursor:pointer;" onclick=\'document.getElementById("selected_tr").onmouseover="this.style.backgroundColor=\"#'.Preferences('HIGHLIGHT').'\"; this.style.color=\"white\";"; document.getElementById("selected_tr").onmouseout="this.style.cssText=\"background-color:transparent; color:black;\";"; document.getElementById("selected_tr").style.cssText="background-color:transparent; color:black;"; document.getElementById("new_id_div").style.display="block";document.getElementById("new_title_input").focus();document.getElementById("main_div").style.display="none";document.getElementById("new_tr").onmouseover="";document.getElementById("new_tr").onmouseout="";this.onclick="";\'><small> '._('Add a Letterhead Template').' &nbsp;<BR><DIV id=new_id_div style="display:none;">'._('Title').' <INPUT type=text id=new_title_input name=new_title></DIV> </small></A>';
	echo '</TD>';
	echo '<TD'.$style.'><A style="cursor:pointer;"><IMG SRC=images/'.$arrow_right.'.gif></A></TD>';
	echo '</TR>';
	
	echo '</TABLE>';
	echo '</TD><TD width=75%>';*/
	echo '<DIV id=main_div>';
	if($_REQUEST['doc_id'])
	{

		$array = db_request(db_execute("SELECT HEADER,SCHOOL_DEP,SCHOOL_YEAR_DEP,FOOTER,TITLE,SCHOOL_ID,DEFAULT_SM,ORIENTATION,PAGE_BREAKS,DEFAULT_USERS_SM,DOC_TYPE,USER_ID FROM DOCS_TEMPLATES WHERE ID='".$_REQUEST['doc_id']."'"));
		include_once($staticpath."js/fckeditor/fckeditor.php");
		
		if($array[1]['ORIENTATION']=='landscape')
			$width = 950;
		else
			$width = 700;

//		PopTable('header',false,'width='.$width,0);
		PopTable('header',false,'width=90%',0);
		echo '<TABLE>';
		echo '<TR><TD><b>'._('Document Title').':</b></TD><TD>'.TextInput($array[1]['TITLE'],'values[title]').'</TD></TR>';
		
		$schools = substr(str_replace(",","','",get_user('SCHOOLS')),2,-2);
		$schools_arr[0] = _('All Schools');
		$choose_schools = false;
		if($schools)
		{	
			$schools = explode(',',str_replace("'",'',$schools));
			foreach($schools as $school)
				$schools_arr[$school] = get_school($school);
			if(count($schools_arr)>1)
				$choose_schools = true;
		}
		else
		{
			$schools_array = db_request(db_execute("SELECT ID,TITLE FROM SCHOOLS"));
			if(count($schools_array)>1)
			{
				$choose_schools = true;
				foreach($schools_array as $school)
					$schools_arr[$school['ID']] = $school['TITLE'];
			}
		}
		
		if($choose_schools)
			echo '<TR><TD><b>'._('School').':</b></TD><TD>'.SelectInput($array[1]['SCHOOL_ID'],'values[school_id]',null,$schools_arr,false,null,'force').'</TD></TR>';
//		$template_programs = array('mod_grades/GrdPrintStudentReportCards.php'=>_('Report Cards'),'mod_evaluation/BncGetStudReportCard.php'=>_('Benchmark Report Cards'),'mod_grades/GrdStudentPrintGC.php'=>_('Transcripts'),'mod_grades/GrdBookReportWorkspace.php'=>_('Gradebook Progress Reports'),'mod_students/StuLetterWorkspace.php'=>_('Print Letters & Send Emails'),'mod_curriculum/ScdPRStudSchedWorkspace.php'=>_('Print Schedules'),'mod_curriculum/ScdPRStudReqWorkspace.php'=>_('Print Requests'),'mod_curriculum/ScdPReportStudClassList.php'=>_('Print Class Lists'),'mod_billing/BilStatReport.php'=>_('Print Statements'));
//		echo '<TR><TD><b>'._('Default for').':</b></TD><TD>'.SelectInput($array[1]['DEFAULT_SM'],'values[default_sm]',null,$template_programs,_('No Programs'),null,'force').'</TD></TR>';
//		echo '<TR><TD><b>'._('Default for Teachers, Parents & Students').':</b></TD><TD>'.SelectInput($array[1]['DEFAULT_USERS_SM'],'values[default_users_sm]',null,$template_programs,_('No Programs'),null,'force').'</TD></TR>';

		$orientations = array('portrait'=>_('Portrait'),'landscape'=>_('Landscape'));
		echo '<TR><TD><b>'._('Page Orientation').':</b></TD><TD>'.SelectInput($array[1]['ORIENTATION'],'values[orientation]',null,$orientations,_('Auto'),null,'force').'</TD></TR>';

		$pageBreaksOptions = array(0 =>_("Include Hard Page Breaks between Students"), 1 =>_("Don't Include Hard Page Breaks"));
		echo '<TR><TD><b>'._('Include Hard Page Breaks between Students').':</b></TD><TD>'.SelectInput($array[1]['PAGE_BREAKS'],'values[page_breaks_options]',null,$pageBreaksOptions,false,null,'force').'</TD></TR>';
                /*
                 * Counter setup */
                echo '<TR><TD><b>'._('Counter Options').':</b></TD><TD>';
                $count_options = $array[1];
                $SCHOOL_DEP = $count_options['SCHOOL_DEP'];
                    echo CheckboxInput($SCHOOL_DEP, 'values[SCHOOL_DEP]', _('School'));
                $SCHOOL_YEAR_DEP = $count_options['SCHOOL_YEAR_DEP'];
                    echo CheckboxInput($SCHOOL_YEAR_DEP, 'values[SCHOOL_YEAR_DEP]', _('Year'));
                //echo SelectInput($array[1]['PAGE_BREAKS'],'values[page_breaks_options]',null,$pageBreaksOptions,false,null,'force');
                echo '</TD></TR>';
                $more_options = '';
                if($SCHOOL_DEP == 'Y')
                    $more_options .= " AND SCHOOL_ID = '".get_school_id()."' ";
                if($SCHOOL_YEAR_DEP == 'Y')
                    $more_options .= " AND SCHOOL_YEAR = '".get_school_year()."' ";
                $count_value = db_request(db_execute("SELECT VALUE FROM STD_COUNTER WHERE DOC_ID = '".$_REQUEST['doc_id']."' $more_options "));
                $count_value = $count_value[1]['VALUE'];
                echo '<TR><TD><b>'._('Current Counter Value').':</b></TD><TD>'.NoInput($count_value).'</TD></TR>';
                 /** Counter setup end
                */

		echo '</TABLE><BR>';
//		echo "-->".$array[1]['DOC_TYPE'];
		if($array[1]['DOC_TYPE'] == '0' || $array[1]['DOC_TYPE'] == '1' || !$array[1]['DOC_TYPE'])
		{
			echo '<b>'._('Header').': </b>';
			$oFCKeditor = new FCKeditor('header',null,800);
			$oFCKeditor->BasePath = 'js/fckeditor/';
			$oFCKeditor->ToolbarSet = 'Letterhead';
			$oFCKeditor->Value = $array[1]['HEADER'];
			echo $oFCKeditor->Create();
		}
		if($array[1]['DOC_TYPE'] == '1' || $array[1]['DOC_TYPE'] == '2')
		{
			echo '<b><BR><BR>'._('Footer').':</b>';
			$oFCKeditor = new FCKeditor('footer',null,800);
			$oFCKeditor->BasePath = 'js/fckeditor/';
			$oFCKeditor->Value = $array[1]['FOOTER'];
			$oFCKeditor->ToolbarSet = 'Letterhead';
			echo $oFCKeditor->Create();
		}
		echo '<CENTER>'.$submitButton->createSButton(_('Save'),'btn_save_doc').'</CENTER>';
		PopTable('footer');
	}
	echo '</DIV>';
	echo '</TD></TR></TABLE>';
	echo '</FORM>';
}

//var_dump($_REQUEST['servicefunction']);
//var_dump($_REQUEST);
//var_dump($save_exit);
//var_dump($updated);
if($_REQUEST['servicefunction']!='delete' && $_REQUEST['servicefunction']!='remove' && $_REQUEST['servicefunction']!='open_doc' && $_REQUEST['servicefunction']!='update' && $updated === false && $iqy_saved === false && $_REQUEST['servicefunction']!='doc_edit' && $save_exit === false)
{
    if(!$_REQUEST['servicefunction'] && $_REQUEST['doc_cat_id'] && $_REQUEST['doc_cat_id']!='new')
    {
        $types_array = db_request(db_execute("SELECT ID AS ID,TITLE FROM DOCS_TEMPLATES_CATEGORIES ORDER BY TITLE"));// WHERE SCHOOL_ID='".get_school_id()."'
        if(count($types_array)==1 && !$_REQUEST['doc_cat_id'])
        	$_REQUEST['doc_cat_id'] = $types_array[1]['ID'];
        if($_REQUEST['doc_id']!='new' && $_REQUEST['doc_cat_id']!='new')
        	$delete_button = "<INPUT style='width:100px;' type=button value="._('Delete')." onClick='javascript:window.location=\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete&doc_cat_id=$_REQUEST[doc_cat_id]\"'>";
    }
    if($_REQUEST['doc_cat_id'] && $_REQUEST['doc_cat_id']!='new' && $_REQUEST['doc_id']!='new')
    {
    	    $sql = "SELECT ID AS ID,SCHOOL_ID,SCHOOLS,TITLE,SHORT_NAME,SORT_ORDER
                                    FROM DOCS_TEMPLATES_CATEGORIES
                                    WHERE ID='$_REQUEST[doc_cat_id]'";
            $QI = db_execute($sql);

            $array = db_request($QI);
            $array = $array[1];
            $title = $array['TITLE'];
    }
    elseif($_REQUEST['doc_id']=='new')
            $title = _("New Document");
    elseif($_REQUEST['doc_cat_id']=='new')
            $title = _("New Document Category");

    if($_REQUEST['doc_cat_id'])
    {
                    echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&doc_cat_id=$_REQUEST[doc_cat_id] method=POST>";
                    $_REQUEST['DrawAlign'] = 'LEFT';
                    if($after_delete === false)
                	    DisplayHeader('<B>'.$title.'</B>',$delete_button.' &nbsp; &nbsp;<INPUT style="width:100px;" type=submit value='._('Save').'>');
                    unset($_REQUEST['DrawAlign']);
                    //Панель ввода и отображения данных начинает формироваться тут
                    if($after_delete === false && $_REQUEST['servicefunction']!='iqy_setup')
                    {
	                    $header .= '<TABLE border=0 cellpadding=3 cellspacing=0 width=100%>';
//                     if($_REQUEST['doc_cat_id']=='new')
//                            echo 'new';
    	        	    $header .= '</TD></TR><TR>';
        	            $header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;" align=center>'.TextInput($array['TITLE'],'tables[DOCS_TEMPLATES_CATEGORIES]['.$_REQUEST['doc_cat_id'].'][TITLE]',_('Document Category Title'),' size=20').'</TD>';
	                    $header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;">'.TextInput($array['SHORT_NAME'],'tables[DOCS_TEMPLATES_CATEGORIES]['.$_REQUEST['doc_cat_id'].'][SHORT_NAME]',_('Short Name'),' size=8 maxlength=8').'</TD>';
    	        	    $header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;">'.TextInput($array['SORT_ORDER'],'tables[DOCS_TEMPLATES_CATEGORIES]['.$_REQUEST['doc_cat_id'].'][SORT_ORDER]',_('Sort Order'),' size=4 maxlength=4').'</TD>';
        	            $header .= '</TR>';
                            if($_REQUEST['servicemod']=='mod_ssetup/SchDocsWorkspace.php')
                            {
                                $header .= '<TR>';
                                $header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;">';
                                        $sql = "SELECT ID,TITLE FROM SCHOOLS ORDER BY TITLE";
                                        $QI = db_execute($sql);
                                        $school_array = db_request($QI);
                                        unset($options);
                                        if(count($school_array))
                                        {
                                            $opt = '||';
                                            foreach($school_array as $value)
                                            {
                                                $opt .= ((strpos($array['SCHOOLS'],','.$value['ID'].',')!==false)?$value['ID'].'||':'');
                                                $school_options[$value['ID']] = $value['TITLE'];
                                            }
                                            $school_options['ALL'] = _('All Schools');
                                            //$div = ($opt=='')?false:'force';
                                            if($_REQUEST['doc_cat_id']=='new')
                                                $div = false;
                                            else
                                                $div = 'force';
                                            if($div == 'force')
                                            {
                                                echo "<script>";
                                                echo 'jQuery(document).ready(function() {';
                                                echo 'var school_div= document.getElementById("innerdivtables[DOCS_TEMPLATES_CATEGORIES]['.$_REQUEST['doc_cat_id'].'][SCHOOLS][]");';
                                                    echo 'jQuery(school_div).click(function(){';
                                                        echo "jQuery.getScript(\"ajax.php?function_=checkall\", function(data){});";
                                                    echo '});';
                                                echo '});';
                                                echo "</script>";
                                            }
                                            else
                                            {
                                                echo '<script>
                                                jQuery(document).ready(function() {
                                                jQuery("input:checkbox[value=\'ALL\']").click(function(){
                                                    if(jQuery("input:checkbox[value=\'ALL\']").is(":checked"))
                                                        jQuery("input:checkbox").attr("checked","checked"); // устанавливает галочку на все checkbox-ы
                                                    else
                                                        jQuery("input:checkbox").removeAttr("checked"); // снимает галочку со всех checkbox-ов
                                                });
                                            });
                                            </script>';

                                            }
                                            $header .= SelectMultipleInput($opt, 'tables[DOCS_TEMPLATES_CATEGORIES]['.$_REQUEST['doc_cat_id'].'][SCHOOLS][]',_('Schools'), $school_options,null,null,$div,4);
                                        }
                                $header .= '</TD>';
                                $header .= '</TR>';
                            }
                	    $header .= '</TABLE>';
                    }

    }
    else
        $header = false;

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

            $Gridoutput_options = array('save'=>false,'search'=>false,'add'=>true,'xscroll'=>false);
            echo '<TABLE><TR>';
            $doc_cat_array = db_request(db_execute("SELECT ID,SCHOOL_ID,SCHOOLS,TITLE,SHORT_NAME,SORT_ORDER,USER_ID FROM DOCS_TEMPLATES_CATEGORIES ORDER BY SORT_ORDER"));
            if($_REQUEST['servicemod']<>'mod_ssetup/SchDocsWorkspace.php')
            {
                if(count($doc_cat_array))
                {
                        $i=1;
                        foreach($doc_cat_array as $key=>$value)
                        {
                            if(strpos($value['SCHOOLS'],  ','.get_school_id().',') === false)
                                unset($doc_cat_array[$key]);
                            else
                            {
                                $tmp_doc_cat_array[$i] = $value;
                                $i++;
                            }
                        }
                        $doc_cat_array = $tmp_doc_cat_array;
                }
            }

            if(count($doc_cat_array))
            {
                    if($_REQUEST['doc_cat_id'])
                    {
                            foreach($doc_cat_array as $key=>$value)
                            {
                                    if($value['ID']==$_REQUEST['doc_cat_id'])
                                            $doc_cat_array[$key]['row_color'] = Preferences('HIGHLIGHT');
                            }
                    }
            }

            echo '<TD valign=top>';
            $columns = array('TITLE'=>_('Document Category'),'SHORT_NAME'=>_('Short Name'));
            if($_REQUEST['servicefunction']=='iqy_setup')
        	    unset($columns['SHORT_NAME']);
            $link =array();
            $link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]";
            $link['TITLE']['variables'] = array('doc_cat_id'=>'ID');
            if($_REQUEST['servicefunction']!='iqy_setup')            
	            $link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&doc_cat_id=new";

            Gridoutput($doc_cat_array,$columns,_('Document Categories'),_('Amount of Document Categories'),$link,array(),$Gridoutput_options);
            echo '</TD>';
//            echo '</TR></TABLE>';
}

// doc_id
if($_REQUEST['doc_cat_id'] && $_REQUEST['doc_cat_id']!='new' && !empty($doc_cat_array) && $after_delete === false && $_REQUEST['servicefunction']!='delete' && $_REQUEST['servicefunction']!='remove' && $_REQUEST['servicefunction']!='open_doc')// && $_REQUEST['tables']!='DOCS_TEMPLATES_CATEGORIES')
{
    echo '<TD valign=top style="width:100%;">';
    $doc_types_array = array(_('Header Only'),_('Header & Footer'),_('Footer Only'));
    if($_REQUEST['servicefunction']!='remove' && $_REQUEST['servicefunction']!='open_doc')
    {

	    $_SYSTEM['itable'] = 'DOCS_TEMPLATES';
            $sql = "SELECT USE_INQUIRY,ID,SCHOOL_ID,USER_ID,USE_STUDENTS,TITLE,SHORT_NAME,SORT_ORDER,DOCUMENT_CATEGORY_ID,DOC_TYPE FROM DOCS_TEMPLATES WHERE  DOCUMENT_CATEGORY_ID='".$_REQUEST['doc_cat_id']."' ORDER BY SORT_ORDER";//SCHOOL_ID='".get_school_id()."' AND
            $QI = db_execute($sql);
	    $html_field_name = 'docs_templates';            
            $docs_array = db_request($QI,array('TITLE'=>'makeTextInput','SHORT_NAME'=>'makeTextInput','USER_ID'=>'get_teacher_allschools','SORT_ORDER'=>'makeTextInput','DOC_TYPE'=>'makeDocInput','USE_INQUIRY'=>'makeCheckInput','USE_STUDENTS'=>'makeCheckInput'));
	    unset($columns);
	    unset($link);
            $columns = array('TITLE'=>_('Document Title'),'SHORT_NAME'=>_('Short Name'),'SORT_ORDER'=>_('Sort Order'),'USER_ID'=>_('Owner'),'DOC_TYPE'=>_('Document Type'),'USE_INQUIRY'=>_('Used for Applicants'));
            if($_REQUEST['servicemod'] == 'mod_students/StuPrintSpecDocs.php')
            {
        	    unset($columns['USE_INQUIRY']);
        	    $columns += array('USE_STUDENTS'=>_('Use for Students'));
    	    }
	    // 'CHECKBOX'=>'</A><INPUT type=checkbox value=Y name=controller onclick="checkAll(this.form,this.checked,\''.$html_field_name.'\');CheckAll_hilite(this.form,this.form.controller.checked,\''.$html_field_name.'\');"><A>',		            
            if($_REQUEST['servicefunction']!='iqy_setup')
        	    unset($columns['USE_INQUIRY']);
            if($_REQUEST['servicefunction']=='iqy_setup')
            {        	    
                    $Gridoutput_options = array('save'=>false,'search'=>false,'add'=>true,'xscroll'=>false);
                    unset($columns['SORT_ORDER']);
                    unset($columns['DOC_TYPE']);
            }
            else
	    {
	            $link['add']['html'] = array('TITLE'=>makeTextInput('','TITLE'),'SHORT_NAME'=>makeTextInput('','SHORT_NAME'),'SORT_ORDER'=>makeTextInput('','SORT_ORDER'),'DOC_TYPE'=>makeDocInput('','DOC_TYPE'));
	            $link['remove']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=remove";
	            $link['open']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=open_doc";
	            $link['remove']['variables'] = array('doc_cat_id'=>'DOCUMENT_CATEGORY_ID','doc_id'=>'ID');
	            $link['open']['variables'] = array('doc_cat_id'=>'DOCUMENT_CATEGORY_ID','doc_id'=>'ID');
            }

//            echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=update method=POST>";
    //	DisplayHeader('','<INPUT type=submit value='._('Save').'>');
            Gridoutput($docs_array,$columns,_('Documents'),_('Amount of Documents'),$link,array(),$Gridoutput_options);
            unset($_SYSTEM['itable']);
            
    //        echo '<CENTER><INPUT type=submit value='._('Save').'></CENTER>';

    }

    echo '</TD>';
    echo '</TR></TABLE>';
    echo '<CENTER>'.$submitButton->createSButton(_('Save')).'</CENTER>';
    echo '</FORM>';        
}



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

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

	if($name!='TITLE')
		$addition = 'size=6 maxlength=10';
	if($name=='SORT_ORDER')
		$comment = '<!-- '.$value.' -->';

	return $comment.TextInput($value,'tables['.$_SYSTEM['itable'].']['.$id.']['.$name.']','',$addition,$div);
}

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

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

	return SelectInput($value,'tables['.$_SYSTEM['itable'].']['.$id.']['.$name.']','',$doc_types_array,_('N/A'),'',$div);
}

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

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

	return CheckboxInput($value,'tables['.$_SYSTEM['itable'].']['.$id.']['.$name.']','',$doc_types_array,'',_('Yes'),_('No'),$div);
}

function _makeChooseCheckbox1($value,$title='')
{       global $THIS_array, $html_field_name;

        $doc_id_field="ID";
        
        return "<INPUT onchange='hl_cb(this)' type=checkbox name=".$html_field_name."[".$THIS_array[$doc_id_field]."] value=Y>";
}
                
?>