<?php
ini_set("display_errors","1");
ini_set("display_startup_errors","1");
set_magic_quotes_runtime(0);
include("include/dbcommon.php");
header("Expires: Thu, 01 Jan 1970 00:00:01 GMT"); 

include("include/##@TABLE.strShortTableName s##_variables.php");

$gsqlHead="select ##@BUILDER.strUserNameField ws## ";
$gsqlFrom="from ##@BUILDER.strLoginTable ts##";
$gsqlWhereExpr="";
$gsqlTail="";
// $gstrSQL = "##@TABLE.strSQL ls##";
$gstrSQL = gSQLWhere("");

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


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


//	process reqest data, fill session variables

if(!count($_POST) && !count($_GET))
{
	$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[$strTableName."_search"]=0;
else if(@$_REQUEST["a"]=="search")
{
	$_SESSION[$strTableName."_searchfield"]=postvalue("SearchField");
	$_SESSION[$strTableName."_searchoption"]=postvalue("SearchOption");
	$_SESSION[$strTableName."_searchfor"]=postvalue("SearchFor");
	if(postvalue("SearchFor")!="" || postvalue("SearchOption")=='Empty')
		$_SESSION[$strTableName."_search"]=1;
	else
		$_SESSION[$strTableName."_search"]=0;
	$_SESSION[$strTableName."_pagenumber"]=1;
}
else if(@$_REQUEST["a"]=="advsearch")
{
	$_SESSION[$strTableName."_asearchnot"]=array();
	$_SESSION[$strTableName."_asearchopt"]=array();
	$_SESSION[$strTableName."_asearchfor"]=array();
	$_SESSION[$strTableName."_asearchfor2"]=array();
	$tosearch=0;
	$asearchfield = postvalue("asearchfield");
	$_SESSION[$strTableName."_asearchtype"] = postvalue("type");
	if(!$_SESSION[$strTableName."_asearchtype"])
		$_SESSION[$strTableName."_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[$strTableName."_asearchopt"][$field]=$asopt;
			if(!is_array($value1))
				$_SESSION[$strTableName."_asearchfor"][$field]=$value1;
			else
				$_SESSION[$strTableName."_asearchfor"][$field]=combinevalues($value1);
			$_SESSION[$strTableName."_asearchfortype"][$field]=$type;
			if($value2)
				$_SESSION[$strTableName."_asearchfor2"][$field]=$value2;
			$_SESSION[$strTableName."_asearchnot"][$field]=($not=="on");
		}
	}
	if($tosearch)
		$_SESSION[$strTableName."_search"]=2;
	else
		$_SESSION[$strTableName."_search"]=0;
	$_SESSION[$strTableName."_pagenumber"]=1;
}

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

	$xt->assign("mastertable_block",true);
//$smarty->assign("mastertable",$mastertable);
//$smarty->assign("mastertable_short",GetTableURL($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\"");
$xt->assign("languages_block",true);
##endif##

if(@$_REQUEST["orderby"])
{
	$_SESSION[$strTableName."_orderby"]=@$_REQUEST["orderby"];
	$_SESSION[$strTableName."_pagenumber"]=1;
}

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

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


//	process reqest data - end

$includes="";

##if Fields[bListPage && bUseiBox && bShowThumbnail].len##
$includes.="<script type='text/javascript' src='include/ibox.js'></script>\r\n";
$includes.="<link rel='stylesheet' href='include/ibox.css' type='text/css' media='screen'/>\r\n";
##else##
	##foreach @BUILDER.tables as @t filter @TABLE.arrMasterTables[strMasterTable==@t.strDataSourceTable] && @t.arrFieldObj[bListPage && bUseiBox && bShowThumbnail].len##
	##if @first## 
$includes.="<script type='text/javascript' src='include/ibox.js'></script>\r\n";
$includes.="<link rel='stylesheet' href='include/ibox.css' type='text/css' media='screen'/>\r\n";
	##endif##
	##endfor##
##endif##


$includes.="<script type=\"text/javascript\" src=\"include/jquery.js\"></script>\r\n";
$includes.="<script type=\"text/javascript\" src=\"include/ajaxsuggest.js\"></script>\r\n";
##if @TABLE.bInlineAdd || @TABLE.bInlineEdit##
//	validation stuff
	$editValidateTypes = array();
	$editValidateFields = array();
	$addValidateTypes = array();
	$addValidateFields = array();

	$includes.="<script type=\"text/javascript\" src=\"include/inlineedit.js\"></script>\r\n";
	##foreach Fields as @f filter @f.bInlineEdit && @f.bListPage##
	##if NeedValidationOnEdit(@f)##
		##if @f.strEditFormat!=EDIT_FORMAT_TEXT_FIELD && @f.strEditFormat!=EDIT_FORMAT_TIME##
			$validatetype="";
		##else##
			##if @f.EditFormatObj.strValidateAs==VALIDATE_AS_NUMBER##
				$validatetype="IsNumeric";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_PASSWORD##
				$validatetype="IsPassword";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_EMAIL##
				$validatetype="IsEmail";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_CURRENCY##
				$validatetype="IsMoney";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_ZIPCODE##
				$validatetype="IsZipCode";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_PHONENUMBER##
				$validatetype="IsPhoneNumber";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_STATE##
				$validatetype="IsState";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_SSN##
				$validatetype="IsSSN";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_CC##
				$validatetype="IsCC";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_TIME##
				$validatetype="IsTime";
			##else##
				$validatetype="";
			##endif##
		##endif##
		##if @f.EditFormatObj.bRequired && @f.strEditFormat!=EDIT_FORMAT_CHECKBOX && @f.strEditFormat!=EDIT_FORMAT_READONLY##
			$validatetype.="IsRequired";
		##endif##
			$editValidateTypes[] = $validatetype;
			$editValidateFields[] = "##@f.strname g##";
	##else##
		$editValidateTypes[] = "";
		$editValidateFields[] = "##@f.strname g##";
	##endif##
	##endfor##
	
	##foreach Fields as @f filter @f.bInlineAdd && @f.bListPage##
	##if NeedValidationOnAdd(@f)##
		##if @f.strEditFormat!=EDIT_FORMAT_TEXT_FIELD && @f.strEditFormat!=EDIT_FORMAT_TIME##
			$validatetype="";
		##else##
			##if @f.EditFormatObj.strValidateAs==VALIDATE_AS_NUMBER##
				$validatetype="IsNumeric";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_PASSWORD##
				$validatetype="IsPassword";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_EMAIL##
				$validatetype="IsEmail";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_CURRENCY##
				$validatetype="IsMoney";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_ZIPCODE##
				$validatetype="IsZipCode";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_PHONENUMBER##
				$validatetype="IsPhoneNumber";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_STATE##
				$validatetype="IsState";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_SSN##
				$validatetype="IsSSN";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_CC##
				$validatetype="IsCC";
			##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_TIME##
				$validatetype="IsTime";
			##else##
				$validatetype="";
			##endif##
		##endif##
		##if @f.EditFormatObj.bRequired && @f.strEditFormat!=EDIT_FORMAT_CHECKBOX && @f.strEditFormat!=EDIT_FORMAT_READONLY##
			$validatetype.="IsRequired";
		##endif##
			$addValidateTypes[] = $validatetype;
			$addValidateFields[] = "##@f.strName g##";
	##else##
		$addValidateTypes[] = "";
		$addValidateFields[] = "##@f.strName g##";
	##endif##
	##endfor##


	##foreach Fields as @f filter @f.bListPage && NeedValidation(@f)##
	##if @first##
	$includes.="<script type=\"text/javascript\">\r\n";
	$includes.="var TEXT_INLINE_FIELD_REQUIRED='".jsreplace(##message INLINE_FIELD_REQUIRED##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_ZIPCODE='".jsreplace(##message INLINE_FIELD_ZIPCODE##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_EMAIL='".jsreplace(##message INLINE_FIELD_EMAIL##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_NUMBER='".jsreplace(##message INLINE_FIELD_NUMBER##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_CURRENCY='".jsreplace(##message INLINE_FIELD_CURRENCY##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_PHONE='".jsreplace(##message INLINE_FIELD_PHONE##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_PASSWORD1='".jsreplace(##message INLINE_FIELD_PASSWORD1##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_PASSWORD2='".jsreplace(##message INLINE_FIELD_PASSWORD2##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_STATE='".jsreplace(##message INLINE_FIELD_STATE##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_SSN='".jsreplace(##message INLINE_FIELD_SSN##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_DATE='".jsreplace(##message INLINE_FIELD_DATE##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_TIME='".jsreplace(##message INLINE_FIELD_TIME##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_CC='".jsreplace(##message INLINE_FIELD_CC##)."';\r\n";
	$includes.="var TEXT_INLINE_FIELD_SSN='".jsreplace(##message INLINE_FIELD_SSN##)."';\r\n";
	$includes.= "</script>\r\n";
	##endif##	
	##endfor##

	##foreach Fields as @f filter @f.bInlineEdit && @f.bListPage##
	##if @first##
		$types_separated = implode(",", $editValidateTypes);
		$fields_separated = implode(",", $editValidateFields);
		$includes.="<script type=\"text/javascript\">\r\n";
		$includes.= "var editValidateTypes = String('".$types_separated."').split(',');"."\r\n";
		$includes.= "var editValidateFields = String('".$fields_separated."').split(',');"."\r\n";
		$includes.= "</script>\r\n";
	##endif##
	##endfor##

	##foreach Fields as @f filter @f.bInlineAdd && @f.bListPage##
	##if @first##
		$types_separated = implode(",", $addValidateTypes);
		$fields_separated = implode(",", $addValidateFields);
		$includes.="<script type=\"text/javascript\">\r\n";
		$includes.= "var addValidateTypes = String('".$types_separated."').split(',');"."\r\n";
		$includes.= "var addValidateFields = String('".$fields_separated."').split(',');"."\r\n";
		$includes.= "</script>\r\n";
	##endif##
	##endfor##	

##endif##

$includes.="<script language=\"JavaScript\" src=\"include/customlabels.js\"></script>\r\n".
"<script language=\"JavaScript\" src=\"include/jsfunctions.js\"></script>\r\n".
"<script type=\"text/javascript\">".
"\nvar bSelected=false;".
"\nvar TEXT_FIRST = \"".##message FIRST##."\";".
"\nvar TEXT_PREVIOUS = \"".##message PREVIOUS##."\";".
"\nvar TEXT_NEXT = \"".##message NEXT##."\";".
"\nvar TEXT_LAST = \"".##message LAST##."\";".
"\nvar TEXT_CTRL_CLICK = \"".##message CTRL_CLICK##."\";".
"\nvar TEXT_PLEASE_SELECT='".jsreplace(##message PLEASE_SELECT##)."';".
"\nvar TEXT_SAVE='".jsreplace(##message SAVE##)."';".
"\nvar TEXT_CANCEL='".jsreplace(##message CANCEL##)."';".
"\nvar TEXT_INLINE_ERROR='".jsreplace(##message INLINE_ERROR##)."';".
"\nvar locale_dateformat = ".$locale_info["LOCALE_IDATE"].";".
"\nvar locale_datedelimiter = \"".$locale_info["LOCALE_SDATE"]."\";".
"\nvar bLoading=false;\r\n";

	$includes.="var INLINE_EDIT_TABLE='##@TABLE.strShortTableName##_edit.php';\r\n";
	$includes.="var INLINE_ADD_TABLE='##@TABLE.strShortTableName##_add.php';\r\n";
	$includes.="var INLINE_VIEW_TABLE='##@TABLE.strShortTableName##_view.php';\r\n";
	$includes.="var SUGGEST_TABLE='##@TABLE.strShortTableName##_searchsuggest.php';\r\n";
	$includes.="var MASTER_PREVIEW_TABLE='##@TABLE.strShortTableName##_masterpreview.php';\r\n";
$includes.="\n</script>\n";
$includes.="<div id=\"search_suggest\"></div>";
$includes.="<div id=\"master_details\" onmouseover=\"RollDetailsLink.showPopup();\" onmouseout=\"RollDetailsLink.hidePopup();\"></div>";
##if @TABLE.bInlineEdit || @TABLE.bInlineAdd##
$includes.="<div id=\"inline_error\"></div>";
##endif##

$body = array();
$body["begin"]=$includes.'
<form name="frmSearch" method="GET" action="##@TABLE.strShortTableName##_list.php">
<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>';


//	process session variables
//	order by
$strOrderBy="";
$order_ind=-1;


$recno=1;
$numrows=0;

##foreach Fields as @f filter @f.bListPage##
$xt->assign("##@f.strName g##_orderlinkattrs","href=\"##@TABLE.strShortTableName##_list.php?orderby=a##@f.strName g##\"");
$xt->assign("##@f.strName g##_fieldheader",true);
##endfor##


//	save member assignments
if(postvalue("a")=="save")
{
	$useridx=0;
	foreach(postvalue("username") as $user)
	{
		$useridx++;
//	delete records which are not needed
		$sql="delete from ##@BUILDER.strUGMembers ts## where UserName='".db_addslashes($user)."'";
		if($user==$_SESSION["UserID"])
			$sql.=" and GroupID<>-1";
		db_exec($sql,$conn);
		if(count($_POST["cb_".$useridx]))
		{
			$glist="";
			foreach(@$_POST["cb_".$useridx] as $g)
			{
				if($g<0)
				{
					if($user==$_SESSION["UserID"] && $g==-1)
						continue;
					$sql="insert into ##@BUILDER.strUGMembers ts## (UserName,GroupID) values ('".htmlspecialchars($user)."',".$g.")";
					db_exec($sql,$conn);
				}
				else
				{
					if($glist!="")
						$glist.=",";
					$glist.=$g;
				}
			}
			if($glist!="")
			{
				$sql="insert into ##@BUILDER.strUGMembers ts## (UserName,GroupID) select '".htmlspecialchars($user)."',GroupID from ##@BUILDER.strUGGroups ts## where GroupID in (".$glist.")";
				db_exec($sql,$conn);
			}
		}
	}
}

if(@$_SESSION[$strTableName."_orderby"]=="D")
	$strOrderBy="Order by 1 desc";
else
	$strOrderBy="Order by 1 asc";

$sortbygroup=true;
if(!@$_SESSION[$strTableName."_orderby"] || @$_SESSION[$strTableName."_orderby"]=="A" || @$_SESSION[$strTableName."_orderby"]=="D")
	$sortbygroup=false;
//	page number
$mypage=(integer)$_SESSION[$strTableName."_pagenumber"];
if(!$mypage)
	$mypage=1;

//	page size
$PageSize=(integer)$_SESSION[$strTableName."_pagesize"];
if(!$PageSize)
	$PageSize=$gPageSize;

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


//	make sql "select" string

$strWhereClause="";

//	select groups list
$groups=array();
$groups[]=array(-1,"<Admin>");
$groupfullchecked=array();
$groupfullchecked[]=true;

$trs = db_query("select GroupID,Label from ##@BUILDER.strUGGroups ts## order by Label",$conn);
while($tdata = db_fetch_numarray($trs))
{
	$groups[]=array($tdata[0],$tdata[1]);
	$groupfullchecked[]=true;
}
//	select members list
$members=array();
$trs = db_query("select UserName,GroupID from ##@BUILDER.strUGMembers ts## order by UserName,GroupID",$conn);
while($tdata = db_fetch_numarray($trs))
{
	$members[]=array($tdata[1],$tdata[0]);
}

$smartygroups = array();
foreach($groups as $g)
{
	$smartygroups[]=array("groupname"=>htmlspecialchars($g[1]),
	"groupheaderlink_attrs"=>"href=\"##@TABLE.strShortTableName h##_list.##@ext##?orderby=a".$g[0]."\"",
	"groupheaderbox_attrs"=>"name=\"".$g[0]."\" onclick=\"var chk = this.checked; \$('input[@type=checkbox][@value\='+this.name+'][@name^=cb_]').each( function(){this.checked=chk;})\""
	);
}


// 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);
}

//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)
	$xt->assign("menu_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##


//	make sql "select" string

//$strSQL = $gstrSQL;
$strWhereClause="";

//	add search params

if(@$_SESSION[$strTableName."_search"]==1)
//	 regular search
{  
	$strSearchFor=trim($_SESSION[$strTableName."_searchfor"]);
	$strSearchOption=trim($_SESSION[$strTableName."_searchoption"]);
	if(@$_SESSION[$strTableName."_searchfield"])
	{
		$strSearchField = $_SESSION[$strTableName."_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[$strTableName."_search"]==2)
//	 advanced search
{
	$sWhere="";
	foreach(@$_SESSION[$strTableName."_asearchfor"] as $f => $sfor)
		{
			$strSearchFor=trim($sfor);
			$strSearchFor2="";
			$type=@$_SESSION[$strTableName."_asearchfortype"][$f];
			if(array_key_exists($f,@$_SESSION[$strTableName."_asearchfor2"]))
				$strSearchFor2=trim(@$_SESSION[$strTableName."_asearchfor2"][$f]);
			if($strSearchFor!="" || true)
			{
				if (!$sWhere) 
				{
					if($_SESSION[$strTableName."_asearchtype"]=="and")
						$sWhere="1=1";
					else
						$sWhere="1=0";
				}
				$strSearchOption=trim($_SESSION[$strTableName."_asearchopt"][$f]);
				if($where=StrWhereAdv($f, $strSearchFor, $strSearchOption, $strSearchFor2,$type))
				{
					if($_SESSION[$strTableName."_asearchnot"][$f])
						$where="not (".$where.")";
					if($_SESSION[$strTableName."_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##

##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[$strTableName."_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[$strTableName."_sql"] = $strSQL;
$_SESSION[$strTableName."_where"] = $strWhereClause;
$_SESSION[$strTableName."_order"] = $strOrderBy;

$rowsfound=false;

//	select and display records
if($allow_search)
{
	$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\">";
		$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);
		$xt->assign("pagination","<script language=\"JavaScript\">WritePagination(".$mypage.",".$maxpages.");
		function GotoPage(nPageNumber)
		{
			window.location='##@TABLE.strShortTableName##_list.php?goto='+nPageNumber;
		}
		</script>");
	}

	if(!$sortbygroup)
	{
##if @BUILDER.nDatabaseType==nDATABASE_MySQL##
		$strSQL.=" limit ".(($mypage-1)*$PageSize).",".$PageSize;
##elseif @BUILDER.nDatabaseType==nDATABASE_MSSQLServer##
		$strSQL = AddTop($strSQL, $mypage*$PageSize);
##elseif @BUILDER.nDatabaseType==nDATABASE_Access##
		$strSQL = AddTop($strSQL, $mypage*$PageSize);
##elseif @BUILDER.nDatabaseType==nDATABASE_Oracle##
		$strSQL = AddRowNumber($strSQL, $mypage*$PageSize);
##elseif @BUILDER.nDatabaseType==nDATABASE_PostgreSQL##
		$maxrecs=$PageSize;
		$strSQL.=" limit ".$PageSize." offset ".(($mypage-1)*$PageSize);
##endif##
	}
##if @BUILDER.nDatabaseType==nDATABASE_MySQL##
	$rs=db_query($strSQL,$conn);
##elseif @BUILDER.nDatabaseType==nDATABASE_MSSQLServer##
	$rs=db_query($strSQL,$conn);
	db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==nDATABASE_Access##
	$rs=db_query_direct($strSQL,$conn,$numrows);
	db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==nDATABASE_Oracle##
	$rs=db_query_direct($strSQL,$conn,$numrows);
	db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==nDATABASE_PostgreSQL##
	$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();
	$shade=false;
	$editlink="";
	$copylink="";

##if @TABLE.bInlineAdd##
	if($allow_add)
	{
//	add inline add row	
		$row=array();
		$row["rowattrs"]="class=\"addarea\"";
		$row["rowspace_attrs"]="class=\"addarea\"";
		$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\"";
		$record["inlineeditlink_attrs"]= "id=\"ieditlink_add\"";
		$record["copylink_attrs"]="id=\"copylink_add\"";
		$record["viewlink_attrs"]="id=\"viewlink_add\"";
		$record["checkbox_attrs"]="id=\"checklink_add\" name=\"selection[]\"";
##foreach @BUILDER.Tables as @t filter @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].len##
//detail tables
		$record["##@t.strShortTableName##_dtable_link"]=true;
		$record["##@t.strShortTableName##_dtablelink_attrs"]="onmouseover=\"RollDetailsLink.showPopup(this,'##@t.strShortTableName h##_detailspreview.##@ext##'+this.href.substr(this.href.indexOf('?')));\" onmouseout=\"RollDetailsLink.hidePopup();\" href=\"##@t.strShortTableName h##_list.##@ext##?\" id=\"master_##@t.strShortTableName##_add\"";
##endfor##
##foreach Fields as @f filter @f.bListPage order @f.nListPageOrder##
		$record["##@f.strName g##_value"] = "<span id=\"add_##@f.strName g##\">&nbsp;</span>";
##endfor##
		if($colsonpage>1)
			$record["endrecord_block"]=true;
		$record["grid_recordheader"]=true;
		$record["grid_vrecord"]=true;
		$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[]=$row;
	}
##endif##
	

//	add grid data	
	
	while($data=db_fetch_array($rs))
	{
		if(function_exists("BeforeProcessRowList"))
		{
			if(!BeforeProcessRowList($data))
				continue;
		}
		break;
	}

	while($data && ($sortbygroup || $recno<=$PageSize))
	{
	
		$row=array();
##if !@TABLE.bListVerticalLayout##
		if(!$shade)
		{
			$row["rowattrs"]="class=shade onmouseover=\"this.className = 'rowselected';\" onmouseout=\"this.className = 'shade';\"";
			$shade=true;
		}
		else
		{
			$row["rowattrs"]="onmouseover=\"this.className = 'rowselected';\" onmouseout=\"this.className = '';\"";
			$shade=false;
		}
		$row["grid_record"]=array();
		$row["grid_record"]["data"]=array();
##endif##

//	create checkboxes		
		$member_indexes=array();
		foreach($members as $idx=>$m)
		{
			if($m[1]==$data["##@BUILDER.strUserNameField s##"])
				$member_indexes[]=$idx;
		}
		$rowgroups=array();
		$userfullchecked=true;
		foreach($groups as $idx=>$g)
		{
			$checked=false;
			$smarty_group=array();
			foreach($member_indexes as $i)
			{
				if($members[$i][0]==$g[0])
				{
					$checked=true;
					break;
				}
			}
			$smarty_group["groupbox_attrs"]="name=\"cb_".$recno."[]\" value=\"".$g[0]."\"";
			$smarty_group["checked"]=0;
			if(!$checked)
			{
				$userfullchecked=false;
				$groupfullchecked[$idx]=false;
			}
			else
			{
				$smarty_group["groupbox_attrs"].=" checked";
				$smarty_group["checked"]=1;
			}
			$smarty_group["group"]=$g[0];
			$rowgroups[]=$smarty_group;
		}
		$row["usergroup_boxes"]=array("data"=>$rowgroups);
		$usercheckbox_attrs="";
		if($userfullchecked)
			$usercheckbox_attrs.=" checked";
		$row["begin"]="<input type=hidden name=\"username[]\" value=\"".htmlspecialchars($data["##@BUILDER.strUserNameField s##"])."\">";
		$row["username"]=htmlspecialchars($data["##@BUILDER.strUserNameField s##"]);
		$row["user"]=$data["##@BUILDER.strUserNameField s##"];
		$usercheckbox_attrs.=" name=\"user_".htmlspecialchars($data["##@BUILDER.strUserNameField s##"])."\"";
		$usercheckbox_attrs.=" onclick=\"var ch=document.getElementsByName('cb_".$recno."[]');
			for(i=0;i<ch.length;i++)
				ch[i].checked=this.checked;
			return true;\"";
		$row["usercheckbox_attrs"]=$usercheckbox_attrs;
		$recno++;

//	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;
		
		if(function_exists("BeforeMoveNextList"))
			BeforeMoveNextList($data,$row,$record);
		$rowinfo[]=$row;
		while($data=db_fetch_array($rs))
			{
				if(function_exists("BeforeProcessRowList"))
				{
					if(!BeforeProcessRowList($data))
						continue;
				}
				break;
			}
		
	}

	foreach($smartygroups as $idx=>$g)
	{
		if($groupfullchecked[$idx])
			$smartygroups[$idx]["groupheaderbox_attrs"].=" checked";
	}
	
//	sort rowinfo
if($sortbygroup)
{
	$sortgroup=substr($_SESSION[$strTableName."_orderby"],1);
	$sortorder=substr($_SESSION[$strTableName."_orderby"],0,1);
	DPOrderUsers($rowinfo);
	
// apply pagination
	$firstindex=$PageSize*($mypage-1);
	for($i=0;$i<$firstindex;$i++)
		array_shift($rowinfo);
	if(count($rowinfo)>$PageSize)
		array_splice($rowinfo,$PageSize,count($rowinfo)-$PageSize);
	$recno=1;
	$shade=false;
	for($i=0;$i<count($rowinfo);$i++)
	{
		for($j=0;$j<count($rowinfo[$i]["usergroup_boxes"]["data"]);$j++)
		{
			$rowinfo[$i]["usergroup_boxes"]["data"][$j]["groupbox_attrs"]="name=\"cb_".$recno."[]\" value=\"".$rowinfo[$i]["usergroup_boxes"]["data"][$j]["group"]."\"";
			if($rowinfo[$i]["usergroup_boxes"]["data"][$j]["checked"])
				$rowinfo[$i]["usergroup_boxes"]["data"][$j]["groupbox_attrs"].=" checked";
		}
		$recno++;
		if(!$shade)
		{
			$rowinfo[$i]["shadeclass"]='class="shade"';
			$rowinfo[$i]["shadeclassname"]="shade";
			$shade=true;
		}
		else
		{
			$rowinfo[$i]["shadeclass"]="";
			$rowinfo[$i]["shadeclassname"]="";
			$shade=false;
		}
	}
}

//		assign sort links
foreach($groups as $i=>$g)
{
	if($sortbygroup && $sortgroup==$g[0] && $sortorder=="a")
	{
		$smartygroups[$i]["groupheaderlink_attrs"]="href=\"##@TABLE.strShortTableName h##_list.##@ext##?orderby=d".$g[0]."\"";
		$smartygroups[$i]["groupheader_img"] = "<img src=\"images/up.gif\" border=0>";
	}
	else
	{
//		$smartygroups[$i]["order_link"]="a".$g[0];
		if($sortbygroup && $sortgroup==$g[0] && $sortorder=="d")
		$smartygroups[$i]["groupheader_img"] = "<img src=\"images/down.gif\" border=0>";
	}
		
}
$userheaderlink_attrs = "href=\"##@TABLE.strShortTableName h##_list.##@ext##?orderby=";
if($sortbygroup || @$_SESSION[$strTableName."_orderby"]!="A")
	$userheaderlink_attrs.="A";
else
	$userheaderlink_attrs.="D";
$userheaderlink_attrs.="\"";
$xt->assign("userheaderlink_attrs",$userheaderlink_attrs);
if(!$sortbygroup)
{
	if(@$_SESSION[$strTableName."_orderby"]=="A")
		$xt->assign("users_orderimg","<img src=\"images/up.gif\" border=0>");
	else if(@$_SESSION[$strTableName."_orderby"]=="D")
		$xt->assign("users_orderimg","<img src=\"images/down.gif\" border=0>");
}
	$xt->assign_loopsection("grid_row",$rowinfo);
	$xt->assign_loopsection("usergroup_header",$smartygroups);


##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_##@f.strName g##\" type=\"##@f.strTotalsType##\">".$total."</span>";
	##endif##
		$record["##@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(); return false;\"";
##endif##
	if($_SESSION[$strTableName."_search"]==1)
	{
//	fill in search variables
	//	field selection
		if(@$_SESSION[$strTableName."_searchfield"])
			$xt->assign(GoodFieldName(@$_SESSION[$strTableName."_searchfield"])."_searchfieldoption","selected");
	// search type selection
		$xt->assign(GoodFieldName(@$_SESSION[$strTableName."_searchoption"])."_searchtypeoption","selected");
		$searchfor_attrs.=" value=\"".htmlspecialchars(@$_SESSION[$strTableName."_searchfor"])."\"";
	}
	$searchfor_attrs.=" name=\"ctlSearchFor\" id=\"ctlSearchFor\"";
	$xt->assign("searchfor_attrs",$searchfor_attrs);
	$xt->assign("searchbutton_attrs","onClick=\"javascript: RunSearch();\"");
	$xt->assign("showallbutton_attrs","onClick=\"javascript: document.forms.frmSearch.a.value = 'showall'; document.forms.frmSearch.submit();\"");
}
##endif##

##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","onclick=\"window.open('##@TABLE.strShortTableName h##_print.##@ext##','wPrint');return false;\"");
	$xt->assign("printalllink_attrs","onclick=\"window.open('##@TABLE.strShortTableName h##_print.##@ext##?all=1','wPrint');return false;\"");
	$xt->assign("export_link",$allow_export);
	$xt->assign("exportlink_attrs","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';\"");
	$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';\"");
	
	$xt->assign("add_link",$allow_add);
	$xt->assign("inlineadd_link",$allow_add);
	$xt->assign("addlink_attrs","onClick=\"window.location.href='##@TABLE.strShortTableName h##_add.##@ext##'\"");
	$xt->assign("inlineaddlink_attrs","onclick=\"return inlineAdd(newrecord_id++);\"");

	
	$xt->assign("checkbox_column",$allow_delete || $allow_export  || $allow_edit);
	$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","disptype=\"control1\" name=\"edit_selected\" 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\" style=\"display:none\" onclick=\"\$('a[@id^=save_]').click();\"");
	$xt->assign("cancelall_link",$allow_edit||$allow_edit);
	$xt->assign("cancelalllink_attrs","disptype=\"control1\" name=\"revertall_edited\" style=\"display:none\" onclick=\"\$('a[@id^=revert_]').click();\"");
	

	$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##
 	$xt->assign("##@t.strShortTableName##_dtable_column",$allow_##@t.strShortTableName##);
##endfor##


##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","onclick=\"window.location.href='##@TABLE.strShortTableName h##_search.##@ext##';return false;\"");
$xt->assign("import_link",$allow_import);
$xt->assign("importlink_attrs","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_field",$allow_search);
$xt->assign("searchform_option",$allow_search);
$xt->assign("searchform_text",$allow_search);
$xt->assign("searchform_search",$allow_search);
$xt->assign("searchform_showall",$allow_search);

$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;\"");
$xt->assign("usermessage",true);

if($display_grid)
{
	$xt->assign_section("grid_block",
	"<form method=\"POST\" action=\"##@TABLE.strShortTableName h##_list.php\" name=\"frmAdmin\" id=\"frmAdmin\">
	<input type=\"hidden\" id=\"a\" name=\"a\" value=\"save\">",
	"</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);
	$xt->assign("grid_footer",true);



}


$xt->assign("details_block",$allow_search && $rowsfound);
$xt->assign("pages_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("grid_controls",$display_grid);



##foreach @TABLE.arrMasterTables as @m filter @m.bDisplayInfo##
##if @first##
//	display master table info
$masterkeys=array();
//$smarty->assign("showmasterfile","empty.htm");
##endif##
if($mastertable=="##@m.strMasterTable s##")
{
//	include proper masterlist.php code
	include("include/##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##_masterlist.php");
	##foreach @m.arrDetailKeys as @mk##
	$masterkeys[]=@$_SESSION[$strTableName."_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);
	$xt->assign("backtomaster_link",true);
	$xt->assign("mastertable_short","##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##");
//	DisplayMasterTableInfo("##@TABLE.strDataSourceTable s##", $masterkeys);
//	$smarty->assign("showmasterfile","##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##_masterlist.htm");
}
##endfor##

$linkdata="";

$linkdata .= "<script type=\"text/javascript\">\r\n";

##if @TABLE.bInlineAdd##
	$linkdata.="\$(\".addarea\").each(function(i) { \$(this).hide();});\r\n";
	$linkdata.="var newrecord_id=".($recno+1).";\r\n";
	$linkdata.="var newrecord_tempid=0;\r\n";
	if(!$numrows)
	{
		$linkdata .= "$('[@name=record_controls]').hide();
			$('[@name=maintable]').hide();";
	}
##endif##
	$linkdata .= "</script>\r\n";
##if @TABLE.bInlineAdd || @TABLE.bInlineEdit##
$linkdata .= "<script type='text/javascript' src='include/onthefly.js'></script>\r\n";

$linkdata .= "<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##
$linkdata.="<script>
if(!$('[@disptype=control1]').length && $('[@disptype=controltable1]').length)
	$('[@disptype=controltable1]').hide();
</script>";
if($_SESSION[$strTableName."_search"]==1)
	$linkdata.= "<script>if(document.getElementById('SearchFor')) document.getElementById('ctlSearchFor').focus();</script>";

$body["end"]=$linkdata;
$xt->assignbyref("body",$body);
$xt->assign("style_block",true);
$xt->assign("iestyle_block",true);
$xt->assign("security_block",true);

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

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


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

$xt->assign("exitaa_attrs","href=\"".$defaulturl."\" onclick=\"window.location.href='".$defaulturl."';return false;\"");
##endif##

##if CreateMenu##
$xt->assign("quickjump_attrs","onchange=\"window.location.href=this.options[this.selectedIndex].value;\"");
##endif##
$xt->assign("recordcontrols_block",true);
$xt->assign("savebuttons_block",true);
$xt->assign("savebutton_attrs","onclick=\"document.forms.frmAdmin.submit();\"");
$xt->assign("resetbutton_attrs","onclick=\"document.forms.frmAdmin.reset();\"");


$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.php\"");
$xt->assign("admin_members_tablelink",true);
$xt->assign("admin_members_tablelink_attrs","href=\"admin_members_list.php\"");
$xt->assign("admin_users_tablelink",true);
$xt->assign("admin_users_tablelink_attrs","href=\"admin_users_list.php\"");
$xt->assign("admin_rights_optionattrs","value=\"admin_rights_list.php\"");
$xt->assign("admin_members_optionattrs","value=\"admin_members_list.php\"");
$xt->assign("admin_users_optionattrs","value=\"admin_users_list.php\"");
$xt->assign("quickjump_attrs","onchange=\"window.location.href=this.options[this.selectedIndex].value;\"");

$xt->assign("shiftstyle_block",true);
$xt->assign("left_block",true);


$templatefile = "admin_members_list.htm";


$xt->display($templatefile);

