<?php
//require_once ($static_path."modules/mod_portal/date_to_ru.php");
function Gridoutput($result,$column_names,$singular='',$plural='',$link=false,$group=false,$options=false,$count_option=false,$hardcount=false){	
		global $_SYSTEM,$sum;

		if(!isset($options['headersize']))	$options['headersize'] = -1;
		if(!isset($options['save']))	$options['save'] = true;
		if(!isset($options['print']))	$options['print'] = true;
		if(!isset($options['search']))	$options['search'] = true;
		if(!isset($options['center']))	$options['center'] = false;
		if(!isset($options['count']))	$options['count'] = true;
		if(!isset($options['sort']))	$options['sort'] = true;
		if(!isset($options['cellpadding']))	$options['cellpadding'] = 0;
		if(!isset($options['onclick']))	$options['onclick'] = "";
		if(!isset($options['filter']))	$options['filter']=false;
    	if(!isset($options['rowspan']))	$options['rowspan'] = null;
    	if(!isset($options['openfilter']))	$options['openfilter'] = false;
		if(!$link)
		$link = array();

		$is_IE = strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')!==false;

	    if(!isset($options['add'])){
			if(!AllowEdit()){
				if($link){
					unset($link['add']);
					unset($link['remove']);
				}
			}
		}

		// Added - ability to set various table, td styles
		$s_class_table = isset($options['table_class']) ? "class='" .$options['table_class'] . "'" : '';
		$s_class_lo_field = isset($options['lo_field_class']) ? "class='" .$options['lo_field_class'] . "'" : "class='GridOutput_fieldstyle'";
		$s_class_inner_lo_field = isset($options['inner_lo_field_class']) ? "class='" .$options['inner_lo_field_class'] : "class='GridOutput_fieldint'";
		$s_class_header_field = "class='Gridtable_header'";
        
		if(!function_exists("_doFilter")){
			/**
			 * function _countGrouped count number of rows even if result is grouped
			 *
			 * @param mixed $result Result
			 * @return mixed Count of rows, no matter if result is grouped
			 */
			function _countGrouped($result,$count_option=false){
				$count = 0;
				if(!$result) $result = array();
				foreach($result as $key => &$value){
					foreach($value as $k1 => &$v1){
						//handling grouped and non-grouped result
	                    if($count_option){
	                    	if(!$group_count[$v1[$count_option]]){
	                            $group_count[$v1[$count_option]] = true;
	                            $count++;
	                        }
	                    }
	                    else{
	                    	if(!is_array($v1)){
	                    		$count=count($result);
	                    		break 2;
	                    	}
	                    	else{
	                    		$count++; //=count($v1);
	                    	}
	                    }
					}
				} 
				return $count;
			}

			/**
			 * function _calculateFilter takes one parameter $str, containing only numbers and & and |, like 1&1|0 and calculating this expression.
			 * OR has top priority.
			 * @param mixed $str Input string
			 * @return mixed bool result of calculation
			 *
			 */

			function _calculateFilter($str){
				$result = true;
				if(strlen($str)>0){
					//calculate ORs first
					while(substr_count($str,"|")){
						$str=str_replace("0|0","0",$str);
						$str=str_replace("0|1","1",$str);
						$str=str_replace("1|0","1",$str);
						$str=str_replace("1|1","1",$str);
					}
					//then calculate ANDs
					while(substr_count($str,"&")){
						$str=str_replace("0&0","0",$str);
						$str=str_replace("0&1","0",$str);
						$str=str_replace("1&0","0",$str);
						$str=str_replace("1&1","1",$str);
					}
					//in the end there must be single symbol - 0 or 1
					$result=($str=="1");
				}
				return $result;
			}

			/**
			 * function _doFilter applies the filter and returns only related rows
			 *
			 * @param mixed $result Input result to filter
			 * @return mixed Filtered rows from input
			 */

			function _doFilter($result){
				$filtered = array("0"=>null);
				$filter_rules = array();

				//checking if there are filters and making filter array
				$msr_has_filters = isset($_REQUEST['msr_rule_column']) && is_array($_REQUEST['msr_rule_column']) && count($_REQUEST['msr_rule_column']);
				if($msr_has_filters){
					foreach($_REQUEST['msr_rule_column'] as $k=>$v){
						$column = $v;
						$operator = $_REQUEST['msr_rule_op'][$k];
						$val = $_REQUEST['msr_rule_value'][$k];
						$cond = $_REQUEST['msr_rule_cond'][$k];

						if($column && $operator != "" && $val != ""){
							$filter_rules[] = array(
													'column'=>$column,'operator'=>$operator,
													'val'=>$val,'cond'=>$cond
												);
						}
					} 
				}

				foreach($result as $key => $value){
					$break = false;
					foreach($value as $k1 => $v1){
					//check whether result is grouped
					if(!is_array($v1)){
						$vv = $value; //array($k1 => $v1);
						$break = true;
					}
					else
						$vv = $v1;
						$inc = true; //flag used for grouped result
						$str = "";

						foreach($filter_rules as $k=>$v){
							if(!array_key_exists($v['column'], $vv)) continue;
							//remove all tags and leave only text
							$text = strtolower(strip_tags($vv[$v['column']]));
							$vval = strtolower($v['val']);
							$condition = $v['cond'];
							//this used for filtering by checkbox columns with x or check picture
							if("" == $text)
							$text = (substr_count($vv[$v['column']], "check.gif")) ? "y" : "n";
							$op = true;
							switch($v['operator'])
							{
								case "1": //equal
								{
									$op = ($text == $vval);

									break;
								} //1
								case "2": //not equal
								{
									$op = ($text != $vval);

									break;
								} //2
								case "3": //starts with
								{
									$pos = strpos($text, $vval);
									$op = ($pos === 0);

									break;
								} //3
								case "4": //contains
								{
									$pos = substr_count($text, $vval);
									$op = ($pos > 0);

									break;
								} //4
								case "5": //doesnt contain
								{
									$pos = substr_count($text, $vval);
									$op = ($pos == 0);

									break;
								} //5
								case "6": //less
								{
									$op = $text < $vval;

									break;
								}
								case "7": //greater
								{
									$op = $text > $vval;

									break;
								}
								case "8": //less or equal
								{
									$op = $text <= $vval;

									break;
								}
								case "9": //greaater or equal
								{
									$op = $text >= $vval;

									break;
								}
								default:
								{
									break;
								}
							} //switch
							$str .= ($op ? "1" : "0").("1" == $condition ? "&" : "|");
						} 
						
						$str = substr($str,0, strlen($str)-1);
						$inc = _calculateFilter($str);

						if($inc){
							if(is_array($v1)){
								$filtered[$key][$k1] = $v1; //for grouped results
							}
							else{
								$filtered[] = $value; //for ungrouped (sorted) results
							}
						}

						if($break) break;
				}
			} //foreach($result as $key=>$value)

			unset($filtered[0]);

			return $filtered;
		} //function _doFilter($result)
	}

	if($options['filter']){
		$result = _doFilter($result);
	}

    $rowspan_cnt = array();

    if($options['rowspan'])
    {
        foreach($result as $key=>$value)
        {
            foreach($value as $k1 => &$v1)
            {
                //handling grouped and non-grouped result
                if(!is_array($v1))
                {
                    $rowspan_cnt[$key] = 1;
                }
                else
                {
                    $rowspan_cnt[$key]++;
                }
            }
        }
    }

	// PREPARE LINKS ---
	$result_count = $display_count = _countGrouped($result,$count_option); //count($result);
	$num_displayed = 100000;
	$addition = "page=$_REQUEST[page]&GridSortingBy=$_REQUEST[GridSortingBy]&GridOrder=$_REQUEST[GridOrder]&GridSearchIn=".urlencode($_REQUEST['GridSearchIn']);

	$tmp_REQUEST = $_REQUEST;
	unset($tmp_REQUEST['page']);
	unset($tmp_REQUEST['GridSortingBy']);
	unset($tmp_REQUEST['GridOrder']);
	unset($tmp_REQUEST['GridSearchIn']);
	unset($tmp_REQUEST['remove_prompt']);
	unset($tmp_REQUEST['remove_name']);
	unset($tmp_REQUEST['Gridoutput_store']);
	unset($tmp_REQUEST['PHPSESSID']);
	$PHP_tmp_SELF = SetRequestOptions($tmp_REQUEST);
	// END PREPARE LINKS ---

	// UN-GROUPING
	$group_count = is_countable($group)?count($group):'';
	

	if($group_count && $_REQUEST['GridSortingBy']){
		unset($group);
		$group_count = 0;
	}
	elseif(is_array($group) && count($group)){
		$display_zero = true;
	}

	if(!is_array($group))
		$group_count = false;

		$side_color = Preferences('COLOR');
		
		if($group_count && $result_count){
			$color = Preferences('HIGHLIGHT_BACKGROUND');
			$group_result = $result;
			unset($result);
			$result[0] = '';
			$i = '';//это исправляет баг в настройке списка студентов, там не показывался первый title.

		foreach($group_result as $item1)
		{
			if($group_count==1){
				if($color==Preferences('HIGHLIGHT_BACKGROUND'))
					$color = $side_color;
				else
					$color = Preferences('HIGHLIGHT_BACKGROUND');
			}

			foreach($item1 as $item2){
				if($group_count==1){
					$i++;
					if(is_countable($group[0]) && $i!=1){
						foreach($group[0] as $column){
							$item2[$column] = str_replace('<!-- <!--','<!--','<!-- '.str_replace('-->','--><!--',$item2[$column])).' -->';
						}
					}
					$item2['row_color'] = $color;
					$result[] = $item2;
				}
				else{
					if($group_count==2){
						if($color==Preferences('HIGHLIGHT_BACKGROUND'))
							$color = $side_color;
						else
							$color = Preferences('HIGHLIGHT_BACKGROUND');
					}

					foreach($item2 as $item3)
					{
						if($group_count==2){
							$i++;
							if(count($group[0]) && $i!=1){
								foreach($group[0] as $column)
									$item3[$column] = '<!-- '.$item3[$column].' -->';
							}
							if(count($group[1]) && $i!=1){
								foreach($group[1] as $column)
									$item3[$column] = '<!-- '.$item3[$column].' -->';
							}
							$item3['row_color'] = $color;
							$result[] = $item3;
						}
						else
						{
							if($group_count==3){
								if($color==Preferences('HIGHLIGHT_BACKGROUND'))
									$color = $side_color;
								else
									$color = Preferences('HIGHLIGHT_BACKGROUND');
							}
							//this needed to be checked with MSR 
							foreach($item3 as $item4)
							{
								if($group_count==3)
								{
									$i++;
									if($group[2] && $i!=1)
									{
										if(is_array($group[2]))
											foreach($group[2] as $column)
												unset($item4[$column]);
										else
										{
											$column = $group[2];
											unset($item4[$column]);
											unset($item4);
										}
											
									}
									if($item4)
									{
										$item4['row_color'] = $color;
										$result[] = $item4;
									}
								}
							}
//							die();
						}
					}
				}
			}
			$i = 0;
		}
		unset($result[0]);
		$result_count = count($result);

		unset($_REQUEST['GridSortingBy']);
	}
	// END UN-GROUPING
	$_LIST['output'] = true;

	// PRINT HEADINGS, PREPARE PDF, AND SORT THE LIST ---
	if($_LIST['output']!=false)
	{
		if($result_count != 0)
		{
			$count = 0;
			$remove = is_countable($link['remove']['variables']);
			$open = is_countable($link['open']['variables']);
			$cols = is_countable($column_names);

			// HANDLE SEARCHES ---
			if($result_count && $_REQUEST['GridSearchIn'] && $_REQUEST['GridSearchIn']!=_('Search'))
			{
				$_REQUEST['GridSearchIn'] = $search_term = str_replace('\\\"','"',$_REQUEST['GridSearchIn']);
				$_REQUEST['GridSearchIn'] = $search_term = ereg_replace('[^a-zA-Z0-9 _"]*','',strtolower($search_term));

				if(substr($search_term,0,0)!='"' && substr($search_term,-1)!='"')
				{
					$search_term = ereg_replace('"','',$search_term);
					while($space_pos = strpos($search_term,' '))
					{
						$terms[strtolower(substr($search_term,0,$space_pos))] = 1;
						$search_term =  substr($search_term,($space_pos+1));
					}
					$terms[trim($search_term)] = 1;
				}
				else
				{
					$search_term = ereg_replace('"','',$search_term);
					$terms[trim($search_term)] = 1;
				}

				unset($terms['of']); unset($terms['the']); unset($terms['a']); unset($terms['an']); unset($terms['in']);
                                
				foreach($result as $key=>$value)
				{
                                        
					$values[$key] = 0;
					foreach($value as $name=>$val)
					{
						$val = ereg_replace('[^a-zA-Z0-9 _]+','',strtolower($val));
						if(strtolower($_REQUEST['GridSearchIn'])==$val)
							$values[$key] += 25;
						foreach($terms as $term=>$one)
						{
							if(ereg($term,$val))
								$values[$key] += 3;
						}
					}
					if($values[$key]==0)
					{
						unset($values[$key]);
						unset($result[$key]);
						$result_count--;
						$display_count--;
					}
				}
				if($result_count)
				{
					array_multisort($values,SORT_DESC,$result);
					$result = ReindexResults($result);
					$values = ReindexResults($values);

					$last_value = 1;
					$scale = (100/$values[$last_value]);

					for($i=$last_value;$i<=$result_count;$i++)
						$result[$i]['RELEVANCE'] = '<!--' . ((int) ($values[$i]*$scale)) . '--><IMG SRC=images/pixel_grey.gif width=' . ((int) ($values[$i]*$scale)) . ' height=10>';
				}
				$column_names['RELEVANCE'] = _("Relevance");
			} //end search in
			
			// END SEARCHES ---

			if($_REQUEST['GridSortingBy'] && !$_SYSTEM['GridSorted'])
			{
//			var_dump($_REQUEST['GridSortingBy']);
//			var_dump($result);
				foreach($result as $sort)
				{
					//if(substr($sort[$_REQUEST['GridSortingBy']],0,4)!='<!--')
	                    		if(strpos($sort[$_REQUEST['GridSortingBy']],'<!--')===false)
						$sort_array[] = $sort[$_REQUEST['GridSortingBy']];
					else
						$sort_array[] = substr($sort[$_REQUEST['GridSortingBy']],strpos($sort[$_REQUEST['GridSortingBy']],'<!--')+4,strpos($sort[$_REQUEST['GridSortingBy']],'-->')-5);
				}
//				var_dump($sort_array);
				if($_REQUEST['GridOrder']==-1)
					$dir = SORT_DESC;
				else
					$dir = SORT_ASC;

				if($result_count>1)
				{
					if(is_int($sort_array[1]) || is_double($sort_array[1]))
						array_multisort($sort_array,$dir,SORT_NUMERIC,$result);
					else
						array_multisort($sort_array,$dir,$result);
					for($i=$result_count-1;$i>=0;$i--)
						$result[$i+1] = $result[$i];
					unset($result[0]);
				}
			}
		}
		// HANDLE SAVING THE LIST ---

		if($_REQUEST['Gridoutput_store']=='1')
		{
			if(!$options['save_delimiter'] && Preferences('DELIMITER')=='CSV')
				$options['save_delimiter'] = 'comma';
			switch($options['save_delimiter'])
			{
				case 'comma':
					$extension = 'csv';
					$delimiter = ',';
				break;
				case 'xml':
					$extension = 'xml';
				break;
				case 'none':
					$delimiter = '';
				break;
				default:
					$extension = 'xls';
					if($options['save_delimiter'])
						$delimiter = $options['save_delimiter'];
					else
						$delimiter = "\t";
				break;
			}
			if($options['extension'])
				$extension = $options['extension'];

			while(@ob_end_clean());
			if($options['save_delimiter']!='xml' && !$options['alternate_header'])
			{
				foreach($column_names as $key=>$value)
					$output .= str_replace('&nbsp;',' ',str_replace('<BR>',' ',str_replace('<!--.*-->','',$value))) . $delimiter;
				if($options['save_delimiter']=='comma' && $extension=='txt')
					$output = substr($output,0,-1);
				if($options['line_breaks']=='both') // for
					$output .= "\r\n";
				else
					$output .= "\n";
			}
			elseif($options['alternate_header']!==true && strlen($options['alternate_header'])) // if alternate_header is boolean true, no header will be printed.
			{
				$output .= $options['alternate_header'];
			}
			foreach($result as $item)
			{
                            
				foreach($column_names as $key=>$value)
				{
					if($options['save_delimiter']=='comma' && !$options['save_quotes'])
						$item[$key] = str_replace(',',';',$item[$key]);
					$item[$key] = str_replace('<SELECT.*SELECTED\>([^<]+)<.*</SELECT\>','\\1',$item[$key]);
					$item[$key] = str_replace('<SELECT.*</SELECT\>','',$item[$key]);
					$item[$key] = str_replace("[\r\n\t]",'|',$item[$key]);
					if($extension=='xls')
						$output .= ($options['save_quotes']?'"':'') . ($options['save_delimiter']=='xml'?'<'.str_replace(' ','',$value).'>':'') . str_replace('<[^>]+>','',str_replace("<div onclick='[^']+'>",'',str_replace(' +',' ',str_replace('&[^;]+;','',str_replace('<BR>&middot;',' : ','="'.str_replace('&nbsp;',' ',$item[$key]).'"'))))) . ($options['save_delimiter']=='xml'?'</'.str_replace(' ','',$value).'>'."\n":'') . ($options['save_quotes']?'"':'') . $delimiter;
					else // since michigan reports need padded spaces - possibly others
						$output .= ($options['save_quotes']?'"':'') . ($options['save_delimiter']=='xml'?'<'.str_replace(' ','',$value).'>':'') . ereg_replace('<[^>]+>','',ereg_replace("<div onclick='[^']+'>",'',ereg_replace('&[^;]+;','',str_replace('<BR>&middot;',' : ',str_replace('&nbsp;',' ',$item[$key]))))) . ($options['save_delimiter']=='xml'?'</'.str_replace(' ','',$value).'>'."\n":'') . ($options['save_quotes']?'"':'') . $delimiter;
				}
				if($options['save_delimiter']=='comma')
					$output = substr($output,0,-1);
				if($options['line_breaks']=='both') // for
					$output .= "\r\n";
				else
					$output .= "\n";
			}
                        if(Preferences('CONVERT_CP1251') == 'Y')
                            $output = mb_convert_encoding($output, "CP-1251", "UTF-8");
			if($options['filename'])
				$filename = $options['filename'];
			else
				$filename = ProgramTitle().'.'.$extension;
			header("Cache-Control: public");
			header("Pragma: ");
			header("Content-Type: application/$extension");
			header("Content-Disposition: attachment; filename=\"".$filename."\"\n");
			if($options['save_eval'])
				eval($options['save_eval']);
			echo $output;
			exit();
		}
		// END SAVING THE LIST ---
		if($options['center'])
			echo '<CENTER>';
		$header_color = Preferences('HIGHLIGHT');

		if(($result_count > $num_displayed) || (($options['count'] || $display_zero) && ((($result_count==0 || $display_count==0) && $plural) || ($result_count==0 || $display_count==0))))
		{
			echo "<TABLE border=0 width=100% cellpadding=0 cellspacing=0 ";
			//if(isset($_REQUEST['CREATEPDF']))
			//	echo " width=100%";
			echo " $s_class_table ><TR><TD>";
		}

		if($options['count'] || $display_zero)
		{
/*			if (Preferences('LANGUAGE') == 'ru_RU')
			{
				if(($result_count==0 || $display_count==0) && $plural && !$options['middle'])
				{
				    $plural = str_replace('Amount of','',$plural);
					echo "<b>".$plural.' '._('no were found.')."</b> &nbsp; &nbsp;";
				}elseif(($result_count==0 || $display_count==0) && !$options['middle'])
				{
					echo '<b>'._('None were found.').'</b> &nbsp; &nbsp;';
				}elseif($result_count==0 || $display_count==0)
				{
					echo $options['middle'];
				}
			}else{
*/
				if(($result_count==0 || $display_count==0) && $plural && !$options['middle'])
				{
//				    $plural = str_replace('Amount of','',$plural);
				    $singular = str_replace('Amount of','',$singular);
//				    echo $singular;
					echo "<b>"._('No ').' '._($singular).' '._('were found.')."</b> &nbsp; &nbsp;";
				}elseif(($result_count==0 || $display_count==0) && !$options['middle'])
				{
					echo '<b>'._('None were found.').'</b> &nbsp; &nbsp;';
				}elseif($result_count==0 || $display_count==0)
				{
					echo $options['middle'];
				}
//			}
		}
		if($result_count != 0 || ($_REQUEST['GridSearchIn'] && $_REQUEST['GridSearchIn']!=_('Search')))
		{
			if(!isset($_REQUEST['CREATEPDF']))
			{
				if(!$_REQUEST['page'])
					$_REQUEST['page'] = 1;
				if(!$_REQUEST['GridOrder'])
					$_REQUEST['GridOrder'] = 1;
				$start = ($_REQUEST['page'] - 1) * $num_displayed + 1;
				$stop = $start + ($num_displayed-1);
				if($stop > $result_count)
					$stop = $result_count;

				if($result_count > $num_displayed)
				{
					$where_message = "<SMALL>"._('Displaying')." $start "._('through')." $stop</SMALL>";
					echo "Go to Page ";
					if(ceil($result_count/$num_displayed) <= 10)
					{
						for($i=1;$i<=ceil($result_count/$num_displayed);$i++)
						{
							if($i!=$_REQUEST['page'])
								$pages .= "<A HREF=$PHP_tmp_SELF&GridSortingBy=$_REQUEST[GridSortingBy]&GridOrder=$_REQUEST[GridOrder]&GridSearchIn=".urlencode($_REQUEST['GridSearchIn'])."&page=$i>$i</A>, ";
							else
								$pages .= "$i, ";
						}
						$pages = substr($pages,0,-2) . "<BR>";
					}
					else
					{
						for($i=1;$i<=7;$i++)
						{
							if($i!=$_REQUEST['page'])
								$pages .= "<A HREF=$PHP_tmp_SELF&GridSortingBy=$_REQUEST[GridSortingBy]&GridOrder=$_REQUEST[GridOrder]&GridSearchIn=".urlencode($_REQUEST['GridSearchIn'])."&page=$i>$i</A>, ";
							else
								$pages .= "$i, ";
						}
						$pages = substr($pages,0,-2) . " ... ";
						for($i=ceil($result_count/$num_displayed)-2;$i<=ceil($result_count/$num_displayed);$i++)
						{
							if($i!=$_REQUEST['page'])
								$pages .= "<A HREF=$PHP_tmp_SELF&GridSortingBy=$_REQUEST[GridSortingBy]&GridOrder=$_REQUEST[GridOrder]&GridSearchIn=".urlencode($_REQUEST['GridSearchIn'])."&page=$i>$i</A>, ";
							else
								$pages .= "$i, ";
						}
						$pages = substr($pages,0,-2) . " &nbsp;<A HREF=$PHP_tmp_SELF&GridSortingBy=$_REQUEST[GridSortingBy]&GridOrder=$_REQUEST[GridOrder]&GridSearchIn=".urlencode($_REQUEST['GridSearchIn'])."&page=" . ($_REQUEST['page'] +1) . ">Next Page</A><BR>";
					}
					echo $pages;
					echo "</TD></TR></TABLE>";
					echo '<BR>';
				}
			}
			else
			{
				//here making report card pdf
				$start = 1;
				$stop = $result_count;
				if(!$options['header_row_height'])
					$options['header_row_height'] = 0;
				else
					$options['header_row_height'] = ceil($options['header_row_height']/2);
				if($cols>8 || ($_REQUEST['customised_view'] && $_REQUEST['customised_view']!='false') || $_SESSION['orientation'] == 'landscape')
				{
					$_SESSION['orientation'] = 'landscape';
					$repeat_headers = 35 - $options['header_row_height'];
				}
				else
					$repeat_headers = 52 - $options['header_row_height'];
				$repeat_headers = 1000000;
				
				if($options['print'])
				{
					$html = explode('<!-- new page -->',strtolower(ob_get_contents()));
					$html = $html[count($html)-1];
					if(($options['count'] || $display_zero) && ((($result_count==0 || $display_count==0) && $plural) || ($result_count==0 || $display_count==0)))
						echo "</TD></TR></TABLE>";
					$br = (substr_count($html,'<br>')) + (substr_count($html,'<br />')) + (substr_count($html,'</ul>')) + (substr_count($html,'</p>')) + (substr_count($html,'</tr>')) + (substr_count($html,'</h1>')) + (substr_count($html,'</h2>')) + (substr_count($html,'</h3>')) + (substr_count($html,'</h4>')) + (substr_count($html,'</h5>'));
					if($br%2!=0)
					{
						// I cannot explain why, but the first page is fooed without this line.
						$br++;
						//echo '<BR>';
					}
				}
				elseif(($options['count'] || $display_zero) && ((($result_count==0 || $display_count==0) && $plural) || ($result_count==0 || $display_count==0)))
					echo "</TD></TR></TABLE>";
			}
			// END MISC ---

			// WIDTH = 100%

			// SEARCH BOX & MORE HEADERS
			if($where_message || ($singular && $plural) || (!isset($_REQUEST['CREATEPDF']) && $options['search']) || $options['middle'])
			{
				if($options['filter'] && !function_exists("_drawSearchForm"))
				{
					/**
					 * function _drawSearchForm ouputs filter form
					 *
					 * @return mixed Nothing returns
					 *
					 */
					function _drawSearchForm($column_names, $openfilter)
					{
						global $msr_rule_td0, $msr_rule_td1, $msr_rule_td2, $msr_rule_td3, $msr_rule_td4, $msr_search_btn, $_SYSTEM;

                    				$result = '';

						$operators = array(
								'1'=>_('Equal'),
								'2'=>_('Not Equal'),
								'6'=>_('Less Than'),
								'7'=>_('Greater Than'),
								'8'=>_('Less or Equal'),
								'9'=>_('Greater or Equal'),
								'3'=>_('Starts With'),
								'4'=>_('Contains'),
								'5'=>_('Does Not Contain')
						);

						$conditions = array(
								"1"=>_("AND"),
								"2"=>_("OR")
						);

						$AllowEditTemp = $_SYSTEM['AllowEdit'];
						$_SYSTEM['AllowEdit'] = array(true);

						$msr_search_btn= "<input type=submit value='"._("Run Filter")."' />";
						$msr_rule_td0='<center><a href="javascript:;" onclick="msr_filter_remove_rule(this.parentNode.parentNode.parentNode);" style="text-decoration:none;">'._('Remove').'</a></center>';
//						$msr_rule_td0='<center><a href="#" onclick="msr_filter_remove_rule(this.parentNode.parentNode.parentNode)" style="text-decoration:none;">'._('Remove').'</a></center>';
						$msr_rule_td1=SelectInput(0,'msr_rule_column[]','',$column_names,' ','', false, null, false);
						$msr_rule_td2=SelectInput(0,'msr_rule_op[]','',$operators,' ','', false, null, false); //contains as default
						$msr_rule_td3='<input type=text name=msr_rule_value[] size=20 />'; //<a href="#" style="cursor:hand;" onclick="ShowHint(this.previousSibling, this.parentNode.parentNode.childNodes[1].childNodes[1].selectedIndex)">Hint</a>';
						//$msr_rule_td4="<center><small>And</small></center>";
						$msr_rule_td4=SelectInput(0, 'msr_rule_cond[]',"",$conditions, false,"", false, null, false);

						/**
						 * function _prepareJS prepares javascript for handling adding
						 * new row to filter form (maximum 10 lines)
						 *
						 * @return mixed returns script tags with msr_filter_add_rule() function inside
						 *
						 */
						function _prepareJS()
						{
							global $options, $msr_rule_td0, $msr_rule_td1, $msr_rule_td2, $msr_rule_td3, $msr_rule_td4, $msr_search_btn;

							if(!is_array($options))
								$options = array();

							$msr_max_rows = 10+2; //2=top row+bottom row

							$result = "<script>
									var msr_rules_td=new Array();
									msr_rules_td[0]='$msr_rule_td0';
									msr_rules_td[1]='$msr_rule_td1';
									msr_rules_td[2]='$msr_rule_td2';
									msr_rules_td[3]='$msr_rule_td3';
									msr_rules_td[4]='$msr_rule_td4';

									function msr_filter_remove_rule(node)
									{
										var table=document.getElementById('msr_rules_table').firstChild; //table-tbody
										var lastrow = document.getElementById('msr_addrule_link'); //last row with 'Add Rule' link
										var prev=node.previousSibling;
										if(node==lastrow.previousSibling)
										{
											prev.lastChild.innerHTML=\"$msr_search_btn\";
										}
										table.removeChild(node);
										if(table.childNodes.length<=3)
										{
											table.firstChild.nextSibling.firstChild.innerHTML=\"\";
										}
										else
										{
											table.firstChild.nextSibling.firstChild.innerHTML='$msr_rule_td0';
										}
									}

									//
									function msr_filter_add_rule()
									{
										var table=document.getElementById('msr_rules_table').firstChild; //table-tbody
										var lastrow = document.getElementById('msr_addrule_link'); //last row with 'Add Rule' link
										if(table.childNodes.length<$msr_max_rows)
										{
											var newrow = document.createElement('tr');
											for(i=0;i<msr_rules_td.length;i++)
											{
												var td=document.createElement('td');
												td.innerHTML=msr_rules_td[i];
												newrow.appendChild(td);
											}
											lastrow.previousSibling.lastChild.innerHTML=msr_rules_td[4];
											table.insertBefore(newrow, lastrow);
											lastrow.previousSibling.lastChild.innerHTML=\"$msr_search_btn\";
											if(table.childNodes.length>=$msr_max_rows)
											{
												lastrow.firstChild.firstChild.style.display='none';
											}
										}
										if(table.childNodes.length<=3)
										{
											table.firstChild.nextSibling.firstChild.innerHTML=\"\";
										}
										else
										{
											table.firstChild.nextSibling.firstChild.innerHTML='$msr_rule_td0';
										}
									}

                                    function remove_filter()
                                    {
                                        var table=document.getElementById('msr_rules_table').firstChild; //table-tbody
										var lastrow = document.getElementById('msr_addrule_link'); //last row with 'Add Rule' link
										while(lastrow.previousSibling && table.childNodes.length > 3)
                                        {
                                            msr_filter_remove_rule(lastrow.previousSibling);
                                        }
                                        for(i=1;i<4;i++)
										{
                                            lastrow.previousSibling.childNodes[i].innerHTML = msr_rules_td[i];
                                        }
                                    }

                                    function show_filter_form(show)
                                    {
                                        var show_style = show ? \"\" : \"none\";

                                        if(document.getElementById(\"msr_rules_table\"))
                                            document.getElementById(\"msr_rules_table\").style.display=show_style;

                                        if(document.getElementById(\"tr_filter_form\"))
                                            document.getElementById(\"tr_filter_form\").style.display=show_style;

                                        doOnresize();

                                        return false;
                                    }
									</script>";

							return $result;
						} //function _prepareJS()

						//preparing JS functions for adding new row
						$result .= _prepareJS();

						//flag showing that there are filters after submit
                        if(isset($_REQUEST['msr_rule_column']) && is_array($_REQUEST['msr_rule_column']) && count($_REQUEST['msr_rule_column']))
                        {
                            $has_columns = false;

                            foreach($_REQUEST['msr_rule_column'] as $v)
                            {
                                $has_columns = $has_columns || strlen($v)>0;
                            }

                            $msr_has_filters = $has_columns;
                        }
                        else
                        {
                            $msr_has_filters = false;
                        }

						//output table with filter rules
						$result .= "<table align='center' ".((!$msr_has_filters&&!$openfilter)?"style='display:none;'":"")." id='msr_rules_table'><tbody>";
						$result .= "<tr><td colspan='5' class='MSR-filter-header' style='background-color:".Preferences('COLOR')."'>"._("FILTER RULES")."</td></tr>";
						if($msr_has_filters)
						{
							//loop through filter rules
							foreach($_REQUEST['msr_rule_column'] as $msr_key=>$msr_value)
							{
								$result .= "<tr>";
								if(count($_REQUEST['msr_rule_column'])>1)
									$result .= "<td>$msr_rule_td0</td>";
								else
									$result .= "<td></td>";
								$result .= "<td>".SelectInput($msr_value,'msr_rule_column[]','',$column_names,' ','', false, null, false)."</td>";
								$result .= "<td>".SelectInput($_REQUEST['msr_rule_op'][$msr_key],'msr_rule_op[]','',$operators,' ','', false, null, false)."</td>";
								$result .= "<td><input type=text name=msr_rule_value[] size=20 value='".$_REQUEST['msr_rule_value'][$msr_key]."' /></td>";
								if($msr_key==count($_REQUEST['msr_rule_column'])-1)
									$result .= "<td>$msr_search_btn</td>"; //print submit button for last row
								else
									//echo "<td><center><small>And</small></center></td>"; //otherwise print 'And'
									$result .= "<td>".SelectInput($_REQUEST['msr_rule_cond'][$msr_key], 'msr_rule_cond[]',"",$conditions, false,"", false, null, false)."</td>";
								$result .= "</tr>";
							}
						}
						else
						{
							$result .= "<tr><td></td><td>$msr_rule_td1</td><td>$msr_rule_td2</td><td>$msr_rule_td3</td><td>$msr_search_btn</td></tr>";
						}
						$result .= "<tr id='msr_addrule_link'><td nowrap><a href='javascript:;' onclick='msr_filter_add_rule();'>"._("Add Rule")."</a></td><td><a href='javascript:;' onclick='remove_filter();'>"._("Clear Rules")."</a></td><td><a style='display:none;' href='javascript:;' onclick='show_filter_form(false);'>"._("Hide Filter")."</a></td></tr>"; //
						$result .= "</tbody></table><br />";

            			            $_SYSTEM['AllowEdit'] = $AllowEditTemp;
		                            return $result;
					} //function _drawSearchForm()
				}

				echo "<TABLE cellspacing=0 cellpadding=0 border=0 width=100%>";
				echo "<TR>";
				echo "<TD width=100%>";
				echo "<TABLE cellspacing=0 cellpadding=0 border=0 width=100%>";
				if($options['filter'])
		                {
		                    echo "<tr id=tr_filter_form><td colspan=3 align=center>"._drawSearchForm($column_names, $options['openfilter'])."</td></tr>";
		                }
		                echo "<TR>";

				if(!$options['search'] && !$options['filter'] && $options['middle'])
					//echo "<TD align=" . ALIGN_LEFT . " valign=bottom width=100 nowrap>";

				echo "<TD align=".ALIGN_LEFT." valign=bottom width=200 nowrap>";//������� �������� �� 200, ������ ��� � Grades->Grading Scales Settings ������������ �����. 
				else
					echo "<TD style='text-indent:10px;' align=" . ALIGN_LEFT . " valign=bottom width=".(!$options['middle']?"50%":"33%")." nowrap>";

				if($singular && $plural && $options['count'])
				{
					if($display_count > 0)
					    if($link['add']['link'])
						//echo "<b>$plural:&nbsp;$display_count</b> <td align=right>".button('add',$link['add']['title'],$link['add']['link'])."</td>";
						echo "<b>$plural:&nbsp;$display_count</b>".button('add',$link['add']['title'],$link['add']['link']);
					    else
						echo "<b>$plural:&nbsp;$display_count</b> &nbsp; &nbsp;";
//					elseif($display_count==1)
//						echo "<b>1&nbsp;$singular</b> &nbsp; &nbsp;";
					if($where_message)
						echo '<BR>'.$where_message;
				}
				if($options['save'] && !isset($_REQUEST['CREATEPDF']) && $result_count > 0)
					echo "<A HREF=$PHP_tmp_SELF&$addition&Gridoutput_store=1&CREATEPDF=true><IMG SRC=".$_SYSTEM['uri']."images/download.png border=0 vspace=0 hspace=0></A>";
				echo "</TD>";
				if($options['middle'])
					echo '<TD align=left '.($options['search']?'width=33% ':'').'valign=bottom>'.$options['middle'].'</TD>';
				$colspan = 1;
				/*
				if(!isset($_REQUEST['CREATEPDF']) && $options['search'])
				{
					$tmp_REQUEST = $_REQUEST;
					unset($tmp_REQUEST['GridSearchIn']);
					unset($tmp_REQUEST['page']);
					echo "<TD align=".ALIGN_RIGHT." valign=bottom>";
					if($options['filter'])
					{
						echo "<input type=submit name='openfilter' value='"._('Filter')."' onclick='return show_filter_form(true);' />";
					}
					echo "<INPUT type=text id=GridSearchIn name=GridSearchIn value='".(($_REQUEST['GridSearchIn'] && $_REQUEST['GridSearchIn']!=_('Search'))?$_REQUEST['GridSearchIn']:_('Search').'\' style=\'color:BBBBBB\'')."' onfocus='if(this.value==\""._('Search')."\") this.value=\"\"; this.style.color=\"000000\";' onblur='if(this.value==\"\") {this.value=\""._('Search')."\"; this.style.color=\"BBBBBB\";}' onkeypress='if(event.keyCode==13){document.location.href=\"".SetRequestOptions($tmp_REQUEST)."&GridSearchIn=\"+this.value; return false;} '></TD>";
					$colspan++;
				}*/
				echo "</TR></TABLE>";
				echo "</TD></TR>";
				if($options['middle'])
					echo '<TR><TD width=100% height=3 bgcolor="#'.Preferences('HIGHLIGHT').'" colspan='.($colspan+1).'>  </TD></TR>';
				echo "<TR><TD>";
			}
			elseif(!$_REQUEST['CREATEPDF'])
			{
				echo "<TABLE cellspacing=0 cellpadding=0 border=0 width=100% $s_class_table >";
				echo "<TR><TD>";
			}
			// END SEARCH BOX ----

			$rollover_highlight = Preferences('ROLLOVER_HIGHLIGHT');
			if(!$_REQUEST['CREATEPDF'] && !$is_IE)
				echo "<script>
	                    function hilite(obj)
	                    {
		                    if(typeof obj == 'object')
		                            obj.className+=' hilite1'
		                    else
		                            document.getElementById(obj).className+=' hilite1';
    		            };
	                    function unlite(obj)
	                    {
		                    if(typeof obj == 'object')
		                            obj.className=obj.className.replace(/hilite1/g,'');
		                    else
		                            document.getElementById(obj).className=document.getElementById(obj).className.replace(/hilite1/g,'');
	                    }</script>";

			// SHADOW
			if(!isset($_REQUEST['CREATEPDF']))
			{
				echo "<TABLE width=100% cellpadding=0 cellspacing=0 border=0 $s_class_table><TR><TD valign=top>";
				$print_extra = ' border=0';
			}
			elseif($options['split_pages']===true) // this causes the report to split between pages horizontally
				$print_extra = " rules=cols border=1 bordercolor='#DDDDDD' maintable=1";
			else
				$print_extra = " rules=cols border=1 bordercolor='#DDDDDD'";

			// cellspacing = 0
			if($options['width'])
 				echo "<TABLE id=GridOutput_header_row_table cellpadding=" . $options['cellpadding'] . $print_extra . " cellspacing=0 width=" . $options['width'] . "% $s_class_table>";
			else
				echo "<TABLE id=GridOutput_header_row_table cellpadding=" . $options['cellpadding'] . $print_extra . " cellspacing=0 width=100% $s_class_table>";
			if(!isset($_REQUEST['CREATEPDF']) && ($stop-$start)>10)
				echo '<THEAD>';
			if(!isset($_REQUEST['CREATEPDF']))
				echo "<TR id=GridOutput_header_row>";
                                $column_names_temp = $column_names;
        //print_r($column_names);
                                foreach($column_names as $key=>$value)
                                {
                                    if(is_array($value))
                                    {
                                            $color_head_td[$key] = $value['color_head_td'];
                                            $column_names[$key] = $value['title'];
                                    }
                                    else
                                    {
                                        //$column_names[$key] = $column_names[$key]['title'];
                                        $color_head_td[$key] = NULL;
                                    }
                                }
                                
			$i =1;
			if($remove && !isset($_REQUEST['CREATEPDF']) && $result_count!=0)
			{
				echo "<TD ".$s_class_header_field."><A class=column_heading> &nbsp;</A>";
				if(!$_SYSTEM['GO'])
					echo "<DIV id=GridScalex$i style='position: relative;'></DIV>";
				echo "</TD>";
				$i++;
			}
			elseif($open && !isset($_REQUEST['CREATEPDF']) && $result_count!=0)
			{
				echo "<TD ".$s_class_header_field."><A class=column_heading> &nbsp;</A>";
				if(!$_SYSTEM['GO'])
					echo "<DIV id=GridScalex$i style='position: relative;'></DIV>";
				echo "</TD>";
				$i++;
			}
			
			if($result_count!=0 && $cols && !isset($_REQUEST['CREATEPDF']))
			{
				foreach($column_names as $key=>$value)
				{
					//make sort
					if($_REQUEST['GridSortingBy'] == $key)
						$direction = -1 * $_REQUEST['GridOrder'];
					else
						$direction = 1;

					if($options['widths'][$key])
						$width = ' width="'.$options['widths'][$key].'"';
					else
						$width = '';
                                        if($color_head_td[$key]=='')
                                		echo "<TD ".$width." ".$s_class_header_field.' id="thead'.$i.'">';
                                        else
                                        {
                                        	if(!$_SYSTEM['go_td_style_image'])
	                        			$go_td_style_image = "style=\"background:url('images/gridout_head.png') repeat-x scroll left top #".$color_head_td[$key].";\"";
	                        		else
	                        			$go_td_style_image = "style=\"background:url('".$_SYSTEM['go_td_style_image']."images/gridout_head.png') repeat-x scroll left top #".$color_head_td[$key].";\"";
                                        	echo "<TD ".$width." ".$s_class_header_field." $go_td_style_image >";
                                                //echo "<TD ".$width . $s_class_header_field .' style="background-image:none;background-color:#' . $color_head_td[$key] . ';">';
                                        	//echo "<TD ".$width." ".$s_class_header_field." style=\"background:url('images/gridout_head.png') repeat-x scroll left top #".$color_head_td[$key].";\">";
                                        }
					if(!$_SYSTEM['GO'])
						echo "<DIV id=GridScalex$i style='position: relative;'></DIV>";
					if($value)
					{
						echo "<A ";
						if($options['sort'] && !$_REQUEST['deny_sort'])
							echo "HREF=$PHP_tmp_SELF&page=$_REQUEST[page]&GridSortingBy=$key&GridOrder=$direction&GridSearchIn=".urlencode($_REQUEST['GridSearchIn']);
						echo " class=column_heading><b>$value</b></A>";//showing title of category
						if($i==1)
						echo "<DIV id=GridScaley0 style='position: relative;'></DIV>";
					}
					else
						echo ' &nbsp; ';
					echo "</TD>";
					$i++;
				}
                                $column_names = $column_names_temp;
				//echo '<TD width=0><DIV id=LO'.$i.'></DIV></TD>';
				echo "</TR>";
			}

			$color = Preferences('HIGHLIGHT_BACKGROUND');
		//	$color = 'F8F8F9';
			//style="height: 300px; overflow: auto; padding-right: 16px;"
			if(!isset($_REQUEST['CREATEPDF']) && ($stop-$start)>10)
				echo '</THEAD><TBODY>';

			$first_col = key($column_names);
//			echo $start."-".$stop;
//			echo $count."-".$repeat_headers;
//			die();
			for($i=$start;$i<=$stop;$i++)
			{
				$item = $result[$i];
                                if($result[$i]['LOG_FIELD0'])
                                {
                                    $add_array[$i] = $result[$i]['LOG_FIELD0'];
                                    unset($result[$i]['LOG_FIELD0']);
                                }
				if(isset($_REQUEST['CREATEPDF']) && $options['print'] && count($item))
				{
					foreach($item as $key=>$value)
					{
						// $value = eregi_replace('<SELECT.*SELECTED\>([^<]+)<.*</SELECT\>','\\1',$value);
						// $value = eregi_replace('<SELECT.*</SELECT\>','',$value);

						//	if(strpos($value,'GridOutput_fieldint')===false)
						//		$item[$key] = str_replace(' ','&nbsp;',ereg_replace("<div onclick='[^']+'>",'',$value));
						//	else
							//$item[$key] = ereg_replace("<div onclick='[^']+'>",'',$value);
							$item[$key] = $value;
					}
				}
				
				if($item['row_color'])
					$color = $item['row_color'];
				elseif($color==Preferences('HIGHLIGHT_BACKGROUND'))
//				elseif($color=='F8F8F9')
					$color = $side_color;
				else
					$color = Preferences('HIGHLIGHT_BACKGROUND');
//					$color = 'F8F8F9';
					//$color = 'EDF3FE';
				if(isset($_REQUEST['CREATEPDF']) && $count%$repeat_headers==0)
				{
					if($count!=0)
					{
						echo "</TABLE><TABLE cellpadding=" . $options['cellpadding'] . " cellspacing=0 width=100% $s_class_table>";
						echo "<!-- NEW PAGE -->";
					}
					echo "<TR repeat=1>";
					if($remove && !isset($_REQUEST['CREATEPDF']))
						echo "<TD bgcolor=#" . $header_color . $width . " " . $s_class_header_field . "><A class=column_heading> &nbsp;</A></TD>";
//						echo "<TD bgcolor=#" . $header_color . "width=50%" . " " . $s_class_header_field . "><A class=column_heading> &nbsp;</A></TD>";
					if($cols)
					{
						//reset($column_names);
						//$columns_first_key = key($column_names);
						foreach($column_names as $key=>$value)
						{
							if($options['widths'][$key])
								$width = ' width="'.$options['widths'][$key].'"';
							else
								$width = '';
							//draw header hardcode
							if($width == 'width="115%"') $width='width="50%"';
//							$width='$width="50%"';
							$width = str_replace('115','50',$width);
							if($stop>25 && !$options['header_row_height'])
								echo "<TD bgcolor=#".$header_color.$width." ".$s_class_header_field." ><FONT color=#ffffff size=".$options['headersize']."><b>".$value."</b></FONT></TD>";
							else
								echo "<TD bgcolor=#".$header_color.$width." ".$s_class_header_field." ><FONT color=#ffffff size=".$options['headersize']."><b>".$value."</b></FONT></TD>";
						}
					}
					echo "</TR>";
				}
				if($count==0)
					$count = $br;

				$count++;
				$rollover_highlight = Preferences('ROLLOVER_HIGHLIGHT');

				if(!$_REQUEST['CREATEPDF'] && $stop>1 && !$is_IE)
					$onmouseover = " onmouseover='hilite(this);".(($options['yscroll'])?"hilite(\"GridScaley_floatingrow$count\");":"")."' onmouseout='unlite(this);".(($options['yscroll'])?"unlite(\"GridScaley_floatingrow$count\");":"")."'";
				else
					$onmouseover = '';
				if($options['onclick'])
					$onmouseover.= " onclick='".$options['onclick']."'";
				echo "<TR bgcolor=#$color id=GridScaley".$_SYSTEM['GO']."_row".$count.$onmouseover.">";
				//start make list, be careful to use $link['remove'] or ['open']
				if(($remove || $open) && !isset($_REQUEST['CREATEPDF']))
				{
					echo "<TD style='border-width:1px;border-style:none inset inset inset;border-color:".Preferences('HIGHLIGHT').";'".$s_class_lo_field . "'>";
					if($remove && !isset($_REQUEST['CREATEPDF']))
					{
						$button_title = $link['remove']['title'];
						$button_link = $link['remove']['link'];
						if(count($link['remove']['variables']))
						{
							foreach($link['remove']['variables'] as $var=>$val)
								$button_link .= "&$var=" . urlencode($item[$val]);
						}
						echo button('remove',$button_title,$button_link)."&nbsp;&nbsp;&nbsp;&nbsp;";
					}
					if($open && !isset($_REQUEST['CREATEPDF']))
					{
						$button_title = $link['open']['title'];
						$button_link = $link['open']['link'];
						if(count($link['open']['variables']))
						{
							foreach($link['open']['variables'] as $var=>$val)
								$button_link .= "&$var=" . urlencode($item[$val]);
						}
						echo button('open',$button_title,$button_link)." ";
					}				
					echo "</TD>";
				}
				if($cols)
				{
					foreach($column_names as $key=>$value)
					{
						$print_td = true;
                				if($options['rowspan'])
				                {
            						$rowspan = in_array($key,$options['rowspan']['valcol']) ?"rowspan='".$rowspan_cnt[$item[$options['rowspan']['idcol']]]."'":"";
		            			        if(!strip_tags($item[$options['rowspan']['idcol']]) && in_array($key,$options['rowspan']['valcol']))
		                			{
				                        	$print_td = false;
							}
						}else{
							$rowspan = '';
						}
						if($link[$key] && !isset($_REQUEST['CREATEPDF']))
						{
					    	    if($link[$key]['js']===true)
						    {
							$alink = "<A HREF=# onclick='window.open(\"{$link[$key]['link']}";
							if(count($link[$key]['variables']))
							{
								foreach($link[$key]['variables'] as $var=>$val)
									$alink .= "&$var=".urlencode($item[$val]);
							}
							$alink .= "\",\"\",\"scrollbars=yes,resizable=yes,width=875,height=400\");return false;'";
							if($link[$key]['extra'])
								$alink .= ' '.$link[$key]['extra'];
							$alink .= ">";
						    }
						    else
						    {
							$alink = "<A HREF={$link[$key]['link']}";
							if(is_array($link[$key]['variables']))
                            //if(count($link[$key]['variables']))
							{
								foreach($link[$key]['variables'] as $var=>$val)
									$alink .= "&$var=".urlencode($item[$val]);
							}
							if($link[$key]['extra'])
								$alink .= ' '.$link[$key]['extra'];
							$alink .= " ".(($_REQUEST['servicemod']=='mod_apply/AppEnrollment.php')?"target=\"_blank\"":"")." class=\"Grid_hlink\" id=\"link_".$_SYSTEM['GO']."_$i\">";
						    }
			                            //$first_col = key($column_names);
						    echo "<TD style='border-width:1px;border-style:none inset inset inset;border-color:".Preferences('HIGHLIGHT').";' " . $s_class_lo_field . " $rowspan height=26 NOWRAP>";
						    if($count==1 && $key==$first_col && $options['yscroll'])
						    	echo '<DIV id=GridScaley'.($count-$br).' style="position:relative;">';
							
							if($color==Preferences('HIGHLIGHT'))
							{
								echo "<TABLE width=100% " . $s_class_inner_lo_field . "><TR><TD width=100%>";
								echo $alink.'<font color=#ffffff>';
							}
							else
								echo $alink;
							echo $item[$key];
							if($color==Preferences('HIGHLIGHT'))
							{
								echo '</font>';
								if($_SYSTEM['direction']=='RTL')
									echo "</A></TD><TD align=".ALIGN_RIGHT. ">".$alink."<IMG SRC=images/arrow_left.gif border=0></A></TD></TR></TABLE>";
								else
							    		echo "</A></TD><TD align=".ALIGN_RIGHT.">".$alink."<IMG SRC=images/arrow_right.gif height=12 border=0></A></TD></TR></TABLE>";
							}
							else
							{
							    //echo '</font>';
							    if(!isset($item[$key]))
							    	    echo '***';
							    echo "</A>";
							}
							if($count==1 && $key==$first_col && $options['yscroll'])
							    echo '</DIV>';
	    	    					echo "</TD>";
						}//end !createpdf
						else
						{
							if(strpos($item[$key],'GridOutput_fieldint')===false && isset($_REQUEST['CREATEPDF']) && !$options['wrap'])
							{
								$nowrap = '';
								$this_class_lo_field = '';
							}
							elseif(strpos($item[$key],'GridOutput_fieldint')!==false || $options['wrap'])
							{
								$nowrap = '';
								$this_class_lo_field = "class='GridOutput_fieldstyle_wrap'";
							}
							else
							{
								$nowrap = '';
								$this_class_lo_field = "class='GridOutput_fieldstyle'";
							}
							//if($_REQUEST['CREATEPDF'] && $key!=$columns_first_key)
							//	echo '<TD width=2 bgcolor=#CCCCCC><spacer width=2></TD>';

			                                if($print_td)
			                                {
// 				                           var_dump($item);
//                           					 echo'<br>';
                                                            
			                                    echo "<TD style='border-width:1px;border-style:none inset inset inset;border-color:".Preferences('HIGHLIGHT').";' ".$this_class_lo_field.$nowrap." $rowspan height=26>";
			                                    if($key==$first_col && !isset($_REQUEST['CREATEPDF']))
			                                        echo '<DIV id=GridScaley'.($count-$br).' height=100% style="position: relative;">';
			                                    if($color==Preferences('HIGHLIGHT'))
			                                        echo '<font color=white >';
			                                    elseif($options['detailsize'])
			                                        echo '<font size='.$options['detailsize'].'>';
				                                // this breaks the schedule for some reason
				                                //$item[$key] = ereg_replace('<!--.*-->','',$item[$key]);
                            				    $item[$key] = preg_replace('@<![\s\S]*?--[ \t\n\r]*>@','',$item[$key]);
                                                            
							    echo $item[$key];
			                                    if(!$item[$key])
                        				        echo '&nbsp; ';
				                            if($color==Preferences('HIGHLIGHT') || $options['detailsize'])
			                                        echo '</font>';
			                                    if($key==$first_col && !isset($_REQUEST['CREATEPDF']))
				                                echo '<DIV>';
			                                    echo "</TD>";
			                                }
						}
					}
				}
				echo "</TR>";
			}
			if($result_count!=0)
			{
				if($remove && !isset($_REQUEST['CREATEPDF']))
					$cols++;
                                if($link['count']['html'] && $cols)
                                {
                                        if($count%2)
    						$color = Preferences('HIGHLIGHT_BACKGROUND');
					else
						$color = $side_color;

					echo "<TR  " . $s_class_lo_field . ">";
                                        echo "<TD " . $s_class_lo_field . "><b>" . _('Total') . "</b></TD>";
                                        $i=0;
                                        if($hardcount == 'log_fields'){
                                            unset($hardcount);
                                            $count_key = 0;
                                        }
                                        else
                                            $count_key = 1;

					foreach($column_names as $key=>$value)
					{
                                            
                                            $i++;
						if($key<>'SPZ_TITLE' && $i>=$count_key)echo "<TD " . $s_class_lo_field . "><b>".(($hardcount[$key])?((intval($link['count']['html'][$hardcount[$key]['TO']]) > 0)?(round($link['count']['html'][$hardcount[$key]['FROM']]/$link['count']['html'][$hardcount[$key]['TO']],4)):'0'):$link['count']['html'][$key]) . "</b></TD>";//bgcolor=#C4C4C4// (($link['count']['html'][$key])?$link['count']['html'][$key]:'&nbsp;')
					}
					echo "</TR>";
                                }
                                
				//showing plus-href - add_button
				if($link['add']['link'] && !isset($_REQUEST['CREATEPDF']))
					echo "<TR><TD colspan=$cols align=" .ALIGN_LEFT. " bgcolor=#ffffff " . $s_class_lo_field . ">" . button('add',$link['add']['title'],$link['add']['link']) . "</TD></TR>";
				elseif($link['add']['span'] && !isset($_REQUEST['CREATEPDF']))
					echo "<TR><TD colspan=$cols align=" .ALIGN_LEFT. " bgcolor=#ffffff " . $s_class_lo_field . ">" . button('add').$link['add']['span'] . "</TD></TR>";
				elseif($link['add']['html'] && $cols && !isset($_REQUEST['CREATEPDF']))
				{
					if($count%2)
					//	$color = 'F8F8F9';
						$color = Preferences('HIGHLIGHT_BACKGROUND');
					else
						$color = $side_color;

					echo "<TR bgcolor=#$color " . $s_class_lo_field . ">";
					if($remove && !isset($_REQUEST['CREATEPDF']) && $link['add']['html']['remove'])
						echo "<TD bgcolor=#$color " . $s_class_lo_field . ">" . $link['add']['html']['remove'] . "</TD>";
					elseif($remove && !isset($_REQUEST['CREATEPDF']))
						echo "<TD bgcolor=#$color " . $s_class_lo_field . ">" . button('add','') . "</TD>";

					foreach($column_names as $key=>$value)
					{
						//if($_REQUEST['CREATEPDF'] && $key!=$columns_first_key)
						//	echo '<TD width=2 bgcolor=#CCCCCC><spacer width=2 ></TD>';
						echo "<TD bgcolor=#$color " . $s_class_lo_field . ">" . $link['add']['html'][$key] . "</TD>";
					}
					echo "</TR>";
				}
				
				if(!isset($_REQUEST['CREATEPDF']) && ($stop-$start)>10)
					echo '</TBODY>';
				echo "</TABLE>";
				// SHADOW
				
				if(!isset($_REQUEST['CREATEPDF'])) // SHOULD THIS BE ALIGNED TO THE RIGHT IF LOCALIZED TO A RTL LANGUAGE?
				{
//					if($cols==1)
//						echo "\n\t\t</TD>\n\t</TR>\n\t<TR>\n\t\t<TD height=6 align=right>\n\t\t\t<DIV id=GridScalex".(count($column_names)+(($result_count!=0 && $cols && !isset($_REQUEST['CREATEPDF']))?1:0)+(($remove && !isset($_REQUEST['CREATEPDF']))?1:0))." style='width:0; position: relative; height:0;'></DIV>\n\t\t</TD>\n\t</TR>\n</TABLE>";
//					else
						echo "</TD></TR><TR><TD background=".$_SYSTEM['uri']."themes/".Preferences('HIGHLIGHT_MENU')."/gline.png height=4 align=right style='border-width:1px;border-style:solid none none none;'><DIV id=GridScalex".(count($column_names)+(($result_count!=0 && $cols && !isset($_REQUEST['CREATEPDF']))?1:0)+(($remove && !isset($_REQUEST['CREATEPDF']))?1:0))." style='width:0; position: relative; height:0;'></DIV></TD></TR></TABLE>";
				}
				if($where_message || ($singular && $plural) || !isset($_REQUEST['CREATEPDF']))
				{
					echo "</TD></TR>";
					echo "</TABLE>";
				}

				if($options['center'])
					echo '</CENTER>';
			}

		// END PRINT THE LIST ---
		}
		
		if($result_count==0)
		{
			echo "</TD></TR></TABLE>";
			$column_names_temp = $column_names;
                        foreach($column_names as $key=>$value)
                        {
                            if(is_array($value))
                            {
                                    $color_head_td[$key] = $value['color_head_td'];
                                    $column_names[$key] = $value['title'];
                            }
                            else
                            {
                                //$column_names[$key] = $column_names[$key]['title'];
                                $color_head_td[$key] = NULL;
                            }
                        }

			if($link['add']['link'] && !isset($_REQUEST['CREATEPDF']))
			{
				if(!$link['add']['title'])
					$link['add']['title'] = _(' add one');
				echo '<div style="padding-left:20px;padding-top:5px;">'.button('add',$link['add']['title'],$link['add']['link']).'</div>';
			}
			elseif(($link['add']['html'] || $link['add']['span']) && count($column_names) && !isset($_REQUEST['CREATEPDF']))
			{
				$color = $side_color;

				if($options['center'])
					echo '<CENTER>';
				// WIDTH=100%
				echo "<TABLE cellpadding=0 cellspacing=0 bgcolor=#".Preferences('HIGHLIGHT_BACKGROUND')." width=100% $s_table_class><TR><TD>";
				// SHADOW
				echo "<TABLE width=100% cellpadding=0 cellspacing=0 $s_table_class><TR><TD valign=top>";
				if($link['add']['html'])
				{
					echo "<TABLE id=grid_rows  cellpadding=".$options['cellpadding'] . " cellspacing=0 width=100% $s_table_class><TR><TD ".$s_class_header_field."><A class=column_heading> &nbsp;</A></TD>";
					foreach($column_names as $key=>$value)
					{
                                            if($color_head_td[$key]=='')
                                                echo "<TD ".$width . " " . $s_class_header_field. "><A class=column_heading><b>".$value."</b></A></TD>";
                                            else
                                            {
                                                //echo "<TD ".$width . " " . $s_class_header_field ." style=\"background-image:none;background-color:#" . $color_head_td[$key] . ";\"><A class=column_heading><b>" . $value . "</b></A></TD>";
                                                echo "<TD ".$width . " " . $s_class_header_field ." style=\"background:url('images/gridout_head.png') repeat-x scroll left top #" . $color_head_td[$key] . ";\"><A class=column_heading><b>";
                                                echo $value;
                                                echo "</b></A></TD>";
                                            }
					}
					echo "</TR>";

					echo "<TR bgcolor=#$color>";

					if($link['add']['html']['remove'])
						echo "<TD bgcolor=#$color " . $s_class_lo_field . ">".$link['add']['html']['remove']."</TD>";
					else
						echo "<TD bgcolor=#$color " . $s_class_lo_field . ">" . button('add') . "</TD>";

					foreach($column_names as $key=>$value)
					{
						echo "<TD bgcolor=#$color " . $s_class_lo_field . ">" . $link['add']['html'][$key] . "</TD>";
					}
					echo "</TR>";
					echo "</TABLE>";
				}
				elseif($link['add']['span'] && !isset($_REQUEST['CREATEPDF']))
					echo "<TABLE><TR><TD align=" . ALIGN_LEFT . " " . $s_class_lo_field . ">" . button('add') . $link['add']['span'] . "</TD></TR></TABLE>";

				// SHADOW
				echo "</TD></TR><TR><TD background='themes/".Preferences('HIGHLIGHT_MENU')."/gline.png' height=3></TD></TR></TABLE>";
				echo "</TD></TR></TABLE>";
				if($options['center'])
					echo '</CENTER>';
			}
		}
		if($result_count!=0 && !isset($_REQUEST['CREATEPDF']))
		{
			if($options['yscroll'])
			{
                //
                // This block of code builds table columns header which moves right with $options[yscroll]
                //
                $i = 1;
                echo '<div id="GridScaley_layer_header" style="position: absolute; visibility:hidden; top: 0; left: 0; margin:0px 0px 0px 0px; padding:0px;">';
                //border=1 fix for IE8.
                echo "<TABLE id='GridScaley_layer_header_table' cellpadding=" . $options['cellpadding'] . " cellspacing=0 border=1><TR>";
				if($_REQUEST['GridSortingBy'] == $key)
                    $direction = -1 * $_REQUEST['GridOrder'];
                else
                    $direction = 1;

                echo "<TD $s_class_header_field ".'id=GO_column_layer_header'.$i."><A ";
                if($options['sort'])
                    echo "HREF=$PHP_tmp_SELF&page=$_REQUEST[page]&GridSortingBy=$key&GridOrder=$direction&GridSearchIn=".urlencode($_REQUEST['GridSearchIn']);
                echo " class=column_heading><b>" . str_replace('controller','top_controller',$column_names[$first_col]) . "</b></A></TD>";
                $i++;
                if($options['yscroll_numcols'] && $options['yscroll_numcols']>1)
						$keys = array_keys($column_names);
                if($options['yscroll_numcols'] && $options['yscroll_numcols']>1)
                {
                    for($ii=1;$ii<$options['yscroll_numcols'];$ii++)
                    {
                        if($_REQUEST['GridSortingBy'] == $key)
                            $direction = -1 * $_REQUEST['GridOrder'];
                        else
                            $direction = 1;

			echo "<TD $s_class_header_field ".'id=GO_column_layer_header'.$i."><A ";
                        if($options['sort'])
				echo "HREF=$PHP_tmp_SELF&page=$_REQUEST[page]&GridSortingBy=$key&GridOrder=$direction&GridSearchIn=".urlencode($_REQUEST['GridSearchIn']);
			echo " class=column_heading><b>".str_replace('controller','top_controller',$column_names[$keys[$ii]])."</b></A></TD>";
                        $i++;
                    }
                }
                echo "</TR></TABLE></div>";

                //
                // This block of code used to build table header that moves right for both xscroll and yscroll
                //

                $i = 1;
                echo '<div id="GridScaley_layer_header2" style="position: absolute; z-index:10; visibility:hidden; top: 0; left: 0; margin:0px 0px 0px 0px; padding:0px;">';
                //border=1 fix for IE8.
                echo "<TABLE id='GridScaley_layer_header2_table' cellpadding=" . $options['cellpadding'] . " cellspacing=0 border=1><TR>";
				if($_REQUEST['GridSortingBy'] == $key)
                    $direction = -1 * $_REQUEST['GridOrder'];
                else
                    $direction = 1;

                echo "<TD $s_class_header_field ".'id=GO_column_layer_header2_'.$i."><A ";
                if($options['sort'])
                    echo "HREF=$PHP_tmp_SELF&page=$_REQUEST[page]&GridSortingBy=$key&GridOrder=$direction&GridSearchIn=".urlencode($_REQUEST['GridSearchIn']);
                echo " class=column_heading><b>".str_replace('controller','top_controller',$column_names[$first_col])."</b></A></TD>";
                $i++;
                if($options['yscroll_numcols'] && $options['yscroll_numcols']>1)
						$keys = array_keys($column_names);
                if($options['yscroll_numcols'] && $options['yscroll_numcols']>1)
                {
                    for($ii=1;$ii<$options['yscroll_numcols'];$ii++)
                    {
                        if($_REQUEST['GridSortingBy'] == $key)
                            $direction = -1 * $_REQUEST['GridOrder'];
                        else
                            $direction = 1;

			echo "<TD $s_class_header_field ".'id=GO_column_layer_header2_'.$i."><A ";
                        if($options['sort'])
				echo "HREF=$PHP_tmp_SELF&page=$_REQUEST[page]&GridSortingBy=$key&GridOrder=$direction&GridSearchIn=".urlencode($_REQUEST['GridSearchIn']);
			echo " class=column_heading><b>" . str_replace('controller','top_controller',$column_names[$keys[$ii]]) . "</b></A></TD>";
                        $i++;
                    }
                }
                echo "</TR>";
                echo "</TABLE></div>";

                //
                // GO Y-axis floating
                //
		// if here put 47px IE8 will works fine. need to find the problem
                echo '<div id="GridScaley_layer" height='.(count($result)*26).' style="position: absolute; top: 0; left: 0; visibility:hidden;margin:0px 0px 0px 0px; padding:0px;">';
				echo "<TABLE cellpadding=".$options['cellpadding']." height=".(count($result)*26)." cellspacing=0 border=0 id=GridScaley_table $s_table_class><TBODY>";
//                echo '<div id="GridScaley_layer"  style="position: absolute; top: 0; left: 0; height:'.(count($result)*26).'px; visibility:hidden;margin:0px 0px 0px 0px; padding:0px;">';
//				echo "<TABLE cellpadding=".$options['cellpadding']."  cellspacing=0 border=0 id=GridScaley_table $s_table_class style=\"height:".(count($result)*26+47)."px;\"><TBODY>";

				$i = 1;

				if($cols && !isset($_REQUEST['CREATEPDF']))
				{
					if($options['yscroll_numcols'] && $options['yscroll_numcols']>1)
						$keys = array_keys($column_names);
				//	$color = 'F8F8F9';
					$color = Preferences('HIGHLIGHT_BACKGROUND');
					foreach($result as $item)
					{
						if($item['row_color'])
							$color = $item['row_color'];
//						elseif($color=='F8F8F9')
						elseif($color==Preferences('HIGHLIGHT_BACKGROUND'))
							$color = $side_color;
						else
							$color = Preferences('HIGHLIGHT_BACKGROUND');
//							$color = 'F8F8F9';
						echo "<TR bgcolor=#$color id='GridScaley_floatingrow$i'><TD " . $s_class_lo_field . " id=\"ltr".$i."_1\"  height=27>";
						if($color==Preferences('HIGHLIGHT'))
							echo '<font color=white>';
						echo $item[$first_col];
						if(!$item[$first_col])
							echo '&nbsp;';
						if($color==Preferences('HIGHLIGHT'))
							echo '</font>';
						echo "</TD>";
                        
						if($options['yscroll_numcols'] && $options['yscroll_numcols']>1)
						{
							for($ii=1;$ii<$options['yscroll_numcols'];$ii++)
							{
								echo "<TD ".$s_class_lo_field." id=\"ltr".$i."_".($ii+1)."\" height=27>";
								if($color==Preferences('HIGHLIGHT'))
									echo '<font color=white>';
								echo $item[$keys[$ii]];
								if(!$item[$keys[$ii]])
									echo '&nbsp;';
								if($color==Preferences('HIGHLIGHT'))
									echo '</font>';
								echo '</TD>';
				                                $loy_layer_header .= "<TD>".$column_names[$keys[$ii]]."</TD>";
							}
						}
						echo "</TR>";
						$i++; 
					}
				}
				if($link['add']['html'] && $cols && !isset($_REQUEST['CREATEPDF']))
				{
					if($count%2)
				//		$color = 'F8F8F9';
						$color = Preferences('HIGHLIGHT_BACKGROUND');
					else
						$color = $side_color;

					echo "<TR bgcolor=#$color ".$s_class_lo_field.">";
					if($remove && !isset($_REQUEST['CREATEPDF']) && $link['add']['html']['remove'])
						echo "<TD bgcolor=#$color ".$s_class_lo_field.">".$link['add']['html']['remove']."</TD>";
					elseif($remove && !isset($_REQUEST['CREATEPDF']))
						echo "<TD bgcolor=#$color ".$s_class_lo_field.">".button('add','')."</TD>";
					echo "<TD bgcolor=#$color ".$s_class_lo_field.">";
						echo $link['add']['html'][$first_col];
					if(!$link['add']['html'][$first_col])
						echo '&nbsp;';
					echo "</TD>";
					if($options['yscroll_numcols'] && $options['yscroll_numcols']>1)
						$keys = array_keys($column_names);

					for($ii=1;$ii<$options['yscroll_numcols'];$ii++)
					{
						//if($_REQUEST['CREATEPDF'] && $key!=$columns_first_key)
						//	echo '<TD width=2 bgcolor=#CCCCCC><spacer width=2 ></TD>';
						echo "<TD bgcolor=#$color " . $s_class_lo_field . ">" . $link['add']['html'][$keys[$ii]] . "</TD>";
					}
					echo "</TR>";
				}
				echo "</TBODY></TABLE>";
				echo '</div>';
			}

			if(!$_SYSTEM['GO'] && $options['xscroll']!==false)
			{
				echo '<div id="GridScalex_layer" style="position: absolute; top: 0; left: 0; visibility:hidden;">';
				//border=1 fix for IE8
				echo "<TABLE cellpadding=".$options['cellpadding']." cellspacing=0 border=1 id=GridScalex_table><TR>";
				$i = 1;
				if($remove && !isset($_REQUEST['CREATEPDF']) && $result_count!=0)
				{
					echo "<TD $s_class_header_field id=GO_column$i></TD>";
					$i++;
				}
                                $column_names_temp = $column_names;
                                foreach($column_names as $key=>$value)
                                {
                                    if(is_array($value))
                                    {
                                        $color_head_td[$key] = $value['color_head_td'];
                                        $column_names[$key] = $value['title'];
                                    }
                                    else
                                    {
                                        
                                        $color_head_td[$key] = NULL;
                                    }
                                }
				if($cols && !isset($_REQUEST['CREATEPDF']))
				{
					foreach($column_names as $key=>$value)
					{
			                        if($_REQUEST['GridSortingBy'] == $key)
			                                $direction = -1 * $_REQUEST['GridOrder'];
			                        else
			                                $direction = 1;

						if($color_head_td[$key]=='')
//                                                	echo "<TD $s_class_header_field style =\"border-style: none none none none;\" border=1 ".'id=GO_column'.$i."><A ";
                                                	echo "<TD $s_class_header_field ".'id=GO_column'.$i."><A ";
                                                else
                                                {
                                                    	if(!$_SYSTEM['go_td_style_image'])
	                        				$go_td_style_image = "style=\"background:url('images/gridout_head.png') repeat-x scroll left top #".$color_head_td[$key].";\"";
		                        		else
		                        			$go_td_style_image = "style=\"background:url('".$_SYSTEM['go_td_style_image']."images/gridout_head.png') repeat-x scroll left top #".$color_head_td[$key].";\"";
	                                            	echo "<TD $s_class_header_field id=\"GO_column".$i."\" $go_td_style_image ><A ";
//                                                        echo "<TD $s_class_header_field id=\"GO_column".$i."\" style=\"background:url('images/gridout_head.png') repeat-x scroll left top #".$color_head_td[$key].";\"><A ";
                                                }
			                        if($options['sort'])
							echo "HREF=$PHP_tmp_SELF&page=$_REQUEST[page]&GridSortingBy=$key&GridOrder=$direction&GridSearchIn=".urlencode($_REQUEST['GridSearchIn']);
						echo " class=column_heading><b>" . str_replace('controller','top_controller',$value) . "</b></A></TD>";
						$i++;
					}
                                        $column_names = $column_names_temp;
				}
				echo "</TR></TABLE>";
				echo '</div>';
			}

		}

	}
	$_SYSTEM['GO']++;
}

function GridoutputBuffered($result,$column_names,$singular='',$plural='',$link=false,$group=false,$options=false)
{	global $_SYSTEM;

	if(ob_get_level()>0)
	{
		$contents = ob_get_contents();
		ob_end_clean();
		$start = true;
	}
	ob_start();
	Gridoutput($result,$column_names,$singular,$plural,$link,$group,$options);
	$return = ob_get_contents();
	ob_end_clean();
	if($start)
	{
		ob_start();
		echo $contents;
	}
	return $return;
}

?>