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

include("oldinclude/dbcommon.php");
include("oldinclude/##@TABLE.strShortTableName s##_variables.php");
##if @BUILDER.arrLanguages.len>1##
include("oldinclude/languages.php");
##endif##

##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
##endif##
	echo "<p>".##message NO_PERMISSIONS##." <a href=\"login.php\">".##message BACK_TO_LOGIN##."</a></p>";
	exit();
}
##else##
if(!IsAdmin())
{
	echo "<p>".##message NO_PERMISSIONS##." <a href=\"login.php\">".##message BACK_TO_LOGIN##."</a></p>";
	exit();
}
##endif##
##endif##


include('oldlibs/Smarty.class.php');
$smarty = new Smarty();



$conn=db_connect();


//	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"];

$smarty->assign("mastertable",$mastertable);
$smarty->assign("mastertable_short",GetTableURL($mastertable));
##endif##

##if @BUILDER.arrLanguages.len>1##
if(@$_REQUEST["language"])
	$_SESSION["language"]=@$_REQUEST["language"];
$smarty->assign("language",mlang_getcurrentlang());
##endif##

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

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='oldinclude/ibox.js'></script>\r\n";
$includes.="<link rel='stylesheet' href='oldinclude/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='oldinclude/ibox.js'></script>\r\n";
$includes.="<link rel='stylesheet' href='oldinclude/ibox.css' type='text/css' media='screen'/>\r\n";
	##endif##
	##endfor##
##endif##


$includes.="<script type=\"text/javascript\" src=\"oldinclude/jquery.js\"></script>\r\n";
if ($useAJAX) {
	$includes.="<script type=\"text/javascript\" src=\"oldinclude/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=\"oldinclude/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##
		
	##foreach Fields as @f filter (@f.bInlineEdit || @f.bInlineAdd)  && @f.bListPage && UseCalendar(@f)##
	##if @first##
	//	include datepicker files
	$includes.="<script type=\"text/javascript\" src=\"oldinclude/calendar.js\"></script>\r\n";
	##endif##
	##endfor##

##endif##

}
$includes.="<script type=\"text/javascript\" src=\"oldinclude/jsfunctions.js\">".
"</script>\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_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";

if ($useAJAX) {
	$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";
if ($useAJAX) {
$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##
}

$smarty->assign("includes",$includes);
$smarty->assign("useAJAX",$useAJAX);


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

##foreach Fields as @f filter @f.bListPage##
$smarty->assign("order_dir_##@f.strName g##","a");
##endfor##

$recno=1;
$numrows=0;


if(@$_SESSION[$strTableName."_orderby"])
{
	$order_field=substr($_SESSION[$strTableName."_orderby"],1);
	$order_dir=substr($_SESSION[$strTableName."_orderby"],0,1);
	$order_ind=GetFieldIndex($order_field);

	##foreach Fields as @f filter @f.bListPage##
	$smarty->assign("order_dir_##@f.strName g##","a");
	if($order_field=="##@f.strName s##")
	{
		if($order_dir=="a")
		{
			$smarty->assign("order_dir_##@f.strName g##","d");
			$img="up";
		}
		else
			$img="down";
		$smarty->assign("order_image_##@f.strName g##","<img src=\"images/".$img.".gif\" border=0>");
	}
	##endfor##

	if($order_ind)
	{
		if($order_dir=="a")
			$strOrderBy="order by ".($order_ind)." asc";
		else 
			$strOrderBy="order by ".($order_ind)." desc";
	}
}
if(!$strOrderBy)
	$strOrderBy=$gstrOrderBy;

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

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

	$smarty->assign("rpp10_selected",($PageSize==10)?"selected":"");
	$smarty->assign("rpp20_selected",($PageSize==20)?"selected":"");
	$smarty->assign("rpp30_selected",($PageSize==30)?"selected":"");
	$smarty->assign("rpp50_selected",($PageSize==50)?"selected":"");
	$smarty->assign("rpp100_selected",($PageSize==100)?"selected":"");
	$smarty->assign("rpp500_selected",($PageSize==500)?"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##"][$ind-1]);
##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);
}

//	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 = StrWhere($strSearchField, $strSearchFor, $strSearchOption, ""))
			$strWhereClause = whereAdd($strWhereClause,$where);
//			$strSQL = AddWhere($strSQL,$where);
		else
			$strWhereClause = whereAdd($strWhereClause,"1=0");
//			$strSQL = AddWhere($strSQL,"1=0");
	}
	else
	{
		$strWhere = "1=0";
		##foreach Fields as @f filter @f.bSearch##
		if($where=StrWhere("##@f.strName s##", $strSearchFor, $strSearchOption, ""))
			$strWhere .= " or ".$where;
		##endfor##
		$strWhereClause = whereAdd($strWhereClause,$strWhere);
//		$strSQL = AddWhere($strSQL,$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);
//		$strSQL = AddWhere($strSQL,$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);
//	$strSQL = AddWhere($strSQL,$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(CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"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)
	{
		$smarty->assign("rowsfound",false);
		$rowsfound=false;
		$message=##message NO_RECORDS##;
		##if @TABLE.bInlineAdd##
		$message = "<span name=\"notfound_message\">".$message."</span>";
		##endif##
		$smarty->assign("message",$message);
	}
	else
	{
		$smarty->assign("rowsfound",true);
		$rowsfound=true;
		$smarty->assign("records_found",$numrows);
		$maxRecords = $numrows;
		$maxpages=ceil($maxRecords/$PageSize);
		if($mypage > $maxpages)
			$mypage = $maxpages;
		if($mypage<1) 
			$mypage=1;
		$maxrecs=$PageSize;
		$smarty->assign("page",$mypage);
		$smarty->assign("maxpages",$maxpages);

//	write pagination
$smarty->assign("pagination","<script language=\"JavaScript\">WritePagination(".$mypage.",".$maxpages.");
		function GotoPage(nPageNumber)
		{
			window.location='##@TABLE.strShortTableName##_list.php?goto='+nPageNumber;
		}
</script>");
		
##if @BUILDER.nDatabaseType==DATABASE_MySQL##
		$strSQL.=" limit ".(($mypage-1)*$PageSize).",".$PageSize;
	}
	$rs=db_query($strSQL,$conn);
##elseif @BUILDER.nDatabaseType==DATABASE_MSSQLServer##
		$strSQL = AddTop($strSQL, $mypage*$PageSize);
	}
	$rs=db_query($strSQL,$conn);
	db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==DATABASE_Access##
		$strSQL = AddTop($strSQL, $mypage*$PageSize);
	}
	$rs=db_query_direct($strSQL,$conn,$numrows);
	db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==DATABASE_Oracle##
		$strSQL = AddRowNumber($strSQL, $mypage*$PageSize);
	}
	$rs=db_query_direct($strSQL,$conn,$numrows);
	db_pageseek($rs,$PageSize,$mypage);
##elseif @BUILDER.nDatabaseType==DATABASE_PostgreSQL##
		$maxrecs=$PageSize;
		$strSQL.=" limit ".$PageSize." offset ".(($mypage-1)*$PageSize);
	}
	$rs=db_query($strSQL,$conn);
##endif##

//	hide colunm headers if needed
	$recordsonpage=$numrows-($mypage-1)*$PageSize;
	if($recordsonpage>$PageSize)
	$recordsonpage=$PageSize;
##repeat @TABLE.nRecordsPerRowList @i##
	if($recordsonpage>=##@i##)
		$smarty->assign("column##@i##show",true);
	else
		$smarty->assign("column##@i##show",false);
##endrepeat##
##if @TABLE.bInlineAdd##
	$smarty->assign("column1show",true);
##endif##

##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="";

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

	while($data && $recno<=$PageSize)
	{
		$row=array();
##if !@TABLE.bListVerticalLayout##
		if(!$shade)
		{
			$row["shadeclass"]='class="shade"';
			$row["shadeclassname"]="shade";
			$shade=true;
		}
		else
		{
			$row["shadeclass"]="";
			$row["shadeclassname"]="";
			$shade=false;
		}
##endif##
		for($col=1;$data && $recno<=$PageSize && $col<=##@TABLE.nRecordsPerRowList##;$col++)
		{

##foreach Fields as @f filter @f.strTotalsType && @f.bListPage## 
			##if @f.strTotalsType=="COUNT"##
				$totals["##@f.strName s##"]+= ($data["##@f.strName s##"]!="");
			##else##
				$totals["##@f.strName s##"]+=($data["##@f.strName s##"]+0);
			##endif##
##endfor## 

##if SecurityEditOwn##
			$row[$col."editable"]=CheckSecurity($data["##@TABLE.strMainTableOwnerID s##"],"Edit");
##endif##
//	key fields
			$keyblock="";
##foreach @TABLE.arrKeyFields as @k##
			$row[$col."id##@index##"]=htmlspecialchars($data["##@k s##"]);
			$keyblock.=##if !@first## "&". ##endif## rawurlencode($data["##@k s##"]);
##endfor##
			$row[$col."keyblock"]=htmlspecialchars($keyblock);
##if @TABLE.bInlineEdit || @TABLE.bDelete || @TABLE.arrKeyFields.len && (@TABLE.bExportTo || @TABLE.bPrinterFriendly)##
			$row[$col."recno"] = $recno;
##endif##
//	detail tables
##foreach @BUILDER.Tables as @t filter @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].len##
			$masterquery="mastertable=##@TABLE.strDataSourceTable us##";
	##foreach @t.arrMasterTables[strMasterTable==@TABLE.strDataSourceTable].arrMasterKeys as @dk##
			$masterquery.="&masterkey##@index##=".rawurlencode($data["##@dk s##"]);
	##endfor##
			$row[$col."##@t.strShortTableName##_masterkeys"]=$masterquery;
##endfor##
//	edit page link
			$editlink="";
##foreach @TABLE.arrKeyFields as @k##
			$editlink.="##if !@first##&##endif##editid##@index##=".htmlspecialchars(rawurlencode($data["##@k s##"]));
##endfor##
			$row[$col."editlink"]=$editlink;

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

##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.php?field=##@f.strName uhs##".$keylink."\">";
				$value.= "<img border=0";
				$value.=" src=\"##@TABLE.strShortTableName s##_imager.php?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.php?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://" && !file_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.php?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##
/*	
			if(strlen($data["##@f.strName s##"]))
			{
				$strdata = make_db_value("##@f.strName s##",$data["##@f.strName s##"]);
				$LookupSQL="SELECT ";
			##if @f.EditFormatObj.pLookupObj.bCustomDisplay##
				$LookupSQL.="##@f.strDisplayField s##";
			##else## 
				$LookupSQL.="##@f.strDisplayField ws##";
			##endif##
				$LookupSQL.=" FROM ##@f.EditFormatObj.pLookupObj.strTable ts## WHERE ##@f.strLinkField ws## = " . $strdata;
			##if EditFormatObj.pLookupObj.strWhere##
				$LookupSQL.=" and (".##EditFormatObj.pLookupObj.strWhere##.")"; 
			##endif##
				LogInfo($LookupSQL);
				$rsLookup = db_query($LookupSQL,$conn);
				$lookupvalue=$data["##@f.strName s##"];
				if($lookuprow=db_fetch_numarray($rsLookup))
					$lookupvalue=$lookuprow[0];
				##if NeedEncode(@f)##
				$value=ProcessLargeText(GetDataInt($lookupvalue,$data,"##@f.strName s##", "##@f.strViewFormat s##"),"field=##@f.strName uhs##".$keylink,"",MODE_LIST);
				##else##
				$value=GetDataInt($lookupvalue,$data,"##@f.strName s##", "##@f.strViewFormat s##");
				##endif##
			}
			else
				$value="";
*/			
			$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##
			$row[$col."##@f.strName g##_value"]=$value;
##endfor##
			$row[$col."show"]=true;
			if(function_exists("BeforeMoveNextList"))
				BeforeMoveNextList($data,$row,$col);
##if @TABLE.bInlineEdit##
	##foreach Fields as @f filter @f.bListPage order @f.nListPageOrder##
			$span="<span ";
			$span.="id=\"edit".$recno."_##@f.strName g##\" ";
		##if @f.strTotalsType##
				$span.="value=\"".htmlspecialchars($data["##@f.strName s##"])."\" ";
		##endif##
			$span.=">";
			$row[$col."##@f.strName g##_value"] = $span.$row[$col."##@f.strName g##_value"]."</span>";
	##endfor##
##endif##
				
			while($data=db_fetch_array($rs))
			{
				if(function_exists("BeforeProcessRowList"))
				{
					if(!BeforeProcessRowList($data))
						continue;
				}
				break;
			}
			$recno++;
			
		}
		$rowinfo[]=$row;
	}
	$smarty->assign("rowinfo",$rowinfo);

	##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##
	$smarty->assign("showtotal_##@f.strName g##", $total);
	##endfor##
}


##if Fields[bSearch=1].len##
if(CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Search"))
{
	if($_SESSION[$strTableName."_search"]==1)
	{
		$onload = "onLoad=\"if(document.getElementById('SearchFor')) document.getElementById('ctlSearchFor').focus();\"";
		$smarty->assign("onload",$onload);
//	fill in search variables
	//	field selection
	##foreach Fields as @f filter @f.bSearch##
		if(@$_SESSION[$strTableName."_searchfield"]=="##@f.strName s##")
			$smarty->assign("search_##@f.strName g##","selected");
	##endfor##
	// search type selection
		if(@$_SESSION[$strTableName."_searchoption"]=="Contains")
			$smarty->assign("search_contains_option_selected","selected");		
		if(@$_SESSION[$strTableName."_searchoption"]=="Equals")
			$smarty->assign("search_equals_option_selected","selected");		
		if(@$_SESSION[$strTableName."_searchoption"]=="Starts with ...")
			$smarty->assign("search_startswith_option_selected","selected");		
		if(@$_SESSION[$strTableName."_searchoption"]=="More than ...")
			$smarty->assign("search_more_option_selected","selected");		
		if(@$_SESSION[$strTableName."_searchoption"]=="Less than ...")
			$smarty->assign("search_less_option_selected","selected");		
		if(@$_SESSION[$strTableName."_searchoption"]=="Equal or more than ...")
			$smarty->assign("search_equalormore_option_selected","selected");		
		if(@$_SESSION[$strTableName."_searchoption"]=="Equal or less than ...")
			$smarty->assign("search_equalorless_option_selected","selected");		
		if(@$_SESSION[$strTableName."_searchoption"]=="Empty")
			$smarty->assign("search_empty_option_selected","selected");		

		$smarty->assign("search_searchfor","value=\"".htmlspecialchars(@$_SESSION[$strTableName."_searchfor"])."\"");
	}
}
##endif##

##if @BUILDER.bCreateLoginPage##
$smarty->assign("userid",htmlspecialchars($_SESSION["UserID"]));
##endif##


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


##if GroupSecurity##
	$allow_add = CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Add");
	$smarty->assign("allow_delete",CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Delete"));
	$smarty->assign("allow_add",$allow_add);
	$smarty->assign("allow_edit",CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Edit"));
	$smarty->assign("allow_export",CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Export"));
	$smarty->assign("allow_import",CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Import"));
	$allow_search=CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Search");
	$smarty->assign("allow_search",$allow_search);
	$smarty->assign("allow_deleteorexport",CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Delete") || CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Export") );
##endif##


$display_grid=true;
##if GroupSecurity##
	##if !@TABLE.bInlineAdd##
$display_grid = $allow_search;
	##else##
$display_grid = $allow_add || $allow_search && $rowsfound;
	##endif##
##elseif !@TABLE.bInlineAdd##
$display_grid=$rowsfound;
##endif##

$display_records=$display_grid;
##if @TABLE.bInlineAdd##
##if GroupSecurity##
  $display_records = $rowsfound && $allow_search;
##else##
  $display_records = $rowsfound;
##endif##
##endif##
if(!$display_grid)
	$display_records=false;


$smarty->assign("display_grid",$display_grid);
$smarty->assign("display_records",$display_records);

##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("oldinclude/##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##_masterlist.php");
	##foreach @m.arrDetailKeys as @mk##
	$masterkeys[]=@$_SESSION[$strTableName."_masterkey##@index##"];
	##endfor##
	DisplayMasterTableInfo("##@TABLE.strDataSourceTable s##", $masterkeys);
	$smarty->assign("showmasterfile","##@BUILDER.Tables[strDataSourceTable==@m.strMasterTable].strShortTableName##_masterlist.htm");
}
##endfor##

$linkdata="";

if ($useAJAX) {
	$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='oldinclude/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##
}

if ($useAJAX) {
$linkdata.="<script>
if(!$('[@disptype=control1]').length && $('[@disptype=controltable1]').length)
	$('[@disptype=controltable1]').hide();
</script>";
}
$smarty->assign("linkdata",$linkdata);

##if @BUILDER.bDynamicPermissions##
$smarty->assign("admin",@$_SESSION["IsAdmin"]);
##endif##

$strSQL=$_SESSION[$strTableName."_sql"];
$smarty->assign("guest",$_SESSION["AccessLevel"] == ACCESS_LEVEL_GUEST);


##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##

$smarty->assign("url",$defaulturl);
##endif##


$templatefile = "##@TABLE.strShortTableName##_list.htm";
if(function_exists("BeforeShowList"))
	BeforeShowList($smarty,$templatefile);

$smarty->display($templatefile);

