<?php
ini_set("display_errors","1");
ini_set("display_startup_errors","1");
set_magic_quotes_runtime(0);
include("include/dbcommon.##@ext##");
header("Expires: Thu, 01 Jan 1970 00:00:01 GMT");
header("Pragma: no-cache");
header("Cache-Control: no-cache");


include("include/##@TABLE.strShortTableName s##_variables.##@ext##");
##foreach @BUILDER.Tables as @t filter @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].len##
	include("include/##@t.strShortTableName s##_settings.##@ext##");
##endfor##	

##if @BUILDER.bCreateLoginPage##
if(!@$_SESSION["UserID"])
{ 
	$_SESSION["MyURL"]=$_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
	header("Location: login.##@ext##?message=expired"); 
	return;
}
##if !IsAdminTable(@TABLE)##
if(!CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Search") && !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Add"))
{
##if @BUILDER.bDynamicPermissions##
	$adminuser=IsAdmin();
##else##
	$adminuser=false;
##endif##
	if($adminuser)
		echo "<p>".##message NO_PERMISSIONS##."<br><a href=\"admin_rights_list.##@ext##\">".##message AA_PROCEED_TO_ADMINAREA1##."</a> ".##message AA_PROCEED_TO_ADMINAREA2##."</p>";
	else
		echo "<p>".##message NO_PERMISSIONS##." <a href=\"login.##@ext##\">".##message BACK_TO_LOGIN##."</a></p>";
	exit();
}
##else##
if(!IsAdmin())
{
	echo "<p>".##message NO_PERMISSIONS##." <a href=\"login.##@ext##\">".##message BACK_TO_LOGIN##."</a></p>";
	exit();
}
##endif##
##endif##

$pageName = "list.php";

include('include/xtempl.php');
$xt = new Xtempl();

// for different modes.
$sessionPrefix=$strTableName;

//	process reqest data, fill session variables

$mode=LIST_SIMPLE;
if(postvalue("mode")=="lookup")
	$mode=LIST_LOOKUP;
$id=postvalue("id");
$xt->assign("id",$id);

if($mode==LIST_LOOKUP)
{	
	$lookupwhere="";
	$categoryfield="";
	$linkfield="";
	$lookupfield=postvalue("field");
	$lookupcontrol=postvalue("control");
	$lookupcategory=postvalue("category");
	$lookuptable=postvalue("table");
	$lookupparams="mode=lookup&id=".$id."&field=".rawurlencode($lookupfield)
		."&control=".rawurlencode($lookupcontrol)."&category=".rawurlencode($lookupcategory)
		."&table=".rawurlencode($lookuptable);

	//for mode lookup
	$sessionPrefix=$strTableName."_lookup_".$lookuptable.'_'.$lookupfield;
##foreach @BUILDER.tables as @t##
##foreach @t.arrFieldObj as @f filter @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.nLookupType==LT_LOOKUPTABLE && @f.pLookupObj.strTable==@TABLE.strDataSourceTable##
	if($lookuptable=="##@t.strShortTableName##" && $lookupfield=="##@f.strName g##") 
	{
		$linkfield = "##@f.strLinkField s##";
		$dispfield = "##@f.strDisplayField s##";
	##if @f.bUseCategory##
		$categoryfield="##@f.strCategoryFilterField s##";
	##endif##
	##if @f.EditFormatObj.pLookupObj.strWhere##
		$lookupwhere = ##@f.EditFormatObj.pLookupObj.strWhere##;
	##endif##
	}
##endfor##
##endfor##
//	determine which field should be used to select values
	$lookupSelectField="";
##foreach Fields as @f filter @f.bListPage order @f.nListPageOrder##
##if @first##	
	$lookupSelectField="##@f.strName s##";
##endif##
##endfor##
	if(AppearOnListPage($dispfield))
		$lookupSelectField=$dispfield;

	if($categoryfield)
	{
		if(!strlen(GetFullFieldName($categoryfield)))
			$categoryfield="";
	}
	if(!$categoryfield)
		$lookupcategory="";
	
}

$firsttime=postvalue("firsttime");

// clear lookup session data, while loading at first time
if ($mode==LIST_LOOKUP && $firsttime)
{
	$sessLookUpUnset = array();
	foreach($_SESSION as $key=>$value)
		if(strpos($key, "_lookup_") !== false)
			$sessLookUpUnset[] = $key;
			
	foreach($sessLookUpUnset as $key)
		unset($_SESSION[$key]);			
}


if(!count($_POST) && (!count($_GET) || count($_GET)==1 && isset($_GET["menuItemId"])))
{
	$sess_unset = array();
	foreach($_SESSION as $key=>$value)
		if(substr($key,0,strlen($strTableName)+1)==$strTableName."_" &&
			strpos(substr($key,strlen($strTableName)+1),"_")===false)
			$sess_unset[] = $key;
		
	foreach($sess_unset as $key)
		unset($_SESSION[$key]);
}

//	Before Process event
if(function_exists("BeforeProcessList"))
	BeforeProcessList($conn);

if(@$_REQUEST["a"]=="showall")
	$_SESSION[$sessionPrefix."_search"]=0;
else if(@$_REQUEST["a"]=="search")
{
	$basicSearchFieldsArr = array();
##foreach Fields as @f filter @f.bSearch order @f.nAdvSearchPageOrder##
	$basicSearchFieldsArr[]="##@f.strName s##";
##endfor##

	if (postvalue("SearchField")=="" || in_array(postvalue("SearchField"), $basicSearchFieldsArr) === true)
	{
		$_SESSION[$sessionPrefix."_searchfield"]=postvalue("SearchField");
		$_SESSION[$sessionPrefix."_searchoption"]=postvalue("SearchOption");
		$_SESSION[$sessionPrefix."_searchfor"]=postvalue("SearchFor");
		if(postvalue("SearchFor")!="" || postvalue("SearchOption")=='Empty')
			$_SESSION[$sessionPrefix."_search"]=1;
		else
			$_SESSION[$sessionPrefix."_search"]=0;
		$_SESSION[$sessionPrefix."_pagenumber"]=1;
	}
	else 
	{
		$_SESSION[$sessionPrefix."_search"]=0;
	}
	
	
}
else if(@$_REQUEST["a"]=="advsearch")
{
	$_SESSION[$sessionPrefix."_asearchnot"]=array();
	$_SESSION[$sessionPrefix."_asearchopt"]=array();
	$_SESSION[$sessionPrefix."_asearchfor"]=array();
	$_SESSION[$sessionPrefix."_asearchfor2"]=array();
	$tosearch=0;
	$asearchfield = postvalue("asearchfield");
	$_SESSION[$sessionPrefix."_asearchtype"] = postvalue("type");
	if(!$_SESSION[$sessionPrefix."_asearchtype"])
		$_SESSION[$sessionPrefix."_asearchtype"]="and";
	foreach($asearchfield as $field)
	{
		$gfield=GoodFieldName($field);
		$asopt=postvalue("asearchopt_".$gfield);
		$value1=postvalue("value_".$gfield);
		$type=postvalue("type_".$gfield);
		$value2=postvalue("value1_".$gfield);
		$not=postvalue("not_".$gfield);
		if($value1!=='' || $asopt=='Empty')
		{
			$tosearch=1;
			$_SESSION[$sessionPrefix."_asearchopt"][$field]=$asopt;
			if(!is_array($value1))
				$_SESSION[$sessionPrefix."_asearchfor"][$field]=$value1;
			else
				$_SESSION[$sessionPrefix."_asearchfor"][$field]=combinevalues($value1);
			$_SESSION[$sessionPrefix."_asearchfortype"][$field]=$type;
			if($value2!=='')
				$_SESSION[$sessionPrefix."_asearchfor2"][$field]=$value2;
			$_SESSION[$sessionPrefix."_asearchnot"][$field]=($not=="on");
		}
	}
	if($tosearch)
		$_SESSION[$sessionPrefix."_search"]=2;
	else
		$_SESSION[$sessionPrefix."_search"]=0;
	$_SESSION[$sessionPrefix."_pagenumber"]=1;
}

##if @TABLE.arrMasterTables.len##
//	process masterkey value
$mastertable=postvalue("mastertable");
if($mastertable!="")
{
	$_SESSION[$sessionPrefix."_mastertable"]=$mastertable;
//	copy keys to session
	$i=1;
	while(isset($_REQUEST["masterkey".$i]))
	{
		$_SESSION[$sessionPrefix."_masterkey".$i]=$_REQUEST["masterkey".$i];
		$i++;
	}
	if(isset($_SESSION[$sessionPrefix."_masterkey".$i]))
		unset($_SESSION[$sessionPrefix."_masterkey".$i]);
//	reset search and page number
	$_SESSION[$sessionPrefix."_search"]=0;
	$_SESSION[$sessionPrefix."_pagenumber"]=1;
}
else
	$mastertable=$_SESSION[$sessionPrefix."_mastertable"];
##endif##

##if @BUILDER.arrLanguages.len>1##
if(@$_REQUEST["language"])
	$_SESSION["language"]=@$_REQUEST["language"];

$var=GoodFieldName(mlang_getcurrentlang())."_langattrs";
$xt->assign($var,"selected");
$xt->assign("langselector_attrs","name=lang onchange=\"javascript: window.location='##@TABLE.strShortTableName hs##_list.##@ext##?language='+this.options[this.selectedIndex].value\"");
if($mode==LIST_SIMPLE)
	$xt->assign("languages_block",true);
##endif##

if(@$_REQUEST["orderby"])
	$_SESSION[$sessionPrefix."_orderby"]=@$_REQUEST["orderby"];

if(@$_REQUEST["pagesize"])
{
	$_SESSION[$sessionPrefix."_pagesize"]=@$_REQUEST["pagesize"];
	$_SESSION[$sessionPrefix."_pagenumber"]=1;
}

if(@$_REQUEST["goto"])
	$_SESSION[$sessionPrefix."_pagenumber"]=@$_REQUEST["goto"];


//	process reqest data - end

$jscode="";
$jscode_end="";
$html_begin="";
$html_end="";
##if Fields[bListPage && bUseiBox && bShowThumbnail].len##
AddJSFile("ibox");
AddCSSFile("ibox");
##else##
	##foreach @BUILDER.tables as @t filter @TABLE.arrMasterTables[strMasterTable==@t.strDataSourceTable] && @t.arrFieldObj[bListPage && bUseiBox && bShowThumbnail].len##
	##if @first## 
AddJSFile("ibox");
AddCSSFile("ibox");
	##endif##
	##endfor##
##endif##

##if @BUILDER.Tables[arrMasterTables[strMasterTable==@TABLE.strDataSourceTable && nDetailPreview==dpINLINE].len].len##
AddJSFile("detailspreview");
##endif##
	
AddJSFile("validate");

if(@$_REQUEST["language"])
	$language = $_REQUEST["language"];
// may be elseif ?
if(@$_SESSION["language"])
	$language = $_SESSION["language"];
else
	$language = 'English';

$jscode.="window.current_language='".jsreplace($language)."';\r\n";


AddJSFile("inlineedit");
if($mode==LIST_LOOKUP)
{
//	this code must be executed after the inlineedit.js is loaded
	$afteredited_handler="";
	if($lookupSelectField)
	{
		$select_onclick='$("#display_'.$lookupcontrol.'").val($("#edit"+id+"_'.GoodFieldName($dispfield).'").attr("val")); $("#'.$lookupcontrol.'").val($("#edit"+id+"_'.GoodFieldName($linkfield).'").attr("val")); if($("#'.$lookupcontrol.'")[0].onchange) $("#'.$lookupcontrol.'")[0].onchange();RemoveFlyDiv('.$id.');';
		$afteredited_handler = 'window.inlineEditing'.$id.'.afterRecordEdited = function(id) {
			var span=$("#edit"+id+"_'.GoodFieldName($lookupSelectField).'");
			
			if(!span.length)
				return;
			$(span).html("<a href=#>"+$(span).html()+"</a>"); 
			$("a:first",span).click(function() {'.$select_onclick.'});
		};';
	}

	$jscode_end.='
			window.inlineEditing'.$id.' = new InlineEditing(\'##@TABLE.strShortTableName##\',\'##@ext##\','.$id.');
			'.$afteredited_handler;
	if(strlen($lookupcategory))
	{
		$jscode_end.='window.inlineEditing'.$id.'.lookupfield = \''.jsreplace($lookupfield).'\';';
		$jscode_end.='window.inlineEditing'.$id.'.lookuptable = \''.jsreplace($lookuptable).'\';';
		$jscode_end.='window.inlineEditing'.$id.'.categoryvalue = \''.jsreplace($lookupcategory).'\';';
	}
}
##if @TABLE.bInlineAdd || @TABLE.bInlineEdit##
if($mode!=LIST_LOOKUP)
{
	$jscode_end .= 'window.inlineEditing'.$id.' = new InlineEditing(\'##@TABLE.strShortTableName##\',\'##@ext##\');';
}
##endif##	
AddJSFile("ajaxsuggest");

##if @TABLE.bInlineAdd || @TABLE.bInlineEdit##
	##foreach Fields as @f filter @f.bListPage && NeedValidation(@f)##
	##if @first##
	$jscode.="window.TEXT_INLINE_FIELD_REQUIRED='".jsreplace(##message INLINE_FIELD_REQUIRED##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_ZIPCODE='".jsreplace(##message INLINE_FIELD_ZIPCODE##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_EMAIL='".jsreplace(##message INLINE_FIELD_EMAIL##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_NUMBER='".jsreplace(##message INLINE_FIELD_NUMBER##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_CURRENCY='".jsreplace(##message INLINE_FIELD_CURRENCY##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_PHONE='".jsreplace(##message INLINE_FIELD_PHONE##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_PASSWORD1='".jsreplace(##message INLINE_FIELD_PASSWORD1##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_PASSWORD2='".jsreplace(##message INLINE_FIELD_PASSWORD2##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_STATE='".jsreplace(##message INLINE_FIELD_STATE##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_SSN='".jsreplace(##message INLINE_FIELD_SSN##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_DATE='".jsreplace(##message INLINE_FIELD_DATE##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_TIME='".jsreplace(##message INLINE_FIELD_TIME##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_CC='".jsreplace(##message INLINE_FIELD_CC##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_SSN='".jsreplace(##message INLINE_FIELD_SSN##)."';\r\n";
	##endif##	
	##endfor##
		
	##foreach Fields as @f filter (@f.bInlineEdit || @f.bInlineAdd)  && @f.bListPage && UseCalendar(@f)##
	##if @first##
//	include datepicker files
	
	$jscode.="window.TEXT_MONTH_JAN='".jsreplace(##message MONTH_JAN##)."';\r\n";
	$jscode.="window.TEXT_MONTH_FEB='".jsreplace(##message MONTH_FEB##)."';\r\n";
	$jscode.="window.TEXT_MONTH_MAR='".jsreplace(##message MONTH_MAR##)."';\r\n";
	$jscode.="window.TEXT_MONTH_APR='".jsreplace(##message MONTH_APR##)."';\r\n";
	$jscode.="window.TEXT_MONTH_MAY='".jsreplace(##message MONTH_MAY##)."';\r\n";
	$jscode.="window.TEXT_MONTH_JUN='".jsreplace(##message MONTH_JUN##)."';\r\n";
	$jscode.="window.TEXT_MONTH_JUL='".jsreplace(##message MONTH_JUL##)."';\r\n";
	$jscode.="window.TEXT_MONTH_AUG='".jsreplace(##message MONTH_AUG##)."';\r\n";
	$jscode.="window.TEXT_MONTH_SEP='".jsreplace(##message MONTH_SEP##)."';\r\n";
	$jscode.="window.TEXT_MONTH_OCT='".jsreplace(##message MONTH_OCT##)."';\r\n";
	$jscode.="window.TEXT_MONTH_NOV='".jsreplace(##message MONTH_NOV##)."';\r\n";
	$jscode.="window.TEXT_MONTH_DEC='".jsreplace(##message MONTH_DEC##)."';\r\n";
	
	$jscode.="window.TEXT_DAY_SU='".jsreplace(##message DAY_SU##)."';\r\n";
	$jscode.="window.TEXT_DAY_MO='".jsreplace(##message DAY_MO##)."';\r\n";
	$jscode.="window.TEXT_DAY_TU='".jsreplace(##message DAY_TU##)."';\r\n";
	$jscode.="window.TEXT_DAY_WE='".jsreplace(##message DAY_WE##)."';\r\n";
	$jscode.="window.TEXT_DAY_TH='".jsreplace(##message DAY_TH##)."';\r\n";
	$jscode.="window.TEXT_DAY_FR='".jsreplace(##message DAY_FR##)."';\r\n";
	$jscode.="window.TEXT_DAY_SA='".jsreplace(##message DAY_SA##)."';\r\n";
	
	$jscode.="window.TEXT_TODAY='".jsreplace(##message TODAY##)."';\r\n";
	
	AddJSFile("calendar");
	##endif##
	##endfor##
##endif##

if($mode==LIST_SIMPLE)
	$jscode.="\nbSelected=false;";
$jscode.="\nwindow.TEXT_FIRST = \"".##message FIRST##."\";".
"\nwindow.TEXT_PREVIOUS = \"".##message PREVIOUS##."\";".
"\nwindow.TEXT_NEXT = \"".##message NEXT##."\";".
"\nwindow.TEXT_LAST = \"".##message LAST##."\";".
"\nwindow.TEXT_CTRL_CLICK = \"".##message CTRL_CLICK##."\";".
"\nwindow.TEXT_PLEASE_SELECT='".jsreplace(##message PLEASE_SELECT##)."';".
"\nwindow.TEXT_SAVE='".jsreplace(##message SAVE##)."';".
"\nwindow.TEXT_CANCEL='".jsreplace(##message CANCEL##)."';".
"\nwindow.TEXT_INLINE_ERROR='".jsreplace(##message INLINE_ERROR##)."';".
"\nwindow.TEXT_PREVIEW='".jsreplace(##message PREVIEW##)."';".
"\nwindow.TEXT_HIDE='".jsreplace(##message HIDE##)."';".
"\nwindow.TEXT_LOADING='".jsreplace(##message LOADING##)."';".
"\nlocale_dateformat = ".$locale_info["LOCALE_IDATE"].";".
"\nocale_datedelimiter = \"".$locale_info["LOCALE_SDATE"]."\";".
"\nbLoading=false;\r\n";
	$jscode.="SUGGEST_TABLE='##@TABLE.strShortTableName##_searchsuggest.##@ext##';\r\n";
	$jscode.="MASTER_PREVIEW_TABLE='##@TABLE.strShortTableName##_masterpreview.##@ext##';\r\n";
$html_begin.="<div id=\"search_suggest".$id."\"></div>";
$html_begin.="<div id=\"master_details".$id."\" onmouseover=\"RollDetailsLink.showPopup();\" onmouseout=\"RollDetailsLink.hidePopup();\"> </div>";
##if @TABLE.bInlineEdit || @TABLE.bInlineAdd##
if($mode==LIST_SIMPLE)
	$html_begin.="<div id=\"inline_error".$id."\"></div>";
##endif##

$body = array();
if($mode==LIST_SIMPLE)
	$html_begin.="<form name=\"frmSearch\" method=\"GET\" action=\"##@TABLE.strShortTableName##_list.##@ext##\">";
else
{
	$html_begin.="<form name=\"frmSearch".$id."\" target=\"flyframe".$id."\" method=\"GET\" action=\"##@TABLE.strShortTableName##_list.##@ext##\">";
	$html_begin.="<input type=\"Hidden\" name=\"mode\" value=\"lookup\">";
	$html_begin.="<input type=\"Hidden\" name=\"id\" value=\"".$id."\">";
	$html_begin.="<input type=\"Hidden\" name=\"field\" value=\"".htmlspecialchars($lookupfield)."\">";
	$html_begin.="<input type=\"Hidden\" name=\"control\" value=\"".htmlspecialchars($lookupcontrol)."\">";
	$html_begin.="<input type=\"Hidden\" name=\"category\" value=\"".htmlspecialchars($lookupcategory)."\">";
	$html_begin.="<input type=\"Hidden\" name=\"table\" value=\"".htmlspecialchars($lookuptable)."\">";
}
$html_begin.='<input type="Hidden" name="a" value="search">
<input type="Hidden" name="value" value="1">
<input type="Hidden" name="SearchFor" value="">
<input type="Hidden" name="SearchOption" value="">
<input type="Hidden" name="SearchField" value="">
</form>';
$includes_vars="true";
if($mode==LIST_SIMPLE)
{
	$body["begin"]="";
	$body["begin"].="<script type=\"text/javascript\" src=\"include/jquery.js\"></script>";	
	$body["begin"].="<script language=\"JavaScript\" src=\"include/jsfunctions.js\"></script>\r\n";
	//$jscode .='correctListHeight(""); ';
	##if @TABLE.displayLoading##
	$body["begin"].=loadindicator();
	$onLoad ="onload=\"if(!window.stopload){document.getElementById('loading').className='load_hide';window.stopload=true;}\"";
	$xt->assign("bodyattrs",$onLoad);
	##endif##
	$body["begin"].="<script language=\"JavaScript\" src=\"include/customlabels.js\"></script>\r\n";
	$body["begin"].=$html_begin;
}
elseif($mode==LIST_LOOKUP)
{
	$body["begin"].=$html_begin;
	$xt->assign("header","");
}
//	process session variables
//	order by
$strOrderBy="";
$order_ind=-1;


$recno=1;
$recid=$recno+$id;
$numrows=0;
$maxpages=1;
$rowid=0;
##foreach Fields as @f filter @f.bListPage##
//orderlinkattrs for ##@f.strName g##
$href="##@TABLE.strShortTableName##_list.##@ext##?orderby=a##@f.strName g##";
$orderlinkattrs="";
if($mode==LIST_LOOKUP)
{
	$href.="&".$lookupparams;
	$orderlinkattrs="onclick=\"window.frames['flyframe".$id."'].location='".$href."';return false;\" href=\"".$href."\"";
}
else
	$orderlinkattrs=" href=\"".$href."\" OnMouseDown=\"sort(event,this.href);\" OnMouseOver=\"addspan(event);\" OnMouseMove=\"movespan(event);\" OnMouseOut=\"delspan();\"";
$xt->assign("##@f.strName g##_orderlinkattrs",$orderlinkattrs);
$xt->assign("##@f.strName g##_fieldheader",true);
##endfor##

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Sorting fields
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Array fields for sort	
	$arrFieldForSort=array();
//Array how fields sort	
	$arrHowFieldSort=array();
	$arrImplicitSortFields=array();
	$key=array();
//Session field for sort		
	if(@$_SESSION[$sessionPrefix."_arrFieldForSort"]) 
		$arrFieldForSort=$_SESSION[$sessionPrefix."_arrFieldForSort"];
//Session how field sort
	if(@$_SESSION[$sessionPrefix."_arrHowFieldSort"]) 
		$arrHowFieldSort=$_SESSION[$sessionPrefix."_arrHowFieldSort"]; 
//Session key fields for sort		
	if(@$_SESSION[$sessionPrefix."_key"])
		$key=$_SESSION[$sessionPrefix."_key"];
	else{	
			##foreach @TABLE.arrKeyFields as @k##
			if(GetFieldIndex("##@k s##"))
				$key[]=GetFieldIndex("##@k s##");
			##endfor##
			$_SESSION[$sessionPrefix."_key"]=$key; 
		}
	$lenkey=count($key);
	if(!isset($_SESSION[$sessionPrefix."_order"]))
	{
		$arrFieldForSort=array();
		$arrHowFieldSort=array();
		if(count($g_orderindexes))
		{
			for($i=0;$i<count($g_orderindexes);$i++)
			{
				$arrFieldForSort[]=$g_orderindexes[$i][0];
				$arrHowFieldSort[]=$g_orderindexes[$i][1];
			}
		}
		elseif($gstrOrderBy!='')
			$_SESSION[$sessionPrefix."_noNextPrev"] = 1; 
	//add sorting on key fields
		if(count($key))
		{
			for($i=0;$i<$lenkey;$i++)
			{
				$idsearch=array_search($key[$i],$arrFieldForSort);
				if($idsearch===false)
				{
					$arrFieldForSort[]=$key[$i];
					$arrHowFieldSort[]="ASC";
					$arrImplicitSortFields[]=$key[$i];
				}
			}
		}
	}
	$lenArr=count($arrFieldForSort);
	//Sorting defined on the sheet
	if(@$_SESSION[$sessionPrefix."_orderby"])
	{
		$order_field=GetFieldByGoodFieldName(substr($_SESSION[$sessionPrefix."_orderby"],1));
		$order_dir=substr($_SESSION[$sessionPrefix."_orderby"],0,1);
		$order_ind=GetFieldIndex($order_field);
		if($order_ind)
		{
			if(!@$_REQUEST["a"] and !@$_REQUEST["goto"] and !@$_REQUEST["pagesize"])
			{
				if(@$_REQUEST["ctrl"])
				{
					$idsearch=array_search($order_ind,$arrFieldForSort);
					if($idsearch===false)
					{
						if($order_dir=="a")
						{
							$arrFieldForSort[]=$order_ind;
							$arrHowFieldSort[]="ASC";
						}
						else{
								$arrFieldForSort[]=$order_ind;
								$arrHowFieldSort[]="DESC";
							}
					}
					else
						$arrHowFieldSort[$idsearch]=($order_dir=="a" ? "ASC" : "DESC");
				}
				else{
						$arrFieldForSort=array();
						$arrHowFieldSort=array();
						if(!empty($_SESSION[$sessionPrefix."_orderNo"]))
							unset($_SESSION[$sessionPrefix."_orderNo"]);
						$_SESSION[$sessionPrefix."_noNextPrev"] = 0;
						if($order_dir=="a")
						{
							$arrFieldForSort[]=$order_ind;
							$arrHowFieldSort[]="ASC";
						}
						else{
								$arrFieldForSort[]=$order_ind;
								$arrHowFieldSort[]="DESC";
							}
					}
			}
		}
	}
	$lenArr=count($arrFieldForSort);
	//Draw pictures of fields for sorting
	$condition=true;
	if(!count($arrFieldForSort))
		$condition=false;
	elseif(!$arrFieldForSort[0])
		$condition=false;
	if($condition)
	{
		for($i=0;$i<$lenArr;$i++)
		{
			$order_field=GetFieldByIndex($arrFieldForSort[$i]);
			$order_dir=$arrHowFieldSort[$i]=="ASC" ? "a" : "d";
			$idsearch=array_search($arrFieldForSort[$i],$arrImplicitSortFields);
			if($idsearch===false)
				$xt->assign_section(GoodFieldName($order_field)."_fieldheader","","<img src=\"images/".($order_dir=="a" ? "up" : "down").".gif\" border=0>");

			// default ASC for key fields	
			if ($idsearch!==false && in_array(GetFieldIndex($order_field), $arrImplicitSortFields))
			{
				$href="##@TABLE.strShortTableName##_list.##@ext##?orderby=a".GoodFieldName($order_field);
			}
			else
			{
				$href="##@TABLE.strShortTableName##_list.##@ext##?orderby=".($order_dir=="a" ? "d" : "a").GoodFieldName($order_field);	
			}
			$orderlinkattrs="";
			if($mode==LIST_LOOKUP)
			{
				$href.="&".$lookupparams;
				$orderlinkattrs="onclick=\"window.frames['flyframe".$id."'].location='".$href."';return false;\"  href=\"".$href."\"";
			}
			else
				$orderlinkattrs.=" href=\"".$href."\" OnMouseDown=\"sort(event,this.href);\" OnMouseOver=\"addspan(event);\" OnMouseMove=\"movespan(event);\" OnMouseOut=\"delspan();\"";
			$xt->assign(GoodFieldName($order_field)."_orderlinkattrs",$orderlinkattrs);
		}
	}
	//Shape sorting line for a request
	if($lenArr > 0)
	{
		for($i=0;$i<$lenArr;$i++)
			$strOrderBy .=(GetFieldByIndex($arrFieldForSort[$i]) ? ($strOrderBy!="" ? ", " : " ORDER BY ").$arrFieldForSort[$i]." ".$arrHowFieldSort[$i] : "");
	}
	if($_SESSION[$sessionPrefix."_noNextPrev"]==1)
	{
		$strOrderBy = $gstrOrderBy;
	}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//	page number
$mypage=(integer)$_SESSION[$sessionPrefix."_pagenumber"];
if(!$mypage)
	$mypage=1;

//	page size
$PageSize=(integer)$_SESSION[$sessionPrefix."_pagesize"];
if(!$PageSize)
	$PageSize=$gPageSize;
if($mode==LIST_LOOKUP)
	$PageSize=20;

$xt->assign("rpp".$PageSize."_selected","selected");

// delete record
$selected_recs=array();
if (@$_REQUEST["mdelete"])
{
	foreach(@$_REQUEST["mdelete"] as $ind)
	{
		$keys=array();
##foreach @TABLE.arrKeyFields as @k##
		$keys["##@k s##"]=refine($_REQUEST["mdelete##@index##"][mdeleteIndex($ind)]);
##endfor##
		$selected_recs[]=$keys;
	}
}
elseif(@$_REQUEST["selection"])
{
	foreach(@$_REQUEST["selection"] as $keyblock)
	{
		$arr=split("&",refine($keyblock));
		if(count($arr)<##@TABLE.arrKeyFields.len##)
			continue;
		$keys=array();
##foreach @TABLE.arrKeyFields as @k##
		$keys["##@k s##"]=urldecode(@$arr[##eval @index-1##]);
##endfor##
		$selected_recs[]=$keys;
	}
}

$records_deleted=0;
foreach($selected_recs as $keys)
{
	$where = KeyWhere($keys);
##if @TABLE.nSecOptions!=ADVSECURITY_ALL && @BUILDER.nLoginMethod==SECURITY_TABLE && @BUILDER.bCreateLoginPage##
//	delete only owned records
	$where = whereAdd($where,SecuritySQL("Delete"));
##endif##

	$strSQL="delete from ".AddTableWrappers($strOriginalTableName)." where ".$where;
	$retval=true;
	if(function_exists("AfterDelete") || function_exists("BeforeDelete"))
	{
		$deletedrs = db_query(gSQLWhere($where),$conn);
		$deleted_values = db_fetch_array($deletedrs);
	}
	if(function_exists("BeforeDelete"))
		$retval = BeforeDelete($where,$deleted_values);
	if($retval && @$_REQUEST["a"]=="delete")
	{
		$records_deleted++;
		##if @BUILDER.bDeleteFile##
		// delete associated uploaded files if any
		DeleteUploadedFiles($where);
		##endif##
		LogInfo($strSQL);
		db_exec($strSQL,$conn);
		if(function_exists("AfterDelete"))
			AfterDelete($where,$deleted_values);
	}
}

if(count($selected_recs))
{
	if(function_exists("AfterMassDelete"))
		AfterMassDelete($records_deleted);
}


// PRG rule, to avoid POSTDATA resend
if(no_output_done() && count($selected_recs) && $mode==LIST_SIMPLE){	
	// redirect, add a=return param for saving SESSION
	header("Location: ##@TABLE.strShortTableName##_".$pageName."?a=return");
	// turned on output buffering, so we need to stop script
	exit();
}



//deal with permissions
//	table selector
##foreach @BUILDER.Tables as @t filter (@t.bMenuItem || @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].len)##
##if GroupSecurity##
$strPerm = GetUserPermissions("##@t.strDataSourceTable s##");
$allow_##@t.strShortTableName##= (strpos($strPerm, "A")!==false || strpos($strPerm, "S")!==false);
##else##
$allow_##@t.strShortTableName##=true;
##endif##
##endfor##

$createmenu=false;

##foreach @BUILDER.Tables as @t filter @t.bMenuItem order @t.nMenuOrder##
if($allow_##@t.strShortTableName##)
{
	$createmenu=true;
	$xt->assign("##@t.strShortTableName##_tablelink",true);
	$page="";
	##if @t.bList##
	$page="list";
	##if @t.bAdd##
	$strPerm = GetUserPermissions("##@t.strDataSourceTable s##");
	if(strpos($strPerm, "A")!==false && strpos($strPerm, "S")===false)
		$page="add";
	##endif##
	##elseif @t.bAdd##
	$page="add";
	##elseif @t.nType==titREPORT##
	$page="report";
	##elseif @t.nType==titCHART##
	$page="chart";
	##endif##
	$xt->assign("##@t.strShortTableName##_tablelink_attrs","href=\"##@t.strShortTableName##_".$page.".##@ext##\"");
	$xt->assign("##@t.strShortTableName##_optionattrs","value=\"##@t.strShortTableName##_".$page.".##@ext##\"");
}
##endfor##

if($createmenu && $mode==LIST_SIMPLE)
	$xt->assign("menu_block",true);


// for mode simple
if($mode==LIST_SIMPLE)
{
	$xt->assign("shiftstyle_block",true);
	$xt->assign("security_block",true);
	$xt->assign("left_block",true);
}

##if !GroupSecurity##
$allow_add=true;
$allow_delete=true;
$allow_edit=true;
$allow_search=true;
$allow_export=true;
$allow_import=true;
##else##
$strPerm = GetUserPermissions();
$allow_add=(strpos($strPerm,"A")!==false);
$allow_delete=(strpos($strPerm,"D")!==false);
$allow_edit=(strpos($strPerm,"E")!==false);
$allow_search=(strpos($strPerm,"S")!==false);
$allow_export=(strpos($strPerm,"P")!==false);
$allow_import=(strpos($strPerm,"I")!==false);
##endif##

##if !@TABLE.bAdd && !@TABLE.bInlineAdd##
$allow_add=false;
##endif##


//	make sql "select" string

$strWhereClause="";

//	add search params

if(@$_SESSION[$sessionPrefix."_search"]==1)
//	 regular search
{  
	$strSearchFor=trim($_SESSION[$sessionPrefix."_searchfor"]);
	$strSearchOption=trim($_SESSION[$sessionPrefix."_searchoption"]);
	if(@$_SESSION[$sessionPrefix."_searchfield"])
	{
		$strSearchField = $_SESSION[$sessionPrefix."_searchfield"];
		if($where = StrWhereExpression($strSearchField, $strSearchFor, $strSearchOption, ""))
			$strWhereClause = whereAdd($strWhereClause,$where);
		else
			$strWhereClause = whereAdd($strWhereClause,"1=0");
	}
	else
	{
		$strWhere = "1=0";
		##foreach Fields as @f filter @f.bSearch##
		if($where=StrWhereExpression("##@f.strName s##", $strSearchFor, $strSearchOption, ""))
			$strWhere .= " or ".$where;
		##endfor##
		$strWhereClause = whereAdd($strWhereClause,$strWhere);
	}
}
else if(@$_SESSION[$sessionPrefix."_search"]==2)
//	 advanced search
{
	$sWhere="";
	foreach(@$_SESSION[$sessionPrefix."_asearchfor"] as $f => $sfor)
		{
			$strSearchFor=trim($sfor);
			$strSearchFor2="";
			$type=@$_SESSION[$sessionPrefix."_asearchfortype"][$f];
			if(array_key_exists($f,@$_SESSION[$sessionPrefix."_asearchfor2"]))
				$strSearchFor2=trim(@$_SESSION[$sessionPrefix."_asearchfor2"][$f]);
			if($strSearchFor!="" || true)
			{
				if (!$sWhere) 
				{
					if($_SESSION[$sessionPrefix."_asearchtype"]=="and")
						$sWhere="1=1";
					else
						$sWhere="1=0";
				}
				$strSearchOption=trim($_SESSION[$sessionPrefix."_asearchopt"][$f]);
				if($where=StrWhereAdv($f, $strSearchFor, $strSearchOption, $strSearchFor2,$type))
				{
					if($_SESSION[$sessionPrefix."_asearchnot"][$f])
						$where="not (".$where.")";
					if($_SESSION[$sessionPrefix."_asearchtype"]=="and")
	   					$sWhere .= " and ".$where;
					else
	   					$sWhere .= " or ".$where;
				}
			}
		}
		$strWhereClause = whereAdd($strWhereClause,$sWhere);
	}

##if @TABLE.bNoRecordsFirstPage##
if(!count($_GET) && !count($_POST))
	$strWhereClause = whereAdd($strWhereClause,"1=0");
##endif##


##if @TABLE.nSecOptions==ADVSECURITY_VIEW_OWN  && @BUILDER.nLoginMethod==SECURITY_TABLE && @BUILDER.bCreateLoginPage##
if(SecuritySQL("Search"))
	$strWhereClause = whereAdd($strWhereClause,SecuritySQL("Search"));
##endif##

if($mode==LIST_LOOKUP)
{
	if(strlen($lookupcategory))
		$strWhereClause = whereAdd($strWhereClause,GetFullFieldName($categoryfield)."=".make_db_value($categoryfield,$lookupcategory));
	if(strlen($lookupwhere))
		$strWhereClause = whereAdd($strWhereClause,$lookupwhere);
}

##foreach @TABLE.arrMasterTables as @m##
if($mastertable=="##@m.strMasterTable s##")
{
	$where ="";
	##foreach @m.arrDetailKeys as @mk##
	##if !@first##
	$where.=" and ";
	##endif##
	$where.= GetFullFieldName("##@mk s##")."=".make_db_value("##@mk s##",$_SESSION[$sessionPrefix."_masterkey##@index##"]);
	##endfor##
	$strWhereClause = whereAdd($strWhereClause,$where);
}
##endfor##

$strSQL = gSQLWhere($strWhereClause);

//	order by
$strSQL.=" ".trim($strOrderBy);

//	save SQL for use in "Export" and "Printer-friendly" pages

$_SESSION[$sessionPrefix."_sql"] = $strSQL;
$_SESSION[$sessionPrefix."_where"] = $strWhereClause;
$_SESSION[$sessionPrefix."_order"] = $strOrderBy;
$_SESSION[$sessionPrefix."_arrFieldForSort"] = $arrFieldForSort;
$_SESSION[$sessionPrefix."_arrHowFieldSort"] = $arrHowFieldSort;

$rowsfound=false;

//	select and display records
if($allow_search)
{
	$diffDetailMasterDataTypes = false;	
 	
##if @BUILDER.nDatabaseType!=nDATABASE_MySQL##
	// check details and master tables field for types. They must be the same type.
	##foreach @BUILDER.tables as @t filter @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].len##
			$masterkeys=array();
		##foreach @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].arrMasterKeys as @mk##
			$masterkeys[]="##@mk s##";
		##endfor##
			$detailkeys=array();
		##foreach @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].arrDetailKeys as @dk##
			$detailkeys[]="##@dk s##";
		##endfor##	
				
		
		##if @t.strOriginalTable##
			$strOriginalDetailsTable="##@t.strOriginalTable s##";
		##else##
			$strOriginalDetailsTable="##@t.strDataSourceTable s##";
		##endif##		
			
		if (!$diffDetailMasterDataTypes)
			foreach($masterkeys as $idx=>$val)
			{	
				// get field types
				$masterFieldType = GetFieldType($masterkeys[$idx], $strOriginalTableName);
				$detailsFieldType = GetFieldType($detailkeys[$idx], $strOriginalDetailsTable);
				// if different data types we can't use subQ
				if ($masterFieldType != $detailsFieldType){
					$diffDetailMasterDataTypes = true;
					break;
				}
			}	
	##endfor##	
##endif##		
	
	
	
##foreach @BUILDER.tables as @t filter @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].len##
##if @first##	
		
	##if @BUILDER.nDatabaseType==nDATABASE_Access && @TABLE.strOriginalTable == @t.strDataSourceTable##
		// for access no subquery if original
		$subQueriesSupAccess = false;
	##elseif##
		// different MasterKeys and DetailKey
		$subQueriesSupAccess = false;	
	##else## 
		$subQueriesSupAccess = true;
	##endif##
	
	// add count of child records to SQL		
	if($bSubqueriesSupported && $subQueriesSupAccess && !$diffDetailMasterDataTypes)
	{
##endif##	
		
		
##if @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].bDisplayChildCount || @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].bHideChild##
	$sqlWhere="##@t.sqlWhere ls##";	
	$masterkeys=array();
##foreach @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].arrMasterKeys as @mk##
	$masterkeys[]="##@mk s##";
##endfor##
	$detailkeys=array();
##foreach @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].arrDetailKeys as @dk##
	$detailkeys[]="##@dk s##";
##endfor##	
	$masterwhere ="";
	foreach($masterkeys as $idx=>$val)
	{
		if($masterwhere)
			$masterwhere.=" and ";
		// may have to move outside of the foreach
	##if @t.strOriginalTable##
		$strOriginalDetailsTable="##@t.strOriginalTable s##";
	##else##
		$strOriginalDetailsTable="##@t.strDataSourceTable s##";
	##endif##		
		$masterwhere.=AddTableWrappers("subQuery_cnt").".".AddFieldWrappers($detailkeys[$idx])."=".AddTableWrappers($strOriginalTableName).".".AddFieldWrappers($masterkeys[$idx]);
	}
		
	// select data from details table
	$dataSourceTable = "##@t.strDataSourceTable s##";
	$detailsTableFrom = "##@t.sqlFrom ls##";
//	add a key field to the select list
	$subQ = "";
	foreach($detailkeys as $k)
	{
		if(strlen($subQ))
			$subQ.=",";
		$subQ.=GetFullFieldName($k,$dataSourceTable);
	}
	$subQ = "SELECT ".$subQ." ".$detailsTableFrom;
	//	add security where clause for sub query	
	$securityClause = SecuritySQL("Search", $dataSourceTable);	
	if (strlen($securityClause))
		$subQ .= " WHERE ".whereAdd($sqlWhere, $securityClause);	
	elseif(strlen($sqlWhere)) 
		$subQ .= " WHERE ".whereAdd("",$sqlWhere);	
	
		
	$countsql = "SELECT count(*) FROM (".$subQ.") ".AddTableWrappers("subQuery_cnt")." WHERE ".$masterwhere;
	$gsqlHead.=",(".$countsql.") as ##@t.strShortTableName##_cnt ";
	
##endif##
##if @last##
	}
##endif##
##endfor##
	$strSQLbak = $strSQL;
	if(function_exists("BeforeQueryList"))
		BeforeQueryList($strSQL,$strWhereClause,$strOrderBy);
//	Rebuild SQL if needed
	if($strSQL!=$strSQLbak)
	{
//	changed $strSQL - old style	
		$numrows=GetRowCount($strSQL);
	}
	else
	{
		$strSQL = gSQLWhere($strWhereClause);
		$strSQL.=" ".trim($strOrderBy);
		$numrows=gSQLRowCount($strWhereClause,##@TABLE.bGroupBy##);
	}
	LogInfo($strSQL);
	
//	 Pagination:
	if(!$numrows)
	{
		$rowsfound=false;
		$message=##message NO_RECORDS##;
		$message_block=array();
		$message_block["begin"]="<span name=\"notfound_message".$id."\">";
		$message_block["end"]="</span>";
		$xt->assignbyref("message_block",$message_block);
		$xt->assign("message",$message);
	}
	else
	{
		$rowsfound=true;
		$maxRecords = $numrows;
		$xt->assign("records_found",$numrows);
		$maxpages=ceil($maxRecords/$PageSize);
		if($mypage > $maxpages)
			$mypage = $maxpages;
		if($mypage<1) 
			$mypage=1;
		$maxrecs=$PageSize;
		$xt->assign("page",$mypage);
		$xt->assign("maxpages",$maxpages);
		

//	write pagination
	if($maxpages>1)
	{
		$xt->assign("pagination_block",true);
		if($mode==LIST_SIMPLE)
			$jscode_end.="window.GotoPage = function(nPageNumber)
				{
					window.location='##@TABLE.strShortTableName##_list.##@ext##?goto='+nPageNumber;
				};";
		else
			$jscode_end.="window.GotoPage".$id." = function (nPageNumber)
				{
					window.frames['flyframe".$id."'].location='##@TABLE.strShortTableName##_list.##@ext##?".$lookupparams."&goto='+nPageNumber;
				};";
	
			$pagination="<table rows='1' cols='1' align='center' width='auto' border='0'>";
			$pagination.="<tr valign='center'><td align='center'>";
			$counterstart = $mypage - 9; 
			if($mypage%10) 
				$counterstart = $mypage - ($mypage%10) + 1; 
			$counterend = $counterstart + 9;
			if($counterend > $maxpages) $counterend = $maxpages; 
			if($counterstart != 1) 
			{
				$pagination.="<a href='JavaScript:GotoPage".$id."(1);' style='TEXT-DECORATION: none;'>".##message FIRST##."</a>";
				$pagination.="&nbsp;:&nbsp;";
				$pagination.="<a href='JavaScript:GotoPage".$id."(".($counterstart-1).");' style='TEXT-DECORATION: none;'>".##message PREVIOUS##."</a>";
				$pagination.="&nbsp;";
			}
			$pagination.="<b>[</b>"; 
			for($counter = $counterstart;$counter<=$counterend;$counter++)
			{
				if ($counter != $mypage)
					$pagination.="&nbsp;<a href='JavaScript:GotoPage".$id."(".$counter.");' class='pag_n' style='TEXT-DECORATION: none;'>".$counter."</a>";
				else 
					$pagination.="&nbsp;<b>".$counter."</b>";
			}
			$pagination.="&nbsp;<b>]</b>";
			if ($counterend != $maxpages) 
			{
				$pagination.="&nbsp;<a href='JavaScript:GotoPage".$id."(".($counterend+1).");' style='TEXT-DECORATION: none;'>".##message NEXT##."</a>";
				$pagination.="&nbsp;:&nbsp;";
				$pagination.="&nbsp;<a href='JavaScript:GotoPage".$id."(".($maxpages).");' style='TEXT-DECORATION: none;'>".##message LAST##."</a>";
			}
			$pagination.="</td></tr></table>";
			$xt->assign("pagination",$pagination);
		}
	}

##if @BUILDER.nDatabaseType==nDATABASE_MySQL##
	if($maxpages>1)
	{
		$strSQL.=" limit ".(($mypage-1)*$PageSize).",".$PageSize;
	}
	$rs=db_query($strSQL,$conn);
##elseif @BUILDER.nDatabaseType==nDATABASE_MSSQLServer##
	if($maxpages>1)
	{
		$strSQL = AddTop($strSQL, $mypage*$PageSize);
	}
	$rs=db_query($strSQL,$conn);
	db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==nDATABASE_Access##
	if($maxpages>1)
	{
		$strSQL = AddTop($strSQL, $mypage*$PageSize);
	}
	$rs=db_query_direct($strSQL,$conn,$numrows);
	db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==nDATABASE_Oracle##
	if($maxpages>1)
	{
		$strSQL = AddRowNumber($strSQL, $mypage*$PageSize);
	}
	$rs=db_query_direct($strSQL,$conn,$numrows);
	db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==nDATABASE_PostgreSQL##
	if($maxpages>1)
	{
		$maxrecs=$PageSize;
		$strSQL.=" limit ".$PageSize." offset ".(($mypage-1)*$PageSize);
	}
	$rs=db_query($strSQL,$conn);
##else##
	$rs=db_query($strSQL,$conn);
	db_pageseek($rs,$PageSize,$mypage);
##endif##

//	hide colunm headers if needed
	$recordsonpage=$numrows-($mypage-1)*$PageSize;
	if($recordsonpage>$PageSize)
	$recordsonpage=$PageSize;
	$colsonpage=##@TABLE.nRecordsPerRowList##;
	if($colsonpage>$recordsonpage)
		$colsonpage=$recordsonpage;
	if($colsonpage<1)
		$colsonpage=1;

##foreach Fields as @f filter @f.strTotalsType && @f.bListPage## 
##if @first##
	$totals=array();
##endif##
	$totals["##@f.strName s##"]=0;
##endfor## 	

//	fill $rowinfo array
	$rowinfo = array();
	$rowinfo["data"]=array();
	$shade=false;
	$editlink="";
	$copylink="";

##if @TABLE.bInlineAdd##
	if($allow_add )
	{
//	add inline add row	
		$row=array();
		$row["rowattrs"]="class=\"addarea".$id."\" rowid=\"add\"";
		$row["rowattrs"].=' style="display: none;"';
		$row["rowspace_attrs"]="class=\"addarea".$id."\"";
		$record=array();
		$record["edit_link"]=true;
		$record["inlineedit_link"]=true;
		$record["view_link"]=true;
		$record["copy_link"]=true;
		$record["checkbox"]=true;
		$record["checkbox"]=true;
		$record["editlink_attrs"]="id=\"editlink_add".$id."\"";
		##if @TABLE.bInlineEdit##
		if($allow_edit)
			$record["inlineeditlink_attrs"]= "id=\"ieditlink_add".$id."\"";
		##endif##
		$record["copylink_attrs"]="id=\"copylink_add".$id."\"";
		$record["viewlink_attrs"]="id=\"viewlink_add".$id."\"";
		$record["checkbox_attrs"]="id=\"check_add".$id."\" name=\"selection[]\"";
##foreach @BUILDER.Tables as @t filter @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].len##
//detail tables
		$record["##@t.strShortTableName##_dtable_link"]=$allow_##@t.strShortTableName##;
		$record["##@t.strShortTableName##_dtablelink_attrs"]=" href=\"##@t.strShortTableName h##_list.##@ext##?\" id=\"master_##@t.strShortTableName##_add".$id."\"";
	##if @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].nDetailPreview==dpPOPUP##
		$record["##@t.strShortTableName##_dtablelink_attrs"].=" onmouseover=\"RollDetailsLink.showPopup(this,'##@t.strShortTableName h##_detailspreview.##@ext##'+this.href.substr(this.href.indexOf('?')));\" onmouseout=\"RollDetailsLink.hidePopup();\"";
	##endif##
	##if @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].nDetailPreview==dpINLINE##
		$record["##@t.strShortTableName##_preview_link"]=false;
	##endif##
##endfor##
##foreach Fields as @f filter @f.bListPage order @f.nListPageOrder##
		$record["##@f.strName g##_value"] = "<span id=\"add".$id."_##@f.strName g##\">&nbsp;</span>";
##if @first##
		##if @TABLE.bInlineEdit##
		if(!$allow_edit || $mode==LIST_LOOKUP)
			$record["##@f.strName g##_value"] = "<span id=\"ieditlink_add".$id."\"></span>".$record["##@f.strName g##_value"];
		##else##
		$record["##@f.strName g##_value"] = "<span id=\"ieditlink_add".$id."\"></span>".$record["##@f.strName g##_value"];
		##endif##

##endif##
//	add spans for link and display fieldsif they don't appear on the List page		
		if($mode==LIST_LOOKUP && $lookupSelectField)
		{
			$span="";
			if(!AppearOnListPage($linkfield))
			{
				$span.="<span style=\"display:none\" ";
				$span.="id=\"add".$id."_".GoodFieldName($linkfield)."\" ";
				$span.="></span>";
			}
			if($dispfield!=$linkfield && !AppearOnListPage($dispfield))
			{
				$span.="<span  style=\"display:none\" ";
				$span.="id=\"add".$id."_".GoodFieldName($dispfield)."\" ";
				$span.="></span>";
			}
			$record[GoodFieldName($lookupSelectField)."_value"].=$span;
		}
##endfor##
		if($colsonpage>1)
			$record["endrecord_block"]=true;
		$record["grid_recordheader"]=true;
		$record["grid_vrecord"]=true;
		$row["grid_record"]=array("data"=>array());
		$row["grid_record"]["data"][]=$record;
		for($i=1;$i<$colsonpage;$i++)
		{
			$rec=array();
			if($i<$colsonpage-1)
				$rec["endrecord_block"]=true;
			$row["grid_record"]["data"][]=$rec;
		}

		$row["grid_rowspace"]=true;
		$row["grid_recordspace"] = array("data"=>array());
		for($i=0;$i<$colsonpage*2-1;$i++)
			$row["grid_recordspace"]["data"][]=true;
		$rowinfo["data"][]=$row;
	}
##endif##
	

//	add grid data	
	
	while($data=db_fetch_array($rs))
	{
		if(function_exists("BeforeProcessRowList"))
		{
			if(!BeforeProcessRowList($data))
				continue;
		}
		break;
	}
##foreach Fields as @f filter @f.strTotalsType && @f.bListPage && @f.strViewFormat=="Time"##
	$time_##@f.strName g##=array(0=>0,1=>0,2=>0);
##endfor##	
	while($data && $recno<=$PageSize)
	{
		$row=array();
##if !@TABLE.bListVerticalLayout##
		if(!$shade)
		{
			$row["rowattrs"]="class='shade'";
##if @TABLE.bRowHighlite##
			$row["rowattrs"].=" onmouseover=\"this.className = 'rowselected';\" onmouseout=\"this.className = 'shade';\"";
##endif##
			$shade=true;
		}
		else
		{
##if @TABLE.bRowHighlite##
			$row["rowattrs"]="onmouseover=\"this.className = 'rowselected';\" onmouseout=\"this.className = '';\"";
##endif##
			$shade=false;
		}
##endif##
		$row["grid_record"]=array();
		$row["grid_record"]["data"]=array();
		$row["rowattrs"].=" rowid=\"".$rowid."\"";
		$rowid++;
		for($col=1;$data && $recno<=$PageSize && $col<=$colsonpage;$col++)
		{
			$recid=$recno+$id;
			$record=array();
##foreach Fields as @f filter @f.strTotalsType && @f.bListPage## 
			##if @f.strTotalsType=="COUNT"##
				$totals["##@f.strName s##"]+= ($data["##@f.strName s##"]!="");
			##elseif @f.strViewFormat=="Time"##
				$goodname = '##@f.strName g##';
				$time_##@f.strName g##=GetTotalsForTime($data["##@f.strName s##"],$time_##@f.strName g##);
				$hor=$time_##@f.strName g##[0];
				$min=$time_##@f.strName g##[1];
				$sec=$time_##@f.strName g##[2];
				$total = ($hor==0 ? '00' : $hor).':'.($min>9 ? $min : ($min==0? '00' : '0'.$min)).':'.($sec>9 ? $sec : ($sec==0 ? '00' : '0'.$sec));
				$totals["##@f.strName s##"]=$total;
			##else##
				$totals["##@f.strName s##"]+=($data["##@f.strName s##"]+0);
			##endif##
##endfor## 

	$editable=CheckSecurity($data["##@TABLE.strMainTableOwnerID s##"],"Edit");
	$record["edit_link"]=$editable;
	$record["inlineedit_link"]=$editable;
	$record["view_link"]=true;
	$record["copy_link"]=true;

	
//	detail tables
##foreach @BUILDER.Tables as @t filter @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].len##
	
	$masterkeys=array();	
	##foreach @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].arrMasterKeys as @mk##
	$masterkeys[]="##@mk s##";
	##endfor##
	$detailkeys=array();
	##foreach @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].arrDetailKeys as @dk##
	$detailkeys[]="##@dk s##";
	##endfor##
	$masterquery="mastertable=##@TABLE.strDataSourceTable us##";
	
	$detailid=array();
	foreach($masterkeys as $idx=>$m)
	{			
		$d=$detailkeys[$idx];
		$masterquery.="&masterkey".($idx+1)."=".rawurlencode($data[$m]);
		$detailid[]=make_db_value($d,$data[$m],"","","##@t.strDataSourceTable s##");
	}

	//	add count of child records to SQL
	##if @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].bDisplayChildCount || @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].bHideChild##
	if(!$bSubqueriesSupported || !$subQueriesSupAccess || $diffDetailMasterDataTypes)
	{
	$sqlHead="##@t.sqlHead ls##";
	$sqlFrom="##@t.sqlFrom ls##";
	$sqlWhere="##@t.sqlWhere ls##";
	
	$securityClause = SecuritySQL("Search", "##@t.strDataSourceTable s##");	
	// add where 
	if (strlen($securityClause))
		$sqlWhere .= whereAdd("",$securityClause);
	
	$sqlTail="##@t.sqlTail ls##";
	$masterwhere ="";
	foreach($masterkeys as $idx=>$val)
	{
		if($masterwhere)
			$masterwhere.=" and ";
	$masterwhere.=GetFullFieldName($detailkeys[$idx],"##@t.strDataSourceTable s##")."=".$detailid[$idx];
	}
	$data["##@t.strShortTableName##_cnt"]=gSQLRowCount_int($sqlHead,$sqlFrom,$sqlWhere,$sqlTail,$masterwhere,##@t.bGroupBy##);
	}
	##endif##	

//detail tables
	$record["##@t.strShortTableName##_dtable_link"]=$allow_##@t.strShortTableName##;
	$record["##@t.strShortTableName##_dtablelink_attrs"]="href=\"##@t.strShortTableName h##_list.##@ext##?".$masterquery."\" id=\"master_##@t.strShortTableName##".$recid."\"";
	$dpreview=true;
	##if @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].bDisplayChildCount##
	if($data["##@t.strShortTableName##_cnt"]+0)
		$record["##@t.strShortTableName##_childcount"]=true;
	else
		$dpreview=false;
	$record["##@t.strShortTableName##_childnumber"]=$data["##@t.strShortTableName##_cnt"];
	##endif##
	##if @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].bHideChild##
	if(!($data["##@t.strShortTableName##_cnt"]+0))
	{
		$record["##@t.strShortTableName##_dtable_link"]=false;
		$dpreview=false;
	}
	##endif##
	if($dpreview)
	{
	##if @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].nDetailPreview==dpPOPUP##
		$record["##@t.strShortTableName##_dtablelink_attrs"].=" onmouseover=\"RollDetailsLink.showPopup(this,'##@t.strShortTableName h##_detailspreview.##@ext##'+this.href.substr(this.href.indexOf('?')));\" onmouseout=\"RollDetailsLink.hidePopup();\"";
	##endif##
	##if @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].nDetailPreview==dpINLINE##
		$record["##@t.strShortTableName##_preview_link"]=$allow_##@t.strShortTableName##;
		$record["##@t.strShortTableName##_previewlink_attrs"]="id=\"##@t.strShortTableName##_preview".$recid."\" onclick=\"preview_inline(this);return false;\" href=\"##@t.strShortTableName h##_list.##@ext##?".$masterquery."\"";
	##endif##
	}
	
##endfor##

//	key fields
	$keyblock="";
	$editlink="";
	$copylink="";
	$keylink="";
##foreach @TABLE.arrKeyFields as @k##
	##if !@first##
	$keyblock.= "&";
	$editlink.="&";
	$copylink.="&";
	$keylink.="&";
	##endif##
	$keyblock.=rawurlencode($data["##@k s##"]);
	$editlink.="editid##@index##=".htmlspecialchars(rawurlencode($data["##@k s##"]));
	$copylink.="copyid##@index##=".htmlspecialchars(rawurlencode($data["##@k s##"]));
	$keylink.="&key##@index##=".htmlspecialchars(rawurlencode(@$data["##@k s##"]));
##endfor##

	$record["editlink_attrs"]="href=\"##@TABLE.strShortTableName h##_edit.##@ext##?".$editlink."\" id=\"editlink".$recid."\"";
	$record["inlineeditlink_attrs"]= "href=\"##@TABLE.strShortTableName h##_edit.##@ext##?".$editlink."\" onclick=\"return inlineEditing".$id.".inlineEdit('".$recid."','".$editlink."');\" id=\"ieditlink".$recid."\"";
	$record["copylink_attrs"]="href=\"##@TABLE.strShortTableName h##_add.##@ext##?".$copylink."\" id=\"copylink".$recid."\"";
	$record["viewlink_attrs"]="href=\"##@TABLE.strShortTableName h##_view.##@ext##?".$editlink."\" id=\"viewlink".$recid."\"";
	if($mode!=LIST_LOOKUP)
	{
		$record["checkbox"]=$editable;
##if @TABLE.bExportTo || @TABLE.bPrinterFriendly##
		if($allow_export)
			$record["checkbox"]=true;
##endif##
		$record["checkbox_attrs"]="name=\"selection[]\" value=\"".$keyblock."\" id=\"check".$recid."\"";
	}
	else
	{
		$checkbox_attrs="name=\"selection[]\" value=\"".htmlspecialchars(@$data[$linkfield])."\" id=\"check".$recid."\"";
		$record["checkbox"]=array("begin"=>"<input type=radio ".$checkbox_attrs.">", "data"=>array());
	}

##foreach Fields as @f filter @f.bListPage order @f.nListPageOrder##

//	##@f.strName## - ##@f.strViewFormat##
			$value="";
	##if @f.strViewFormat==FORMAT_DATABASE_IMAGE##
		##if @f.bShowThumbnail##
				$value.="<a";
				##if @f.bUseiBox##
					$value .= " rel='ibox'";
				##else##
					$value .= " target=_blank";
				##endif##
				$value.=" href=\"##@TABLE.strShortTableName s##_imager.##@ext##?field=##@f.strName uhs##".$keylink."\">";
				$value.= "<img border=0";
				$value.=" src=\"##@TABLE.strShortTableName s##_imager.##@ext##?field=##@f.strThumbnail uhs##&alt=##@f.strName uhs##".$keylink."\">";
				$value.= "</a>";
			##else##
				$value = "<img";
			##if @f.ListFormatObj.nImageWidth##
				$value.=" width=##@f.ListFormatObj.nImageWidth##";
			##endif##
			##if @f.ListFormatObj.nImageHeight##
				$value.=" height=##@f.ListFormatObj.nImageHeight##";
			##endif##
				$value.=" border=0";
				$value.=" src=\"##@TABLE.strShortTableName s##_imager.##@ext##?field=##@f.strName uhs##".$keylink."\">";
		##endif##
	##elseif @f.strViewFormat==FORMAT_FILE_IMAGE##
			if(CheckImageExtension($data["##@f.strName s##"])) 
			{
		##if @f.bShowThumbnail##
			 	// show thumbnail
				$thumbname="##@f.strThumbnail s##".$data["##@f.strName s##"];
				if(substr("##@f.strhlPrefix s##",0,7)!="http://" && !myfile_exists(GetUploadFolder("##@f.strName s##").$thumbname))
					$thumbname=$data["##@f.strName s##"];
				$value="<a";
				##if @f.bUseiBox##
					$value .= " rel='ibox'";
				##else##
					$value .= " target=_blank";
				##endif##
				$value.=" href=\"".htmlspecialchars(AddLinkPrefix("##@f.strName s##",$data["##@f.strName s##"]))."\">";
				$value.="<img";
				if($thumbname==$data["##@f.strName s##"])
				{
			##if @f.ListFormatObj.nImageWidth##
					$value.=" width=##@f.ListFormatObj.nImageWidth##";
			##endif##
			##if @f.ListFormatObj.nImageHeight##
					$value.=" height=##@f.ListFormatObj.nImageHeight##";
			##endif##
				}

				$value.=" border=0";
				$value.=" src=\"".htmlspecialchars(AddLinkPrefix("##@f.strName s##",$thumbname))."\"></a>";
		##else##
				$value="<img";
			##if @f.ListFormatObj.nImageWidth##
				$value.=" width=##@f.ListFormatObj.nImageWidth##";
			##endif##
			##if @f.ListFormatObj.nImageHeight##
				$value.=" height=##@f.ListFormatObj.nImageHeight##";
			##endif##
				$value.=" border=0";
				$value.=" src=\"".htmlspecialchars(AddLinkPrefix("##@f.strName s##",$data["##@f.strName s##"]))."\">";
		##endif##
			}
	##elseif @f.strViewFormat==FORMAT_DATABASE_FILE##
		##if @f.ListFormatObj.strFilename##
			$filename=$data["##@f.ListFormatObj.strFilename s##"];
			if(!$filename)
				$filename="file.bin";
		##else##
			$filename="file.bin";
		##endif##
			if(strlen($data["##@f.strName s##"]))
			{
				$value="<a href=\"##@TABLE.strShortTableName##_getfile.##@ext##?filename=".rawurlencode($filename)."&field=##@f.strName uhs##".$keylink."\">";
				$value.=htmlspecialchars($filename);
				$value.="</a>";
			}
	##elseif (@f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD || @f.strEditFormat==EDIT_FORMAT_RADIO) && @f.pLookupObj.nLookupType == LT_LOOKUPTABLE && @f.strLinkField!=@f.strDisplayField##
			$value=DisplayLookupWizard("##@f.strName s##",$data["##@f.strName s##"],$data,$keylink,MODE_LIST);
	##elseif NeedEncode(@f)##
			$value = ProcessLargeText(GetData($data,"##@f.strName s##", "##@f.strViewFormat##"),"field=##@f.strName uhs##".$keylink,"",MODE_LIST);
	##else##
			$value = GetData($data,"##@f.strName s##", "##@f.strViewFormat##");
	##endif##
			$record["##@f.strName g##_value"]=$value;
##endfor##
			if(function_exists("BeforeMoveNextList"))
				BeforeMoveNextList($data,$row,$record);
			if($mode==LIST_LOOKUP && $lookupSelectField)
				$jscode_end.='inlineEditing'.$id.'.afterRecordEdited('.$recid.');';
			
##if @TABLE.bInlineEdit##
	##foreach Fields as @f filter @f.bListPage order @f.nListPageOrder##
			$cleanvalue=$record["##@f.strName g##_value"];
			$span="<span ";
			$span.="id=\"edit".$recid."_##@f.strName g##\" ";
		##if !IsBinaryField(@f)##
			$span.="val=\"".htmlspecialchars($data["##@f.strName s##"])."\" ";
		##endif##
			$span.=">";
			$record["##@f.strName g##_value"] = $span.$record["##@f.strName g##_value"]."</span>";
			if(!strlen($cleanvalue))
				$record["##@f.strName g##_value"] .="&nbsp;";
	##endfor##
		//	add spans with the link and display field values to the row
			if($mode==LIST_LOOKUP && $lookupSelectField)
			{
				$span="";
				if(!AppearOnListPage($linkfield))
				{
					$span.="<span ";
					$span.="id=\"edit".$recid."_".GoodFieldName($linkfield)."\" ";
					$span.="val=\"".htmlspecialchars($data[$linkfield])."\" ";
					$span.="></span>";
				}
				if($dispfield!=$linkfield && !AppearOnListPage($dispfield))
				{
					$span.="<span ";
					$span.="id=\"edit".$recid."_".GoodFieldName($dispfield)."\" ";
					$span.="val=\"".htmlspecialchars($data[$dispfield])."\" ";
					$span.="></span>";
				}
				$record[GoodFieldName($lookupSelectField)."_value"].=$span;
			}
##else##
	##foreach Fields as @f filter @f.bListPage##
		if(!strlen($record["##@f.strName g##_value"]))
			$record["##@f.strName g##_value"]="&nbsp";
	##endfor##
		//	add spans with the link and display field values to the row
			if($mode==LIST_LOOKUP && $lookupSelectField)
			{
				$spanlink="<span ";
				$spanlink.="id=\"edit".$recid."_".GoodFieldName($linkfield)."\" ";
				$spanlink.="val=\"".htmlspecialchars($data[$linkfield])."\" ";
				$spanlink.=">";
				$spandisp="<span ";
				$spandisp.="id=\"edit".$recid."_".GoodFieldName($dispfield)."\" ";
				$spandisp.="val=\"".htmlspecialchars($data[$dispfield])."\" ";
				$spandisp.=">";
				$spanselect="<span ";
				$spanselect.="id=\"edit".$recid."_".GoodFieldName($lookupSelectField)."\" ";
				$spanselect.=">";
				if($lookupSelectField==$linkfield)
				{
					$record[GoodFieldName($lookupSelectField)."_value"]=$spanlink.$record[GoodFieldName($lookupSelectField)."_value"]."</span>";
					if($linkfield!=$dispfield)
						$record[GoodFieldName($lookupSelectField)."_value"].=$spandisp."</span>";
				}
				elseif($lookupSelectField==$dispfield)
				{
					$record[GoodFieldName($lookupSelectField)."_value"]=$spandisp.$record[GoodFieldName($lookupSelectField)."_value"]."</span>";
					if($linkfield!=$dispfield)
						$record[GoodFieldName($lookupSelectField)."_value"].=$spanlink."</span>";
				}
				else
				{
					$record[GoodFieldName($lookupSelectField)."_value"]=$spanselect.$record[GoodFieldName($lookupSelectField)."_value"]."</span>";
					$record[GoodFieldName($lookupSelectField)."_value"].=$spanlink."</span>";
					if($linkfield!=$dispfield)
						$record[GoodFieldName($lookupSelectField)."_value"].=$spandisp."</span>";
				}
			}
##endif##
			if($col<$colsonpage)
				$record["endrecord_block"]=true;
			$record["grid_recordheader"]=true;
			$record["grid_vrecord"]=true;
			$row["grid_record"]["data"][]=$record;
			while($data=db_fetch_array($rs))
			{
				if(function_exists("BeforeProcessRowList"))
				{
					if(!BeforeProcessRowList($data))
						continue;
				}
				break;
			}
			$recno++;
			
		}
		while($col<=$colsonpage)
		{
			$record = array();
			if($col<$colsonpage)
				$record["endrecord_block"]=true;
			$row["grid_record"]["data"][]=$record;
			$col++;
		}
//	assign row spacings for vertical layout
		$row["grid_rowspace"]=true;
		$row["grid_recordspace"] = array("data"=>array());
		for($i=0;$i<$colsonpage*2-1;$i++)
			$row["grid_recordspace"]["data"][]=true;
		
		$rowinfo["data"][]=$row;
	}
	if(count($rowinfo["data"]))
		$rowinfo["data"][count($rowinfo["data"])-1]["grid_rowspace"]=false;
	$xt->assignbyref("grid_row",$rowinfo);


##if Fields[strTotalsType].len##
//	process totals
	$xt->assign("totals_row",true);
	$totals_records=array("data"=>array());
	for($i=0;$i<$colsonpage;$i++)
	{
		$record=array();
		if($i==0)
		{
	##foreach Fields as @f filter @f.strTotalsType && @f.bListPage## 
	##if @first##
	//	show totals
	##endif##
		$total=GetTotals("##@f.strName s##",$totals["##@f.strName s##"],"##@f.strTotalsType##",$recno-1,"##@f.strViewFormat##");
	##if @TABLE.bInlineEdit || @TABLE.bInlineAdd##
		$total="<span id=\"total".$id."_##@f.strName g##".$id."\" type=\"##@f.strTotalsType##\" format=\"##@f.strViewFormat##\">".$total."</span>";
	##endif##
		$xt->assign("##@f.strName g##_total",$total);
		$record["##@f.strName g##_showtotal"]=true;
	##endfor##
		}
		if($i<$colsonpage-1)
			$record["endrecordtotals_block"]=true;
		$totals_records["data"][]=$record;
	}
	$xt->assignbyref("totals_record",$totals_records);
##endif##	
}


##if Fields[bSearch=1].len##
if($allow_search)
{

##if @TABLE.bSearchSuggest##
	$searchfor_attrs="autocomplete=off onkeydown=\"return listenEvent(event,this,'ordinary');\" onkeyup=\"searchSuggest(event,this,'ordinary');\"";
##else##
	$searchfor_attrs="onkeydown=\"e=event; if(!e) e = window.event; if (e.keyCode != 13) return true; e.cancel = true; RunSearch('".$id."'); return false;\"";
##endif##
	if($mode==LIST_LOOKUP)
		$searchfor_attrs="onkeydown=\"e=event; if(!e) e = window.event; if (e.keyCode != 13) return true; e.cancel = true; RunSearch('".$id."'); return false;\"";
	if($_SESSION[$sessionPrefix."_search"]==1)
	{
//	fill in search variables
	//	field selection
		if(@$_SESSION[$sessionPrefix."_searchfield"])
			$xt->assign(GoodFieldName(@$_SESSION[$sessionPrefix."_searchfield"])."_searchfieldoption","selected");
	// search type selection
		$xt->assign(GoodFieldName(@$_SESSION[$sessionPrefix."_searchoption"])."_searchtypeoption","selected");
		$searchfor_attrs.=" value=\"".htmlspecialchars(@$_SESSION[$sessionPrefix."_searchfor"])."\"";
	}
	$searchfor_attrs.=" name=\"ctlSearchFor".$id."\" id=\"ctlSearchFor".$id."\"";
	$xt->assign("searchfor_attrs",$searchfor_attrs);
	$xt->assign("searchbutton_attrs","onClick=\"javascript: RunSearch('".$id."');\"");
	$xt->assign("showallbutton_attrs","onClick=\"javascript: document.forms.frmSearch".$id.".a.value = 'showall'; document.forms.frmSearch".$id.".submit();\"");
}
##endif##


if($mode==LIST_SIMPLE)
{

	##if @BUILDER.bCreateLoginPage##
	$xt->assign("login_block",true);
	$xt->assign("username",htmlspecialchars($_SESSION["UserID"]));
	$xt->assign("logoutlink_attrs","onclick=\"window.location.href='login.##@ext##?a=logout';\"");
	##endif##


	$xt->assign("toplinks_block",true);

	$xt->assign("print_link",$allow_export);
	$xt->assign("printall_link",$allow_export);
	$xt->assign("printlink_attrs","href=\"##@TABLE.strShortTableName h##_print.##@ext##\" onclick=\"window.open('##@TABLE.strShortTableName h##_print.##@ext##','wPrint');return false;\"");
	$xt->assign("printalllink_attrs","href=\"##@TABLE.strShortTableName h##_print.##@ext##?all=1\" onclick=\"window.open('##@TABLE.strShortTableName h##_print.##@ext##?all=1','wPrint');return false;\"");
	$xt->assign("export_link",$allow_export);
	$xt->assign("exportlink_attrs","href=\"##@TABLE.strShortTableName h##_export.##@ext##\" onclick=\"window.open('##@TABLE.strShortTableName h##_export.##@ext##','wExport');return false;\"");
	
	$xt->assign("printselected_link",$allow_export);
	$xt->assign("printselectedlink_attrs","disptype=\"control1\" onclick=\"
	if(!\$('input[@type=checkbox][@checked][@name^=selection]').length)
		return true;
	document.forms.frmAdmin.action='##@TABLE.strShortTableName h##_print.##@ext##';
	document.forms.frmAdmin.target='_blank';
	document.forms.frmAdmin.submit(); 
	document.forms.frmAdmin.action='##@TABLE.strShortTableName h##_list.##@ext##'; 
	document.forms.frmAdmin.target='_self';return false\"
	href=\"##@TABLE.strShortTableName h##_print.##@ext##\"");
	$xt->assign("exportselected_link",$allow_export);
	$xt->assign("exportselectedlink_attrs","disptype=\"control1\" onclick=\"
	if(!\$('input[@type=checkbox][@checked][@name^=selection]').length)
		return true;
	document.forms.frmAdmin.action='##@TABLE.strShortTableName h##_export.##@ext##';
	document.forms.frmAdmin.target='_blank';
	document.forms.frmAdmin.submit(); 
	document.forms.frmAdmin.action='##@TABLE.strShortTableName h##_list.##@ext##'; 
	document.forms.frmAdmin.target='_self';return false;\"
	href=\"##@TABLE.strShortTableName h##_export.##@ext##\"");
	
	$xt->assign("add_link",$allow_add);
	$xt->assign("copy_column",$allow_add);
	$xt->assign("addlink_attrs","href=\"##@TABLE.strShortTableName h##_add.##@ext##\" onClick=\"window.location.href='##@TABLE.strShortTableName h##_add.##@ext##'\"");
	$xt->assign("inlineadd_link",$allow_add);
	$xt->assign("inlineaddlink_attrs","href=\"##@TABLE.strShortTableName h##_add.##@ext##\" onclick=\"return inlineEditing".$id.".inlineAdd(flyid++,null,'##@TABLE.strShortTableName##_add.##@ext##');\"");

	$xt->assign("selectall_link",$allow_delete || $allow_export  || $allow_edit);
	$xt->assign("selectalllink_attrs","href=# onclick=\"var i; 
	bSelected=!bSelected;
if ((typeof frmAdmin.elements['selection[]'].length)=='undefined')
	frmAdmin.elements['selection[]'].checked=bSelected;
else
for (i=0;i<frmAdmin.elements['selection[]'].length;++i) 
	frmAdmin.elements['selection[]'][i].checked=bSelected\"");
	
	$xt->assign("checkbox_column",$allow_delete || $allow_export  || $allow_edit);
	$xt->assign("checkbox_header",true);
	$xt->assign("checkboxheader_attrs","onClick = \"var i; 
if ((typeof frmAdmin.elements['selection[]'].length)=='undefined')
	frmAdmin.elements['selection[]'].checked=this.checked;
else
for (i=0;i<frmAdmin.elements['selection[]'].length;++i) 
	frmAdmin.elements['selection[]'][i].checked=this.checked;\"");
	$xt->assign("editselected_link",$allow_edit);
	$xt->assign("editselectedlink_attrs","href=\"##@TABLE.strShortTableName h##_edit.##@ext##\" disptype=\"control1\" name=\"edit_selected".$id."\" onclick=\"\$('input[@type=checkbox][@checked][@id^=check]').each(function(i){
				if(!isNaN(parseInt(this.id.substr(5))))
					\$('a#ieditlink'+this.id.substr(5)).click();});\"");
	$xt->assign("saveall_link",$allow_edit||$allow_edit);
	$xt->assign("savealllink_attrs","disptype=\"control1\" name=\"saveall_edited".$id."\"  onclick=\"\$('a[@id^=save_]').click();\"");
	$xt->assign("savealllink_span","style=\"display:none\"");
	$xt->assign("cancelall_link",$allow_edit||$allow_edit);
	$xt->assign("cancelalllink_attrs","disptype=\"control1\" name=\"revertall_edited".$id."\" onclick=\"\$('a[@id^=revert_]').click();\"");
	$xt->assign("canselalllink_span","style=\"display:none\"");

	$xt->assign("edit_column",$allow_edit);
	$xt->assign("edit_headercolumn",$allow_edit);
	$xt->assign("edit_footercolumn",$allow_edit);
	$xt->assign("inlineedit_column",$allow_edit);
	$xt->assign("inlineedit_headercolumn",$allow_edit);
	$xt->assign("inlineedit_footercolumn",$allow_edit);
	
	$xt->assign("view_column",$allow_search);

##foreach @BUILDER.Tables as @t filter @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].len##
##if @first##
	if($mode!=LIST_LOOKUP)
	{
##endif##
 		$xt->assign("##@t.strShortTableName##_dtable_column",$allow_##@t.strShortTableName##);
##if @last##
	}
##endif##
##endfor##

	$xt->assign("delete_link",$allow_delete);
	$xt->assign("deletelink_attrs","onclick=\"
		if(\$('input[@type=checkbox][@checked][@name^=selection]').length && confirm('".##message DELETE_CONFIRM##."'))
			frmAdmin.submit(); 
		return false;\"");

}
elseif ($mode==LIST_LOOKUP)
{
//	$xt->assign("checkbox_column",true);
	$xt->assign("inlineadd_link",$allow_add);
	$xt->assign("inlineaddlink_attrs","href=\"##@TABLE.strShortTableName h##_add.##@ext##\" onclick=\"return inlineEditing".$id.".inlineAdd(flyid++,".$id.",'##@TABLE.strShortTableName##_add.##@ext##');\"");
//	$xt->assign("inlineedit_column",$allow_edit);
}

##foreach Fields as @f filter @f.bListPage order @f.nListPageOrder##
$xt->assign("##@f.strName g##_fieldheadercolumn",true);
$xt->assign("##@f.strName g##_fieldcolumn",true);
$xt->assign("##@f.strName g##_fieldfootercolumn",true);
##endfor##
	
##if !@TABLE.bInlineAdd##
$display_grid = $allow_search && $rowsfound;
##else##
$display_grid = $allow_add || $allow_search && $rowsfound;
##endif##

$xt->assign("asearch_link",$allow_search);
$xt->assign("asearchlink_attrs","href=\"##@TABLE.strShortTableName h##_search.##@ext##\" onclick=\"window.location.href='##@TABLE.strShortTableName h##_search.##@ext##';return false;\"");
$xt->assign("import_link",$allow_import);
$xt->assign("importlink_attrs","href=\"##@TABLE.strShortTableName h##_import.##@ext##\" onclick=\"window.location.href='##@TABLE.strShortTableName h##_import.##@ext##';return false;\"");

$xt->assign("search_records_block",$allow_search);
$xt->assign("searchform",$allow_search);
$xt->assign("searchform_showall",$allow_search);
if($mode!=LIST_LOOKUP)
{
	$xt->assign("searchform_field",$allow_search);
	$xt->assign("searchform_option",$allow_search);
}
$xt->assign("searchform_text",$allow_search);
$xt->assign("searchform_search",$allow_search);

$xt->assign("usermessage",true);

if($display_grid)
{
	if($mode==LIST_SIMPLE)
		$xt->assign_section("grid_block",
		"<form method=\"POST\" action=\"##@TABLE.strShortTableName h##_list.##@ext##\" name=\"frmAdmin\" id=\"frmAdmin\">
		<input type=\"hidden\" id=\"a\" name=\"a\" value=\"delete\">",
		"</form>");
	elseif($mode==LIST_LOOKUP)
		$xt->assign_section("grid_block",
		"<form method=\"POST\" action=\"##@TABLE.strShortTableName h##_list.##@ext##\" name=\"frmAdmin".$id."\" id=\"frmAdmin".$id."\" target=\"flyframe".$id."\">
		<input type=\"hidden\" id=\"a".$id."\" name=\"a\" value=\"delete\">",
		"</form>");
	
	$record_header=array("data"=>array());
	$record_footer=array("data"=>array());
	for($i=0;$i<$colsonpage;$i++)
	{
		$rheader=array();
		$rfooter=array();
		if($i<$colsonpage-1)
		{
			$rheader["endrecordheader_block"]=true;
			$rfooter["endrecordfooter_block"]=true;
		}
		$record_header["data"][]=$rheader;
		$record_footer["data"][]=$rfooter;
	}
	$xt->assignbyref("record_header",$record_header);
	$xt->assignbyref("record_footer",$record_footer);
	$xt->assign("grid_header",true);
	// hiding header, if no rows
	if (!$numrows)
		$xt->assign("gridHeader_attrs",'id="gridHeaderTr" style="display: none;"');
	
	$xt->assign("grid_footer",true);

	$xt->assign("record_controls",true);
}

$xt->assign("recordcontrols_block",$allow_add || $display_grid);

$xt->assign("newrecord_controls",$allow_add);

if($mode==LIST_SIMPLE)
{
	$xt->assign("details_block",$allow_search && $rowsfound);
	$xt->assign("recordspp_block",$allow_search && $rowsfound);
	$xt->assign("recordspp_attrs","onchange=\"javascript: document.location='##@TABLE.strShortTableName h##_list.##@ext##?pagesize='+this.options[this.selectedIndex].value;\"");
	$xt->assign("pages_block",$allow_search && $rowsfound);
}
else
	$xt->assign("recordspp_attrs","onchange=\"javascript: window.frames['flyframe".$id."'].location='##@TABLE.strShortTableName h##_list.##@ext##?".$lookupparams."&pagesize='+this.options[this.selectedIndex].value;\"");
$xt->assign("grid_controls",$display_grid);



##foreach @TABLE.arrMasterTables as @m##
##if @first##
//	display Back to Master link and master table info
$masterkeys=array();
##endif##
if($mastertable=="##@m.strMasterTable s##")
{
##if @m.bDisplayInfo##
//	include proper masterlist.##@ext## code
	include("include/##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##_masterlist.##@ext##");
	##foreach @m.arrDetailKeys as @mk##
	$masterkeys[]=@$_SESSION[$sessionPrefix."_masterkey##@index##"];
	##endfor##
	$params=array("detailtable"=>"##@TABLE.strDataSourceTable s##","keys"=>$masterkeys);
	$master=array();
	$master["func"]="DisplayMasterTableInfo_##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##";
	$master["params"]=$params;
	$xt->assignbyref("showmasterfile",$master);
##endif##	
	$xt->assign("mastertable_block",true);
	$xt->assign("backtomasterlink_attrs","href=\"##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##_list.##@ext##?a=return\"");
}
##endfor##

$jscode_end.="if(flyid<".($recid+1).") flyid=".($recid+1).";\r\n";
##if @TABLE.bInlineAdd##
	$jscode_end.="\$(\".addarea".$id."\").each(function(i) { \$(this).hide();});\r\n";
	if(!$numrows)
	{
		$jscode_end .= "$('#record_controls".$id."').hide();";
		if($mode==LIST_SIMPLE)
			$jscode_end .= "$('[@name=maintable]').hide();";
		else
		{
			$jscode_end .= "$('[@name=maintable]',$('#fly".$id."')).hide();";
		}
	}
##endif##
##if @TABLE.bInlineAdd || @TABLE.bInlineEdit##

$html_end .= "<style>
#inline_error {
	font-family: Verdana, Arial, Helvetica, sans serif;
	font-size: 11px;
	position: absolute;
	background-color: white;
	border: 1px solid red;
	padding: 10px;
	background-repeat: no-repeat;
	display: none;
	}
</style>";
##endif##
if($mode==LIST_SIMPLE)
	$jscode_end.="if(!$('[@disptype=control1]').length && $('[@disptype=controltable1]').length)
		$('[@disptype=controltable1]').hide();";
if($_SESSION[$sessionPrefix."_search"]==1)
	$jscode_end.= "if(document.getElementById('ctlSearchFor".$id."')) document.getElementById('ctlSearchFor".$id."').focus();";

	
if($mode==LIST_SIMPLE)
{
	$jscode.=$jscode_end;
	PrepareJSCode($jscode,$id);
	$body["end"]="<script>".$jscode."</script>";
	$body["end"].=$html_end;
}
elseif($mode==LIST_LOOKUP)
{
	$body["end"].=$html_end;
	$xt->assign("footer","");
}
$xt->assignbyref("body",$body);
$xt->assign("style_block",true);
$xt->assign("iestyle_block",true);

##if @BUILDER.bDynamicPermissions##
if(@$_SESSION["IsAdmin"])
	$xt->assign("adminarea_link",true);
$xt->assign("adminarealink_attrs","href=\"admin_rights_list.##@ext##\" onclick=\"window.location.href='admin_rights_list.##@ext##';return false;\"");
##endif##

$strSQL=$_SESSION[$sessionPrefix."_sql"];
$xt->assign("changepwd_link",$_SESSION["AccessLevel"] != ACCESS_LEVEL_GUEST);
$xt->assign("changepwdlink_attrs","href=\"changepwd.##@ext##\" onclick=\"window.location.href='changepwd.##@ext##';return false;\"");


##if IsAdminTable(@TABLE)##
$defaulturl="";
##if CreateMenu##
		$defaulturl="menu.##@ext##";
##else##
	##foreach @BUILDER.Tables as @t filter @t.bMenuItem order @t.nMenuOrder##
		##if @first##
		##if @t.bList##
		$defaulturl="##@t.strShortTableName##_list.##@ext##";
		##elseif @t.nType==titREPORT##
		$defaulturl="##@t.strShortTableName##_report.##@ext##";
		##elseif @t.nType==titCHART##
		$defaulturl="##@t.strShortTableName##_chart.##@ext##";
		##else##
		$defaulturl="##@t.strShortTableName##_add.##@ext##";
		##endif##
		##endif##
	##endfor##
##endif##			
##if !@BUILDER.Tables[bMenuItem].len##
	##if @BUILDER.Tables.bList##
		$defaulturl="##@BUILDER.Tables.strShortTableName##_list.##@ext##";
	##elseif @t.nType==titREPORT##
		$defaulturl="##@BUILDER.Tables.strShortTableName##_report.##@ext##";
	##elseif @t.nType==titCHART##
		$defaulturl="##@BUILDER.Tables.strShortTableName##_chart.##@ext##";
	##else##
		$defaulturl="##@BUILDER.Tables.strShortTableName##_add.##@ext##";
	##endif##
##endif##

$xt->assign("exitaalink_attrs","href=\"".$defaulturl."\" onclick=\"window.location.href='".$defaulturl."';return false;\"");
$xt->assign("exitaalink_href","href=\"".$defaulturl."\"");
$xt->assign("exitadminarea_link",true);
$xt->assign("admin_rights_tablelink",true);
$xt->assign("admin_rights_tablelink_attrs","href=\"admin_rights_list.##@ext##\"");
$xt->assign("admin_members_tablelink",true);
$xt->assign("admin_members_tablelink_attrs","href=\"admin_members_list.##@ext##\"");
$xt->assign("admin_users_tablelink",true);
$xt->assign("admin_users_tablelink_attrs","href=\"admin_users_list.##@ext##\"");
$xt->assign("admin_rights_optionattrs","value=\"admin_rights_list.##@ext##\"");
$xt->assign("admin_members_optionattrs","value=\"admin_members_list.##@ext##\"");
$xt->assign("admin_users_optionattrs","value=\"admin_users_list.##@ext##\"");
##endif##

##if CreateMenu || IsAdminTable(@TABLE)##
$xt->assign("quickjump_attrs","onfocus =\"window.selectcurrent = this.selectedIndex;\" onchange=\"if(this.options[this.selectedIndex].value){window.location.href=this.options[this.selectedIndex].value;}else{this.selectedIndex=window.selectcurrent;}\"");
##endif##

##if @BUILDER.bWebReports##
$xt->assign("webreport_link",true);
##endif##

$xt->assign("endrecordblock_attrs","colid=\"endrecord\"");
$templatefile = "##@TABLE.strShortTableName##_list.htm";
if(function_exists("BeforeShowList"))
	BeforeShowList($xt,$templatefile);

if($mode==LIST_SIMPLE)
	$xt->display($templatefile);
elseif($mode==LIST_LOOKUP)
{
	$jscode.=$jscode_end;
	PrepareJSCode($jscode,$id);
	if($firsttime)
	{
		echo str_replace(array("\\","\r","\n"),array("\\\\","\\r","\\n"),$jscode);
		echo "\n";
	}
	else
	{
		echo "<textarea id=data>decli";
		echo htmlspecialchars($jscode);
		echo "</textarea>";
	}
	$xt->load_template($templatefile);
	// add search controls for left menu layouts (Rome, London)
	$lookupSearchControls = $xt->fetch_loaded('searchform_field').'&nbsp;'
		.$xt->fetch_loaded('searchform_option').'&nbsp;'
		.$xt->fetch_loaded('searchform_text').'&nbsp;'
		.$xt->fetch_loaded('searchform_search').'&nbsp;'
		.$xt->fetch_loaded('searchform_showall').'&nbsp;';
	$xt->assign("lookupSearchControls",$lookupSearchControls);
	
	$xt->display_loaded("style_block");
	$xt->display_loaded("iestyle_block");
	$xt->display_loaded("body");
}

?>
