<?php 
ini_set("display_errors","1");
ini_set("display_startup_errors","1");
set_magic_quotes_runtime(0); 

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


##if @BUILDER.bCreateLoginPage##
//	check if logged in

##if @BUILDER.bDynamicPermissions##
if(@$_SESSION["UserID"] && IsAdmin() && !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Add"))
{
	echo "<p>".##message NO_PERMISSIONS##."<br>Proceed to <a href=\"admin.php\">Admin Area</a> to set up user permissions</p>";
	return;
}
##endif##
if(!@$_SESSION["UserID"] || !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Add"))
{ 
	$_SESSION["MyURL"]=$_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
	header("Location: login.php?message=expired"); 
	return;
}
##endif##

$filename="";
$status="";
$message="";
$usermessage="";
$error_happened=false;
$readavalues=false;


$showKeys = array();
$showValues = array();
$showRawValues = array();
$showFields = array();
$showDetailKeys = array();
$IsSaved = false;
$HaveData = true;
if(@$_REQUEST["editType"]=="inline")
	$inlineedit=ADD_INLINE;
elseif(@$_REQUEST["editType"]=="onthefly")
	$inlineedit=ADD_ONTHEFLY;
else
	$inlineedit=ADD_SIMPLE;
$keys=array();
##if @TABLE.bInlineAdd##
if($inlineedit==ADD_INLINE)
	$templatefile = "##@TABLE.strShortTableName s##_inline_add.htm";
else
	$templatefile = "##@TABLE.strShortTableName##_add.htm";
##else##
$templatefile = "##@TABLE.strShortTableName##_add.htm";
##endif##

//connect database
$conn = db_connect();

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

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

// insert new record if we have to

if(@$_POST["a"]=="added")
{
	$afilename_values=array();
	$avalues=array();
##if @BUILDER.nDatabaseType==DATABASE_Oracle##
	$blobs=array();
##endif##
	$files_move=array();
##foreach Fields as @f filter (@f.bAddPage || @f.bInlineAdd)  order @f.nAddPageOrder##
//	processing ##@f.strName## - start
##if !@f.bAddPage##
	if($inlineedit==ADD_INLINE)
	{
##elseif !@f.bInlineAdd##
	if($inlineedit!=ADD_INLINE)
	{
##endif##
	$value = postvalue("value_##@f.strName g##");
	$type=postvalue("type_##@f.strName g##");
	if (in_assoc_array("type_##@f.strName g##",$_POST) || in_assoc_array("value_##@f.strName g##",$_POST) || in_assoc_array("value_##@f.strName g##",$_FILES))
	{
##if @f.strEditFormat==EDIT_FORMAT_DATABASE_FILE && @f.ListFormatObj.strFilename##
		$value=prepare_for_db("##@f.strName s##",$value,$type,postvalue("filename_##@f.strName g##"));
##else##
		$value=prepare_for_db("##@f.strName s##",$value,$type);
##endif##
	}
	else
		$value=false;
	if(!($value===false))
	{
##if @f.bCreateThumbnail && (@f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE || @f.strEditFormat==EDIT_FORMAT_FILE)##
		if($value)
		{
	##if @f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE##
			$ext = CheckImageExtension($_FILES["value_##@f.strName g##"]["name"]);
			$thumb = CreateThumbnail($value,##@f.nThumbnailSize##,$ext);
		##if @BUILDER.nDatabaseType==DATABASE_Oracle##
			$blobs["##@f.strThumbnail s##"]=$thumb;
			$avalues["##@f.strThumbnail s##"]="EMPTY_BLOB()";
		##else##
			$avalues["##@f.strThumbnail s##"]=$thumb;
		##endif##
	##else##
			$ext = CheckImageExtension($_FILES["file_##@f.strName g##"]["name"]);
			$contents = myfile_get_contents($_FILES["file_##@f.strName g##"]['tmp_name']);
			$thumb = CreateThumbnail($contents,##@f.nThumbnailSize##,$ext);
			$file = GetUploadFolder("##@f.strName s##")."##@f.strThumbnail s##".$value;
			if(file_exists($file))
					@unlink($file);
			$th = fopen($file,"w");
			fwrite($th,$thumb);
			fclose($th);
	##endif##
		}
##endif##

##if @f.bResizeOnUpload && (@f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE || @f.strEditFormat==EDIT_FORMAT_FILE)##
	// resize image on upload
		if($value)
		{
	##if @f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE##
			$ext = CheckImageExtension($_FILES["value_##@f.strName g##"]["name"]);
			$thumb = CreateThumbnail($value,##@f.nNewSize##,$ext);
		##if @BUILDER.nDatabaseType==DATABASE_Oracle##
			$blobs["##@f.strName s##"]=$thumb;
			$value="EMPTY_BLOB()";
		##else##
			$value=$thumb;
		##endif##
	##else##
			$ext = CheckImageExtension($_FILES["file_##@f.strName g##"]["name"]);
			$contents = myfile_get_contents($_FILES["file_##@f.strName g##"]['tmp_name']);
			$thumb = CreateThumbnail($contents,##@f.nNewSize##,$ext);
			$file = GetUploadFolder("##@f.strName s##").$value;
			if(file_exists($file))
					@unlink($file);
			$th = fopen($file,"w");
			fwrite($th,$thumb);
			fclose($th);
			$n = array_search(GetUploadFolder("##@f.strName s##").$value, $files_move);
			array_splice($files_move, $n, 1);
	##endif##
		}
##endif##

##if @BUILDER.nDatabaseType==DATABASE_Oracle && !@f.bResizeOnUpload && (@f.strEditFormat==EDIT_FORMAT_DATABASE_FILE || @f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE)##
		$blobs["##@f.strName s##"]=$value;
		$avalues["##@f.strName s##"]="EMPTY_BLOB()";
##else##
		$avalues["##@f.strName s##"]=$value;
##endif##
	}
##if @f.strEditFormat==EDIT_FORMAT_DATABASE_FILE && @f.ListFormatObj.strFilename##
	if($filename)
		$afilename_values["##@f.ListFormatObj.strFilename s##"]=$filename;
##endif##			
##if !@f.bInlineAdd || !@f.bAddPage##
	}
##endif##
//	processibng ##@f.strName## - end
##endfor##


##if SecurityViewEditOwn##
//	insert ownerid value if exists
	$avalues["##@TABLE.strMainTableOwnerID s##"]=prepare_for_db("##@TABLE.strMainTableOwnerID s##",$_SESSION["_".$strTableName."_OwnerID"]);
##endif##


##if @TABLE.arrMasterTables.len##
//	insert masterkey value if exists and if not specified
	##foreach @TABLE.arrMasterTables as @m##
	if(@$_SESSION[$strTableName."_mastertable"]=="##@m.strMasterTable s##")
	{
		##foreach @m.arrDetailKeys as @dk##
		$avalues["##@dk s##"]=prepare_for_db("##@dk s##",$_SESSION[$strTableName."_masterkey##@index##"]);
		##endfor##
	}
	##endfor##
##endif##

if($inlineedit==ADD_ONTHEFLY)
{
##foreach @BUILDER.tables as @t##
##foreach @t.arrFieldObj as @f filter @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.bAllowToAdd && @f.nLookupType==LT_LOOKUPTABLE && @f.pLookupObj.strTable==@TABLE.strDataSourceTable && @f.bUseCategory##
	if(postvalue("table")=="##@t.strShortTableName##" && postvalue("field")=="##@f.strName g##") 
	{
		if(!array_key_exists("##@f.strCategoryFilterField##",$avalues))
			$avalues["##@f.strCategoryFilterField##"]=postvalue("category");
	}
##endfor##
##endfor##
}


//	add filenames to values
	foreach($afilename_values as $akey=>$value)
		$avalues[$akey]=$value;
//	make SQL string
	$strSQL = "insert into ".AddTableWrappers($strOriginalTableName)." ";
	$strFields="(";
	$strValues="(";
	
//	before Add event
	$retval = true;
	if(function_exists("BeforeAdd"))
		$retval=BeforeAdd($avalues,$usermessage,$inlineedit);
	if($retval)
	{
		foreach($avalues as $akey=>$value)
		{
			$strFields.=AddFieldWrappers($akey).", ";
			$strValues.=add_db_quotes($akey,$value).", ";
		}
		if(substr($strFields,-2)==", ")
			$strFields=substr($strFields,0,strlen($strFields)-2);
		if(substr($strValues,-2)==", ")
			$strValues=substr($strValues,0,strlen($strValues)-2);
		$strSQL.=$strFields.") values ".$strValues.")";
##if @BUILDER.nDatabaseType==DATABASE_Oracle##
		$locs=array();
		if(count($blobs))
		{
			$strSQL.=" returning ";
			$blobfields="";
			$blobvars="";
			$idx=1;
			foreach($blobs as $akey=>$value)
			{
				if(count($locs))
				{
					$blobfields.=",";
					$blobvars.=",";
				}
				$blobfields.=AddFieldWrappers($akey);
				$blobvars.=":bnd".$idx;
				$locs[$akey]=OCINewDescriptor($conn, OCI_D_LOB);
			}
			$strSQL.=$blobfields." into ".$blobvars;
			$idx++;
		}
		$stmt=OCIParse($conn,$strSQL);
		$idx=1;
		foreach($locs as $akey=>$value)
		{
			OCIBindByName($stmt,":bnd".$idx,$locs[$akey],-1,OCI_B_BLOB);
			$idx++;
		}
		LogInfo($strSQL);
		set_error_handler("add_error_handler");
		OCIExecute($stmt, OCI_DEFAULT);
		foreach($locs as $akey=>$value)
		{
			$locs[$akey]->save($blobs[$akey]);
			$locs[$akey]->free();
		}
		OCICommit($conn);
		OCIFreeStatement($stmt);
##else##
		LogInfo($strSQL);
		set_error_handler("add_error_handler");
		db_exec($strSQL,$conn);
##endif##
		set_error_handler("error_handler");
//	move files
		if(!$error_happened)
		{
			foreach ($files_move as $file)
			{
				move_uploaded_file($file[0],$file[1]);
				if(strtoupper(substr(PHP_OS,0,3))!="WIN")
					@chmod($file[1],0777);
			}
##if @TABLE.bInlineAdd##
			if ( $inlineedit==ADD_INLINE ) 
			{
				$status="ADDED";
				$message="".##message RECORD_ADDED##."";
				$IsSaved = true;
			} 
			else
				$message="<div class=message><<< ".##message RECORD_ADDED##." >>></div>";
##else##
			$message="<div class=message><<< ".##message RECORD_ADDED##." >>></div>";
##endif##				
			if($usermessage!="")
				$message = $usermessage;
if($inlineedit==ADD_INLINE || $inlineedit==ADD_ONTHEFLY || function_exists("AfterAdd"))
{

	$failed_inline_add = false;
	##foreach @TABLE.arrKeyFields as @k##
	##if Fields[strName=@k].bInlineAdd##
	$keys["##@k s##"]=$avalues["##@k s##"];
	##elseif Fields[strName=@k].bAutoInc##
		##if @BUILDER.nDatabaseType==DATABASE_MySQL##
			$keys["##@k s##"]=mysql_insert_id($conn);
		##elseif @BUILDER.nDatabaseType==DATABASE_MSSQLServer##
			$lastrs = db_query("select @@IDENTITY",$conn);
			if($lastdata = db_fetch_numarray($lastrs))
				$keys["##@k s##"]=$lastdata[0];
		##elseif @BUILDER.nDatabaseType==DATABASE_PostgreSQL##
			$seqname=db_addslashes("##@TABLE.strOriginalTable s##_##@k s##_seq");
			$lastrs = @db_query("SELECT currval('".$seqname."')",$conn);
			if($lastdata = db_fetch_numarray($lastrs))
				$keys["##@k s##"]=$lastdata[0];
		##else##
			$mystrSQL = "SELECT MAX(##@k s##) FROM ".AddTableWrappers($strOriginalTableName);
			$myrs=db_query($mystrSQL,$conn);
			if($mydata = db_fetch_numarray($myrs));
				$keys["##@k s##"] = $mydata[0];
		##endif##
	##else##
	if(array_key_exists("##@k s##",$avalues))
		$keys["##@k s##"]=$avalues["##@k s##"];
	else
		$failed_inline_add = true;
	##endif##
	##endfor##
}	

//	after edit event
			if(function_exists("AfterAdd"))
			{
				foreach($keys as $idx=>$val)
					$avalues[$idx]=$val;
				AfterAdd($avalues,$keys,$inlineedit);
			}
		}
	}
	else
	{
		$message = $usermessage;
		$status="DECLINED";
		$readavalues=true;
	}
}

$defvalues=array();


//	copy record
if(array_key_exists("copyid1",$_REQUEST) || array_key_exists("editid1",$_REQUEST))
{
	$copykeys=array();
	if(array_key_exists("copyid1",$_REQUEST))
	{
##foreach @TABLE.arrKeyFields as @k##
		$copykeys["##@k s##"]=postvalue("copyid##@index##");
##endfor##
	}
	else
	{
##foreach @TABLE.arrKeyFields as @k##
		$copykeys["##@k s##"]=postvalue("editid##@index##");
##endfor##
	}
	$strWhere=KeyWhere($copykeys);
##if @TABLE.nSecOptions!=ADVSECURITY_ALL && @BUILDER.nLoginMethod==SECURITY_TABLE && @BUILDER.bCreateLoginPage##
	$strWhere=whereAdd($strWhere,SecuritySQL("Search"));
##endif##
	$strSQL = gSQLWhere($strWhere);

	LogInfo($strSQL);
	$rs=db_query($strSQL,$conn);
	$defvalues=db_fetch_array($rs);
##foreach @TABLE.arrKeyFields as @k##	
##if @first##
//	clear key fields
##endif##
	$defvalues["##@k s##"]="";
##endfor##
//call CopyOnLoad event
	if(function_exists("CopyOnLoad"))
		CopyOnLoad($defvalues,$strWhere);
}
else if(!count($defvalues))
{
##foreach Fields as @f filter (@f.bAddPage || @f.bInlineAdd) && @f.strDefaultValue.len order @f.nAddPageOrder##
	$defvalues["##@f.strName s##"]=##@f.strDefaultValue##;
##endfor##
}
if($inlineedit==ADD_ONTHEFLY)
{
##foreach @BUILDER.tables as @t##
##foreach @t.arrFieldObj as @f filter @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.bAllowToAdd && @f.nLookupType==LT_LOOKUPTABLE && @f.pLookupObj.strTable==@TABLE.strDataSourceTable && @f.bUseCategory##
	if(postvalue("table")=="##@t.strShortTableName##" && postvalue("field")=="##@f.strName g##") 
		$defvalues["##@f.strCategoryFilterField##"]=postvalue("category");
##endfor##
##endfor##
}
if($readavalues)
{
##foreach Fields as @f filter  @f.bAddPage && @f.strEditFormat!=EDIT_FORMAT_DATABASE_FILE && @f.strEditFormat!=EDIT_FORMAT_DATABASE_IMAGE && @f.strEditFormat!=EDIT_FORMAT_FILE##
	$defvalues["##@f.strName s##"]=@$avalues["##@f.strName s##"];
##endfor##
}

foreach($defvalues as $key=>$value)
	$smarty->assign("value_".GoodFieldName($key),$value);

$linkdata="";
$includes="";
$arr_includes=array();
	
##if @TABLE.bInlineAdd##
if ( $inlineedit!=ADD_INLINE ) {
##endif##
	//	include files

	//	validation stuff
	$bodyonload="";
	$onsubmit="";
	$needvalidate=false;
##foreach Fields as @f filter @f.bAddPage && NeedValidationOnAdd(@f)##
##if @first##
	if($inlineedit!=ADD_ONTHEFLY)
		$includes.="<script language=\"JavaScript\" src=\"oldinclude/validate.js\"></script>\r\n";
	
	if($inlineedit!=ADD_ONTHEFLY)
	{
		$includes.="<script language=\"JavaScript\">\r\n";
		$includes.="var TEXT_FIELDS_REQUIRED='".addslashes(##message FIELDS_REQUIRED##)."';\r\n";
		$includes.="var TEXT_FIELDS_ZIPCODES='".addslashes(##message FIELDS_ZIPCODES##)."';\r\n";
		$includes.="var TEXT_FIELDS_EMAILS='".addslashes(##message FIELDS_EMAILS##)."';\r\n";
		$includes.="var TEXT_FIELDS_NUMBERS='".addslashes(##message FIELDS_NUMBERS##)."';\r\n";
		$includes.="var TEXT_FIELDS_CURRENCY='".addslashes(##message FIELDS_CURRENCY##)."';\r\n";
		$includes.="var TEXT_FIELDS_PHONE='".addslashes(##message FIELDS_PHONE##)."';\r\n";
		$includes.="var TEXT_FIELDS_PASSWORD1='".addslashes(##message FIELDS_PASSWORD1##)."';\r\n";
		$includes.="var TEXT_FIELDS_PASSWORD2='".addslashes(##message FIELDS_PASSWORD2##)."';\r\n";
		$includes.="var TEXT_FIELDS_PASSWORD3='".addslashes(##message FIELDS_PASSWORD3##)."';\r\n";
		$includes.="var TEXT_FIELDS_STATE='".addslashes(##message FIELDS_STATE##)."';\r\n";
		$includes.="var TEXT_FIELDS_SSN='".addslashes(##message FIELDS_SSN##)."';\r\n";
		$includes.="var TEXT_FIELDS_DATE='".addslashes(##message FIELDS_DATE##)."';\r\n";
		$includes.="var TEXT_FIELDS_TIME='".addslashes(##message FIELDS_TIME##)."';\r\n";
		$includes.="var TEXT_FIELDS_CC='".addslashes(##message FIELDS_CC##)."';\r\n";
		$includes.="var TEXT_FIELDS_SSN='".addslashes(##message FIELDS_SSN##)."';\r\n";
		$includes.="</script>\r\n";
	}
	else
	{
		$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";
	}
##endif##
	##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##
		if($validatetype)
		{
			$needvalidate=true;
			if($inlineedit==ADD_ONTHEFLY)
				$linkdata.="define_fly('value_##@f.strName g##_".postvalue("id")."','".$validatetype."');";
			else
				$bodyonload.="define('value_##@f.strName g##','".$validatetype."','##@f.strLabel js##');";
			
		}
##endfor##

	if($needvalidate)
	{
		if($inlineedit==ADD_ONTHEFLY)
			$onsubmit="return validate_fly(this);";
		else
			$onsubmit="return validate();";
		$bodyonload="onload=\"".$bodyonload."\"";
	}

	if($inlineedit!=ADD_ONTHEFLY)
	{
		$includes.="<script language=\"JavaScript\" src=\"oldinclude/jquery.js\"></script>\r\n";
		$includes.="<script language=\"JavaScript\" src=\"oldinclude/onthefly.js\"></script>\r\n";
		if ($useAJAX) 
			$includes.="<script language=\"JavaScript\" src=\"oldinclude/ajaxsuggest.js\"></script>\r\n";
		$includes.="<script language=\"JavaScript\" src=\"oldinclude/jsfunctions.js\"></script>\r\n";
	}
	if($inlineedit!=ADD_ONTHEFLY)
	{
		$includes.="<script language=\"JavaScript\">\r\n";
	}
	$includes.="var locale_dateformat = ".$locale_info["LOCALE_IDATE"].";\r\n".
	"var locale_datedelimiter = \"".$locale_info["LOCALE_SDATE"]."\";\r\n".
	"var bLoading=false;\r\n".
	"var TEXT_PLEASE_SELECT='".addslashes(##message PLEASE_SELECT##)."';\r\n";
	if ($useAJAX) {
	$includes.="var SUGGEST_TABLE='##@TABLE.strShortTableName##_searchsuggest.php';\r\n";
	}
	if($inlineedit!=ADD_ONTHEFLY)
	{
		$includes.="</script>\r\n";
		if ($useAJAX)
			$includes.="<div id=\"search_suggest\"></div>\r\n";
	}
	##foreach Fields as @f filter @f.bAddPage && UseCalendar(@f)##
	##if @first##
	//	include datepicker files
	if($inlineedit!=ADD_ONTHEFLY)
		$includes.="<script language=\"JavaScript\" src=\"oldinclude/calendar.js\"></script>\r\n";
	else
		$arr_includes[]="oldinclude/calendar.js";
	##endif##
	##endfor##

	##foreach Fields as @f filter @f.bAddPage && UseRTEBASIC(@f)##
	##if @first##
	//	include Rich Text Editor files
	if($inlineedit!=ADD_ONTHEFLY)
		$includes.="<script language=\"JavaScript\" type=\"text/javascript\" src=\"oldinclude/richtext.js\"></script>\r\n";
	else
		$arr_includes[]="oldinclude/richtext.js";
	if($inlineedit!=ADD_ONTHEFLY)
	{
		$includes.="<script language=\"JavaScript\">\r\n";
		$includes.="var TEXT_VIEW_SOURCE='".addslashes(##message VIEW_SOURCE##)."';\r\n";
		$includes.="initRTE('oldinclude/images/', 'oldinclude/', '');\r\n";
		$includes.="</script>\r\n";
		$onsubmit="updateRTEs();".$onsubmit;
	}
	##endif##
	##endfor##

	##foreach Fields as @f filter @f.bAddPage && UseRTEFCK(@f)##
	##if @first##
	include("plugins/fckeditor/fckeditor.php");
	##endif##
	##endfor##

	##foreach Fields as @f filter @f.bAddPage && UseRTEINNOVA(@f)##
	##if @first##
	if($inlineedit!=ADD_ONTHEFLY)
		$includes .= "<script language=\"Javascript\" src=\"plugins/innovaeditor/scripts/innovaeditor.js\"></script>";
	else
		$arr_includes[]="plugins/innovaeditor/scripts/innovaeditor.js";
	##endif##
	##endfor##

	if($inlineedit!=ADD_ONTHEFLY)
		$smarty->assign("includes",$includes);
	$smarty->assign("bodyonload",$bodyonload);
	if(strlen($onsubmit))
		$onsubmit="onSubmit=\"".$onsubmit."\"";
	$smarty->assign("onsubmit",$onsubmit);
##if @TABLE.bInlineAdd##
}
##endif##

$smarty->assign("message",$message);
$smarty->assign("status",$status);

$readonlyfields=array();

//	show readonly fields
##foreach Fields as @f filter (@f.bAddPage || @f.bInlineAdd) && @f.strEditFormat==EDIT_FORMAT_READONLY##
##if @f.strViewFormat==FORMAT_HTML || @f.strViewFormat==FORMAT_FILE_IMAGE || @f.strViewFormat==FORMAT_FILE || @f.strViewFormat==FORMAT_HYPERLINK || @f.strViewFormat==FORMAT_EMAILHYPERLINK || @f.strViewFormat==FORMAT_CHECKBOX##
	$readonlyfields["##@f.strName s##"] = GetData($defvalues,"##@f.strName s##", "##@f.strViewFormat##");
##else##
	$readonlyfields["##@f.strName s##"] = htmlspecialchars(GetData($defvalues,"##@f.strName s##", "##@f.strViewFormat##"));
##endif##
##endfor##


if ($useAJAX) 
{
	$record_id= postvalue("recordID");
	if($inlineedit==ADD_ONTHEFLY)
		$record_id= postvalue("id");
	##foreach @TABLE.arrFieldObj as @f filter (@f.bInlineAdd || @f.bAddPage) && @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.bUseCategory##
##if !@f.bInlineAdd##
	if($inlineedit!=ADD_INLINE)
	{
##elseif !@f.bAddPage##
	if($inlineedit==ADD_INLINE)
	{
##endif##
		$output = loadSelectContent("##@f.strName s##",@$defvalues["##@f.strCategoryControlField s##"],@$defvalues["##@f.strName s##"]);
		$txt = ""; 
		foreach( $output as $value ) 
		{
			$txt .= jsreplace($value)."\\n";
		}
		$linkdata .= "preloadSelectContent('".$txt."', 'value_##@f.strName g##', '".jsreplace(@$defvalues["##@f.strName s##"])."','".$record_id."');\r\n";
##if !@f.bInlineAdd || !@f.bAddPage##
	}
##endif##
	##endfor##

##if @TABLE.bInlineAdd##
	if ( $inlineedit==ADD_INLINE ) 
	{
		if(@$_REQUEST["browser"]=="ie")
			$smarty->assign("browserie",true);
		$smarty->assign("id",$record_id);
		$linkdata=str_replace(array("&","<",">"),array("&amp;","&lt;","&gt;"),$linkdata);
	##foreach Fields as @f filter @f.bInlineAdd && UseRTEFCK(@f)##
	##if @first##
		include("plugins/fckeditor/fckeditor.php");
	##endif##
	##endfor##

	} 
	else 
	{
##endif##
		if($inlineedit!=ADD_ONTHEFLY)
		{
			$linkdata = "<script type=\"text/javascript\">\r\n".
			"$(document).ready(function(){ \r\n".
			$linkdata.
			"});</script>";
		}
		else
		{
			$linkdata=$includes."\r\n".$linkdata;
			$includes="var s;";
			foreach($arr_includes as $file)
			{
				$includes.="s = document.createElement('script');s.src = '".$file."';\r\n".
				"document.getElementsByTagName('HEAD')[0].appendChild(s);\r\n";
			}			
			$linkdata=$includes."\r\n".$linkdata;

			if(!@$_POST["a"]=="added")
			{
				$linkdata = str_replace(array("\\","\r","\n"),array("\\\\","\\r","\\n"),$linkdata);
				echo $linkdata;
				echo "\n";
			}
			else if(@$_POST["a"]=="added" && ($error_happened || $status=="DECLINED"))
			{
				echo "<textarea id=\"data\">decli";
				echo htmlspecialchars($linkdata);
				echo "</textarea>";
			}

		}
##if @TABLE.bInlineAdd##
	}
##endif##
} 
else 
{
	##foreach Fields as @f filter @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.bUseCategory && @f.bAddPage##
	//	##@f.strName## - ##@f.strCategoryControlField##
	$linkdata.="<script language=\"Javascript\">";
	$linkdata.="bLoading = true;";
	$linkdata.="SetSelection('value_##@f.strCategoryControlField g##', 'value_##@f.strName g##', '".jsreplace(@$defvalues["##@f.strCategoryControlField s##"])."', '".jsreplace(@$defvalues["##@f.strName s##"])."', arr_##@f.strName g##);";
	$linkdata.="bLoading = false;";
	$linkdata.="</script>";
	##endfor##
}

if($inlineedit!=ADD_ONTHEFLY)
	$smarty->assign("linkdata",$linkdata);

$formname="name=\"editform\"";
if($inlineedit==ADD_ONTHEFLY)
{
	$formname="name=\"editform".postvalue("id")."\"";
	$smarty->assign("onthefly",true);
	$smarty->assign("flytable",postvalue("table"));
	$smarty->assign("flyfield",postvalue("field"));
	$smarty->assign("flycategory",postvalue("category"));
 	$smarty->assign("cancelonclick","onclick=\"RemoveFlyDiv('".substr(postvalue("id"),3)."');\"");
	$smarty->assign("flyid",postvalue("id"));
}
else
	$smarty->assign("onthefly",false);
$smarty->assign("formname",$formname);


if(@$_POST["a"]=="added" && $inlineedit==ADD_ONTHEFLY && !$error_happened && $status!="DECLINED")
{
	$LookupSQL="";
##foreach @BUILDER.tables as @t##
##foreach @t.arrFieldObj as @f filter @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.bAllowToAdd && @f.nLookupType==LT_LOOKUPTABLE && @f.pLookupObj.strTable==@TABLE.strDataSourceTable##
	if(postvalue("table")=="##@t.strShortTableName##" && postvalue("field")=="##@f.strName g##") 
	{
	$linkfield = "##@f.strLinkField s##";
	$dispfield = "##@f.strDisplayField s##";
	$LookupSQL = "select ";
	$LookupSQL .= "##@f.strLinkField ws##";
	##if @f.bCustomDisplay##
	$LookupSQL .= ",##@f.strDisplayField s##";
	##else##
	$LookupSQL .= ",##@f.strDisplayField ws##";
	##endif##
	}
##endfor##
##endfor##
	if($LookupSQL)
		$LookupSQL.=" from ".AddTableWrappers($strOriginalTableName);

	$data=0;
	if(count($keys) && $LookupSQL)
	{
		$where=KeyWhere($keys);
		$LookupSQL.=" where ".$where;
		$rs=db_query($LookupSQL,$conn);
		$data=db_fetch_numarray($rs);
	}
	if(!$data)
	{
		$data=array(@$avalues[$linkfield],@$avalues[$dispfield]);
	}
	echo "<textarea id=\"data\">";
	echo "added";
	print_inline_array($data);
	echo "</textarea>";
	return;
}

##if @TABLE.bInlineAdd##

if ( @$_POST["a"]=="added" && $inlineedit==ADD_INLINE ) {
	//Preparation   view values

	//	get current values and show edit controls

	$data=0;
	if(count($keys))
	{

		$where=KeyWhere($keys);
	##if @TABLE.nSecOptions!=ADVSECURITY_ALL && @BUILDER.nLoginMethod==SECURITY_TABLE && @BUILDER.bCreateLoginPage##
	//	select only owned records
		$where=whereAdd($where,SecuritySQL("Search"));
	##endif##
		$strSQL = gSQLWhere($where);

		LogInfo($strSQL);

		$rs=db_query($strSQL,$conn);
		$data=db_fetch_array($rs);
	}
	if(!$data)
	{
		$data=$avalues;
		$HaveData=false;
	}

	//check if correct values added

##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##
	$showDetailKeys["##@t.strShortTableName##"]=$masterquery;
##endfor##
	
	
	##foreach @TABLE.arrKeyFields as @k##
	$smarty->assign("key##@index##",htmlspecialchars($keys["##@k s##"]));
	$showKeys[] = htmlspecialchars($keys["##@k s##"]);
	##endfor##

	$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 && !@f.bOriginalView##
			$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 id=\"img_##@f.strName##_".$record_id."\" 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 && !@f.bOriginalView##
			$value.=" width=##@f.ListFormatObj.nImageWidth##";
			##endif##
			##if @f.ListFormatObj.nImageHeight && !@f.bOriginalView##
			$value.=" height=##@f.ListFormatObj.nImageHeight##";
			##endif##
			$value.=" id=\"img_##@f.strName##_".$record_id."\" 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 && !@f.bOriginalView##
				 	// 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.=" id=\"img_##@f.strName##_".$record_id."\" border=0";
			$value.=" src=\"".htmlspecialchars(AddLinkPrefix("##@f.strName s##",$thumbname))."\"></a>";
		##else##
			$value="<img";
			##if @f.ListFormatObj.nImageWidth && !@f.bOriginalView##
			$value.=" width=##@f.ListFormatObj.nImageWidth##";
			##endif##
			##if @f.ListFormatObj.nImageHeight && !@f.bOriginalView##
			$value.=" height=##@f.ListFormatObj.nImageHeight##";
			##endif##
			$value.=" id=\"img_##@f.strName##_".$record_id."\" 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##"),"","",MODE_LIST);
		##else##
		$value = GetData($data,"##@f.strName s##", "##@f.strViewFormat##");
		##endif##
		$showValues[] = $value;
		$showFields[] = "##@f.strName g##";
		##if @f.strtotalsType##
		$showRawValues[] = $data["##@f.strName s##"];
		##else##
		$showRawValues[] = "";
		##endif##
	##endfor##
}

if ( @$_POST["a"]=="added" && $inlineedit==ADD_INLINE ) 
{
	echo "<textarea id=\"data\">";
	if($IsSaved && count($showValues))
	{
		if($HaveData)
			echo "saved";
		else
			echo "savnd";
		print_inline_array($showKeys);
		echo "\n";
		print_inline_array($showValues);
		echo "\n";
		print_inline_array($showFields);
		echo "\n";
		print_inline_array($showRawValues);
		echo "\n";
		print_inline_array($showDetailKeys,true);
		echo "\n";
		print_inline_array($showDetailKeys);
		echo "\n";
		echo str_replace(array("&","<","\\","\r","\n"),array("&amp;","&lt;","\\\\","\\r","\\n"),$usermessage);
	}
	else
	{
		if($status=="DECLINED")
			echo "decli";
		else
			echo "error";
		echo str_replace(array("&","<","\\","\r","\n"),array("&amp;","&lt;","\\\\","\\r","\\n"),$message);
	}
	echo "</textarea>";
} 
else 
{
##endif##
	if(function_exists("BeforeShowAdd"))
		BeforeShowAdd($smarty,$templatefile);

	$smarty->display($templatefile);
##if @TABLE.bInlineAdd##
}
##endif##
function add_error_handler($errno, $errstr, $errfile, $errline)
{
	global $readavalues, $message, $status, $inlineedit, $error_happened;
##if @TABLE.bInlineEdit##
	if ( $inlineedit!=ADD_SIMPLE ) 
		$message="".##message RECORD_NOT_ADDED##.". ".$errstr;
	else  
##endif##
		$message="<div class=message><<< ".##message RECORD_NOT_ADDED##." >>><br><br>".$errstr."</div>";
	$readavalues=true;
	$error_happened=true;
}
?>
