<?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");
header("Pragma: no-cache");
header("Cache-Control: no-cache");

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


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

$pageName = "add.php";
$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($inlineedit==ADD_INLINE)
	$templatefile = "##@TABLE.strShortTableName s##_inline_add.htm";
else
	$templatefile = "##@TABLE.strShortTableName##_add.htm";

$id=postvalue("id");


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


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


// insert new record if we have to

if(@$_POST["a"]=="added")
{
	$afilename_values=array();
	$avalues=array();
	$blobfields=array();
	$files_move=array();
	$files_save=array();
##foreach Fields as @f filter (@f.bAddPage || @f.bInlineAdd)  order @f.nAddPageOrder##
//	processing ##@f.strName## - start
    
	$inlineEditOption = true;
##if !@f.bAddPage##
	$inlineEditOption = $inlineedit==ADD_INLINE;
##elseif !@f.bInlineAdd##
	$inlineEditOption = $inlineedit!=ADD_INLINE;
##endif##
	if($inlineEditOption)
	{
	$value = postvalue("value_##@f.strName g##");
	$type=postvalue("type_##@f.strName g##");
	if (FieldSubmitted("##@f.strName s##"))
	{
##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.bResizeOnUpload || @f.bCreateThumbnail) && @f.strEditFormat==EDIT_FORMAT_FILE##
		if($value)
			$contents = GetUploadedFileContents("file_##@f.strName g##");
##endif##

##if @f.bCreateThumbnail && (@f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE || @f.strEditFormat==EDIT_FORMAT_FILE)##
//	create thumbnail
		if($value)
		{
	##if @f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE##
			$ext = CheckImageExtension(GetUploadedFileName("file_##@f.strName g##"));
			$thumb = CreateThumbnail($value,##@f.nThumbnailSize##,$ext);
			$blobfields[]="##@f.strThumbnail s##";
			$avalues["##@f.strThumbnail s##"]=$thumb;
	##else##
			$ext = CheckImageExtension(GetUploadedFileName("file_##@f.strName g##"));
			$thumb = CreateThumbnail($contents,##@f.nThumbnailSize##,$ext);
			$file = GetUploadFolder("##@f.strName s##")."##@f.strThumbnail s##".$value;
			$files_save[] = array("file"=>$thumb,"filename"=>$file);
	##endif##
		}
##endif##

##if @f.bResizeOnUpload && (@f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE || @f.strEditFormat==EDIT_FORMAT_FILE)##
//	resize
		if($value)
		{
	##if @f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE##
			$ext = CheckImageExtension(GetUploadedFileName("value_##@f.strName g##"));
			$thumb = CreateThumbnail($value,##@f.nNewSize##,$ext);
			$blobfields[]="##@f.strName s##";
	##endif##
		}
##endif##
		$blobfields[]="##@f.strName s##";
		$avalues["##@f.strName s##"]=$value;
	}
##if @f.strEditFormat==EDIT_FORMAT_DATABASE_FILE && @f.ListFormatObj.strFilename##
	if($filename)
		$afilename_values["##@f.ListFormatObj.strFilename s##"]=$filename;
##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##


##foreach @BUILDER.tables as @t##
##foreach @t.arrFieldObj as @f filter @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.nLookupType==LT_LOOKUPTABLE && @f.pLookupObj.strTable==@TABLE.strDataSourceTable && @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##


	$failed_inline_add=false;
//	add filenames to values
	foreach($afilename_values as $akey=>$value)
		$avalues[$akey]=$value;
	
//	before Add event
	$retval = true;
	if(function_exists("BeforeAdd"))
		$retval=BeforeAdd($avalues,$usermessage,$inlineedit);
	if($retval)
	{
		if(DoInsertRecord($strOriginalTableName,$avalues,$blobfields))
		{
			$IsSaved=true;
//	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;
	}
}

// PRG rule, to avoid POSTDATA resend
//if ($inlineedit==ADD_SIMPLE && @$_POST["a"]=="added"){
if (no_output_done() && $inlineedit==ADD_SIMPLE && $IsSaved){
 
	// saving message
	$_SESSION["message"] = ($message ? $message : "");
	// redirect
	header("Location: ##@TABLE.strShortTableName##_".$pageName);
	// turned on output buffering, so we need to stop script
	exit();
}
// for PRG rule, to avoid POSTDATA resend. Saving mess in session
if ($inlineedit==ADD_SIMPLE  && isset($_SESSION["message"])){
	$message = $_SESSION["message"];
	unset($_SESSION["message"]);
}


$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);
	if(!$defvalues)
		$defvalues=array();
##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
{
##foreach Fields as @f filter (@f.bAddPage || @f.bInlineAdd) && @f.strDefaultValue.len order @f.nAddPageOrder##
	$defvalues["##@f.strName s##"]=##@f.strDefaultValue##;
##endfor##
}

##foreach @TABLE.arrMasterTables as @m##
##if @first##
//	set default values for the foreign keys
##endif##
if(@$_SESSION[$strTableName."_mastertable"]=="##@m.strMasterTable s##")
{
	##foreach @m.arrDetailKeys as @d##
	$defvalues["##@d s##"]=@$_SESSION[$strTableName."_masterkey##@index##"];
	##endfor##
}
##endfor##


##foreach @BUILDER.tables as @t##
##foreach @t.arrFieldObj as @f filter @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.nLookupType==LT_LOOKUPTABLE && @f.pLookupObj.strTable==@TABLE.strDataSourceTable && @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##
}
//for basic files
$includes="";
//for javascript code
$jscode="";
$bodyonload="";
$onsubmit="";
//////////////////////////////////////////////////////////////////	
//	Begin Add validation params for InlineAdd or Add or AddOnTheFly	
//	validation stuff
	$onsubmit="$('#message_block').html('');";
	$regex='';
	$regexmessage='';
	$regextype = '';
	$RTEfunc="";
	$needvalidate=false;
	$arrValidate = array();
//	for inlineAdd
	$addValidateTypes = array();
	$addValidateFields = array();
	$addValidateUseRTE = array();
	$addValidateCBList = array();	
	$addValidateRegex = array();
	$addValidateRegexmes = array();
	$addValidateRegexmestype = array();
##foreach Fields as @f filter @f.bAddPage && (UseRTEINNOVA(@f) || UseRTEBASIC(@f))##
##if @first##
if($inlineedit!=ADD_INLINE)
{
##endif##
//	notvalidate field like INNOVA or RTEBASIC - ##@f.strName g##
	##if UseRTEINNOVA(@f)##
	$strRTE="INNOVA_FLY";
	##else##
	$strRTE="RTE_FLY";
	##endif##
	if($inlineedit==ADD_ONTHEFLY)
		$RTEfunc.='setDataFromRTEInnova($(\'#value_##@f.strName g##_'.$id.'\'),\''.$strRTE.'\',$(\'#editform'.$id.'\'),\'value_##@f.strName g##\');'; 
	else			
		$RTEfunc.='setDataFromRTEInnova($(\'#value_##@f.strName g##\'),\''.$strRTE.'\',$(\'#editform\'),\'value_##@f.strName g##\');'; 
##if @last##
}
##endif##
##endfor##	
//	Begin Add validation	
//if use InnovaEditor or RTE on pages add or addonthefly when useRTE will be with  -  "_FLY"
//if use InnovaEditor or RTE on page InineAdd when useRTE will be with out  -  "_FLY"		
##foreach Fields as @f filter @f.bAddPage || (@f.bInlineAdd && @f.bListPage) ##
##if @first##
if($inlineedit!=ADD_INLINE) 
{
	if($inlineedit!=ADD_ONTHEFLY)
	{
		AddJSFile("validate");
		if(@$_REQUEST["language"])
			$language = $_REQUEST["language"];
		// may be elseif ?
		if(@$_SESSION["language"])
			$language = $_SESSION["language"];
		else
			$language = 'English';
		
		$jscode.="window.current_language='".jsreplace($language)."';\r\n";
		
		$jscode.="addValid = new validation();\r\n";	
	}
	else	
		$jscode.="window.addFlyValid".$id." = new validation();\r\n";
				
	$jscode.="window.TEXT_INLINE_FIELD_REQUIRED='".jsreplace(##message INLINE_FIELD_REQUIRED##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_ZIPCODE='".jsreplace(##message INLINE_FIELD_ZIPCODE##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_EMAIL='".jsreplace(##message INLINE_FIELD_EMAIL##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_NUMBER='".jsreplace(##message INLINE_FIELD_NUMBER##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_CURRENCY='".jsreplace(##message INLINE_FIELD_CURRENCY##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_PHONE='".jsreplace(##message INLINE_FIELD_PHONE##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_PASSWORD1='".jsreplace(##message INLINE_FIELD_PASSWORD1##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_PASSWORD2='".jsreplace(##message INLINE_FIELD_PASSWORD2##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_STATE='".jsreplace(##message INLINE_FIELD_STATE##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_SSN='".jsreplace(##message INLINE_FIELD_SSN##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_DATE='".jsreplace(##message INLINE_FIELD_DATE##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_TIME='".jsreplace(##message INLINE_FIELD_TIME##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_CC='".jsreplace(##message INLINE_FIELD_CC##)."';\r\n";
	$jscode.="window.TEXT_INLINE_FIELD_SSN='".jsreplace(##message INLINE_FIELD_SSN##)."';\r\n";
}
##endif##
##if NeedValidationOnAdd(@f)##
//	validate field - ##@f.strName g##
##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";
##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_REGEXP##
	$validatetype="Regular expression";
	$regex = "##@f.strRegex##";
	$regexmessage = "##@f.strRegexMessage.text s##";
	$regextype = "##@f.strRegexMessage.nameType s##";
##else##
	$validatetype="##@f.EditFormatObj.strValidateAs##";
	##if @f.EditFormatObj.strValidateAs##
	AddJSFile("validate/".$validatetype,"validate");
	##endif##
##endif##
##endif##
##if @f.EditFormatObj.bRequired && @f.strEditFormat!=EDIT_FORMAT_CHECKBOX && @f.strEditFormat!=EDIT_FORMAT_READONLY##
	$second_validatetype="IsRequired";
##else##
	$second_validatetype="";
##endif##
##if UseRTEFCK(@f)##
	$strRTE='FCK';
##elseif UseRTEINNOVA(@f)##
	$strRTE='INNOVA'.($inlineedit!=ADD_INLINE ? '_FLY' : '');
##elseif  UseRTEBASIC(@f)##
	$strRTE='RTE'.($inlineedit!=ADD_INLINE ? '_FLY' : '');
##else##		
	$strRTE='';
##endif##
##if @f.nControlType==LCT_CBLIST##
	$lookup='CBList';
##elseif @f.nControlType==LCT_LIST || @f.nControlType==LCT_AJAX##
	$lookup='disp';
##elseif @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.nLookupType!=LT_LOOKUPTABLE && @f.nSelectSize>1##	
	$lookup='list';
##else##
	$lookup='';	
##endif##
	$arrValidate[] = array(0 => "##@f.strName g##", 1 => $validatetype, 2 => $second_validatetype, 3 => $strRTE,
						   4 => $lookup, 5 => $regex, 6 => $regexmessage, 7 => $regextype);
##endif##	
##endfor##
for($i=0;$i<count($arrValidate);$i++)
{
	if($arrValidate[$i][1])
	{
		if($inlineedit!=ADD_INLINE)
		{
			$needvalidate=true;
			if($inlineedit==ADD_ONTHEFLY)
			{
				if ($arrValidate[$i][1]=="Regular expression")
					$jscode.="addFlyValid".$id.".addRegex($('#value_".$arrValidate[$i][0]."_".$id."'),'".$arrValidate[$i][1]."','".
						jsreplace($arrValidate[$i][5])."','".jsreplace($arrValidate[$i][6])."','".jsreplace($arrValidate[$i][7])."');\r\n";
				else		
					$jscode.="addFlyValid".$id.".add($('#value_".$arrValidate[$i][0]."_".$id."'),'".$arrValidate[$i][1]."','".$arrValidate[$i][3]."','".$arrValidate[$i][4]."');\r\n";	
			}
			else
			{
				if ($arrValidate[$i][1]=="Regular expression")
					$bodyonload.="addValid.addRegex(document.editform['value_".$arrValidate[$i][0]."'],'".$arrValidate[$i][1]."','".
						jsreplace($arrValidate[$i][5])."','".jsreplace($arrValidate[$i][6])."','".jsreplace($arrValidate[$i][7])."');\r\n";
				else		
					$bodyonload.="addValid.add(document.editform['value_".$arrValidate[$i][0]."'],'".$arrValidate[$i][1]."','".$arrValidate[$i][3]."','".$arrValidate[$i][4]."');\r\n";
			}
		}
		else{
				//	Add Inline validation params
				$addValidateTypes[] = $arrValidate[$i][1];
				$addValidateFields[] = $arrValidate[$i][0];
				$addValidateUseRTE[] = $arrValidate[$i][3];
				$addValidateCBList[] = $arrValidate[$i][4];
				$addValidateRegex[] = jsreplace($arrValidate[$i][5]);
				$addValidateRegexmes[] = jsreplace($arrValidate[$i][6]);
				$addValidateRegexmestype[] = jsreplace($arrValidate[$i][7]);
			}	
	}
	if($arrValidate[$i][2])
	{	
		if($inlineedit!=ADD_INLINE)
		{
			$needvalidate=true;
			if($inlineedit==ADD_ONTHEFLY)
			{	
				if($arrValidate[$i][3]=='INNOVA_FLY' || $arrValidate[$i][3]=='RTE_FLY')
				{
					$jscode.='$("td[@class^=\'editshade_lb\']").each(function(i){';
					$jscode.='if($("iframe[@name=\'value_'.$arrValidate[$i][0].'_'.$id.'\']",this).length)';
					$jscode.='addFlyValid'.$id.'.add($("iframe[@name=\'value_'.$arrValidate[$i][0].'_'.$id.'\']",this),"'.$arrValidate[$i][2].'","'.$arrValidate[$i][3].'","'.$arrValidate[$i][4].'");});';
				//	$func.='getDataFromRTEInnova($(\'#value_'.$arrValidate[$i][0].'_'.$id.'\'),\''.$arrValidate[$i][3].'\',$(\'#editform'.$id.'\'),\'value_'.$arrValidate[$i][0].'\');'; 
				}
				else
					$jscode.="addFlyValid".$id.".add($('".($arrValidate[$i][4]=='CBList' ? "input[@name=\"value_".$arrValidate[$i][0]."[]\"]" : "#value_".$arrValidate[$i][0]."_".$id)."'),'".$arrValidate[$i][2]."','".$arrValidate[$i][3]."','".$arrValidate[$i][4]."');\r\n";
			}
			elseif($arrValidate[$i][3]=='INNOVA_FLY' || $arrValidate[$i][3]=='RTE_FLY')
			{
				$bodyonload.='$("td[@class^=\'editshade_lb\']").each(function(i){';
				$bodyonload.='if($("iframe[@name=\'value_'.$arrValidate[$i][0].'\']",this).length)';
				$bodyonload.='addValid.add($("iframe[@name=\'value_'.$arrValidate[$i][0].'\']",this),"'.$arrValidate[$i][2].'","'.$arrValidate[$i][3].'","'.$arrValidate[$i][4].'");});';
				//$func.='getDataFromRTEInnova($(\'#value_'.$arrValidate[$i][0].'\'),\''.$arrValidate[$i][3].'\',$(\'#editform\'),\'value_'.$arrValidate[$i][0].'\');'; 
			}
			else
				$bodyonload.="addValid.add(document.editform['".($arrValidate[$i][4]=='disp' ? "display_" : "")."value_".$arrValidate[$i][0].($arrValidate[$i][4]=='CBList' || $arrValidate[$i][4]=='list' ? "[]" : "")."'],'".$arrValidate[$i][2]."','".$arrValidate[$i][3]."','".$arrValidate[$i][4]."');\r\n";
		}
		else{
				//	Add Inline validation params
				$addValidateTypes[] = $arrValidate[$i][2];
				$addValidateFields[] = $arrValidate[$i][0];
				$addValidateUseRTE[] = $arrValidate[$i][3];
				$addValidateCBList[] = $arrValidate[$i][4];
				$addValidateRegex[] = jsreplace($arrValidate[$i][5]);
				$addValidateRegexmes[] = jsreplace($arrValidate[$i][6]);
				$addValidateRegexmestype[] = jsreplace($arrValidate[$i][7]);
			}	
	}
}	
//	End Add validation params for InlineAdd or Add or AddOnTheFly
//////////////////////////////////////////////////////////////

##foreach Fields as @f filter (@f.bAddPage || @f.bInlineAdd) && @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && (@f.nControlType==LCT_LIST || @f.bAllowToAdd)##
##if @first##
AddJSFile("ui");
AddJSFile("ui.core","ui");
AddJSFile('ui.resizable','ui.core');
AddJSFile("onthefly");
##endif##
##endfor##

////////////////////// time picker
##foreach Fields as @f filter (@f.bAddPage || @f.bInlineAdd) && @f.useTimePicker##
##if @first##
AddJSFile("ui");
AddJSFile("jquery.utils","ui");
AddJSFile("ui.dropslide","jquery.utils");
AddJSFile("ui.timepickr","ui.dropslide");
AddCSSFile("ui.dropslide");
##endif##
##endfor##
//////////////////////
$body=array();


AddJSFile('customlabels');

$jscode.="window.locale_dateformat = ".$locale_info["LOCALE_IDATE"].";\r\n".
	"window.locale_datedelimiter = \"".$locale_info["LOCALE_SDATE"]."\";\r\n".
	"window.bLoading=false;\r\n".
	"window.TEXT_PLEASE_SELECT='".jsreplace(##message PLEASE_SELECT##)."';\r\n";

##foreach Fields as @f filter @f.bAddPage && UseCalendar(@f)##
##if @first##
//	include datepicker files
	
	$jscode.="window.TEXT_MONTH_JAN='".jsreplace(##message MONTH_JAN##)."';\r\n";
	$jscode.="window.TEXT_MONTH_FEB='".jsreplace(##message MONTH_FEB##)."';\r\n";
	$jscode.="window.TEXT_MONTH_MAR='".jsreplace(##message MONTH_MAR##)."';\r\n";
	$jscode.="window.TEXT_MONTH_APR='".jsreplace(##message MONTH_APR##)."';\r\n";
	$jscode.="window.TEXT_MONTH_MAY='".jsreplace(##message MONTH_MAY##)."';\r\n";
	$jscode.="window.TEXT_MONTH_JUN='".jsreplace(##message MONTH_JUN##)."';\r\n";
	$jscode.="window.TEXT_MONTH_JUL='".jsreplace(##message MONTH_JUL##)."';\r\n";
	$jscode.="window.TEXT_MONTH_AUG='".jsreplace(##message MONTH_AUG##)."';\r\n";
	$jscode.="window.TEXT_MONTH_SEP='".jsreplace(##message MONTH_SEP##)."';\r\n";
	$jscode.="window.TEXT_MONTH_OCT='".jsreplace(##message MONTH_OCT##)."';\r\n";
	$jscode.="window.TEXT_MONTH_NOV='".jsreplace(##message MONTH_NOV##)."';\r\n";
	$jscode.="window.TEXT_MONTH_DEC='".jsreplace(##message MONTH_DEC##)."';\r\n";
	
	$jscode.="window.TEXT_DAY_SU='".jsreplace(##message DAY_SU##)."';\r\n";
	$jscode.="window.TEXT_DAY_MO='".jsreplace(##message DAY_MO##)."';\r\n";
	$jscode.="window.TEXT_DAY_TU='".jsreplace(##message DAY_TU##)."';\r\n";
	$jscode.="window.TEXT_DAY_WE='".jsreplace(##message DAY_WE##)."';\r\n";
	$jscode.="window.TEXT_DAY_TH='".jsreplace(##message DAY_TH##)."';\r\n";
	$jscode.="window.TEXT_DAY_FR='".jsreplace(##message DAY_FR##)."';\r\n";
	$jscode.="window.TEXT_DAY_SA='".jsreplace(##message DAY_SA##)."';\r\n";
	
	$jscode.="window.TEXT_TODAY='".jsreplace(##message TODAY##)."';\r\n";	
		
	AddJSFile("calendar");
##endif##
##endfor##






if($inlineedit!=ADD_INLINE)
{
	if($needvalidate)
	{
		if($RTEfunc)
		{
			if($inlineedit==ADD_ONTHEFLY)
				$onsubmit="if(addFlyValid".$id.".validate()){".$RTEfunc."return true;}else return false;";
			else
				$onsubmit="if(addValid.validate()){".$RTEfunc."return true;}else return false;";	
		}
		else{	
				if($inlineedit==ADD_ONTHEFLY)
					$onsubmit="return addFlyValid".$id.".validate();";
				else
					$onsubmit.="return addValid.validate();";
			}
	}
	elseif($RTEfunc)
		$onsubmit=$RTEfunc."return true;";

	if($inlineedit!=ADD_ONTHEFLY)
	{
		$includes.="<script language=\"JavaScript\" src=\"include/jquery.js\"></script>\r\n";
		AddJSFile("ajaxsuggest");		
		$includes.="<script language=\"JavaScript\" src=\"include/jsfunctions.js\"></script>\r\n";
	}
	
	$jscode.="SUGGEST_TABLE='##@TABLE.strShortTableName##_searchsuggest.php';\r\n";
	if($inlineedit!=ADD_ONTHEFLY)
		$includes.="<div id=\"search_suggest\"></div>\r\n";
	

	##foreach Fields as @f filter @f.bAddPage##
	$xt->assign("##@f.strName g##_fieldblock",true);
	##endfor##
	
	$formname="editform";
	if($onsubmit)
		$onsubmit="onsubmit=\"".$onsubmit."\"";
	if($inlineedit!=ADD_ONTHEFLY)
	{
		$body["begin"]=$includes.
		"<form name=\"editform\" id=\"editform\" encType=\"multipart/form-data\" method=\"post\" action=\"##@TABLE.strShortTableName##_add.##@ext##\" ".$onsubmit.">".
		"<input type=hidden name=\"a\" value=\"added\">";
		$xt->assign("backbutton_attrs","onclick=\"window.location.href='##@TABLE.strShortTableName##_list.##@ext##?a=return'\"");
		$xt->assign("back_button",true);
	}
	else
	{
		$formname="editform".$id;
		$body["begin"]="<form name=\"editform".$id."\" id=\"editform".$id."\" encType=\"multipart/form-data\" method=\"post\" action=\"##@TABLE.strShortTableName##_add.##@ext##\" ".$onsubmit." target=\"flyframe".$id."\">".
		"<input type=hidden name=\"a\" value=\"added\">".
		"<input type=hidden name=\"editType\" value=\"onthefly\">".
		"<input type=hidden name=\"table\" value=\"".postvalue("table")."\">".
		"<input type=hidden name=\"field\" value=\"".postvalue("field")."\">".
		"<input type=hidden name=\"category\" value=\"".postvalue("category")."\">".
		"<input type=hidden name=\"id\" value=\"".$id."\">";
		$xt->assign("cancelbutton_attrs","onclick=\"RemoveFlyDiv('".$id."');\"");
		$xt->assign("cancel_button",true);
		$xt->assign("header","");
	}
	$xt->assign("save_button",true);
	$xt->assign("reset_button",true);
	$xt->assign("resetbutton_attrs",'onclick="resetEditors();"');
}

if($message)
{
	$xt->assign("message_block",true);
	$xt->assign("message",$message);
}
//$xt->assign("status",$status);

$readonlyfields=array();

//	show readonly fields
##foreach Fields as @f filter (@f.bAddPage || @f.bInlineAdd) && @f.strEditFormat==EDIT_FORMAT_READONLY##
##if !NeedEncode(@f)##
	$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##

$linkdata="";
$record_id= postvalue("recordID");

if($inlineedit==ADD_ONTHEFLY)
	$record_id=$id;
##foreach @TABLE.arrFieldObj as @f filter (@f.bInlineAdd || @f.bAddPage) && @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.bUseCategory##

##if !@f.bInlineAdd##
$fieldAppear = ($inlineedit!=ADD_INLINE);
##elseif !@f.bAddPage##
$fieldAppear = ($inlineedit==ADD_INLINE);
##else##
$fieldAppear=true;
##endif##
if($fieldAppear)
{
	$output = loadSelectContent("##@f.strName s##",@$defvalues["##@f.strCategoryControlField s##"],@$defvalues["##@f.strName s##"]);
	$txt = ""; 
	foreach( $output as $value ) 
	{
		$txt .= jsreplace($value)."\\n";
	}
	$jscode .= "preloadSelectContent('".$txt."', 'value_##@f.strName g##', '".jsreplace(@$defvalues["##@f.strName s##"])."','".$record_id."');\r\n";
}
##endfor##

	if($inlineedit==ADD_INLINE) 
	{
		$jscode.= "inlineAddValid".$record_id." = new validation();\r\n";
		##foreach Fields as @f filter @f.bInlineAdd && @f.bListPage##
		##if @first##
		$types_separated = implode(",", $addValidateTypes);
		$fields_separated = implode(",", $addValidateFields);
		$useRTE_separated = implode(",", $addValidateUseRTE);
		$CBList_separated = implode(",", $addValidateCBList);
		$regex_separated = implode(",", $addValidateRegex);
		$regexmes_separated = implode(",", $addValidateRegexmes);
		$regexmestype_separated = implode(",", $addValidateRegexmestype);
		$jscode.= "var addValidateTypes = String('".$types_separated."').split(',');\r\n";
		$jscode.= "var addValidateFields = String('".$fields_separated."').split(',');\r\n";
		$jscode.= "var addValidateUseRTE = String('".$useRTE_separated."').split(',');\r\n";
		$jscode.= "var addValidateCBList = String('".$CBList_separated."').split(',');\r\n";
		$jscode.= "var addValidateRegex = String('".$regex_separated."').split(',');\r\n";
		$jscode.= "var addValidateRegexmes = String('".$regexmes_separated."').split(',');\r\n";
		$jscode.= "var addValidateRegexmestype = String('".$regexmestype_separated."').split(',');\r\n";
		$jscode.='$("span[@id^=edit'.$record_id.'_]").each(function(i){
						var j;
						for(j=0;j<addValidateFields.length;j++)
						{
							if(addValidateFields[j]==this.id.substr(this.id.indexOf("_")+1))
							{
								if($(this).attr("type")=="Innova" || $(this).attr("type")=="RTE")
									inlineAddValid'.$record_id.'.add(this, addValidateTypes[j],addValidateUseRTE[j],addValidateCBList[j]);
								else{
										if($("input[@type=text],input[@type=hidden],input[@type=password],input[@type=file],select",this).length)
										{
											if(addValidateCBList[j]=="list")
												elem = $("select",this);
											else
												elem = $("input[@type=text],input[@type=hidden],input[@type=password],input[@type=file],select",this);
											if(addValidateTypes[j]=="Regular expression")
												inlineAddValid'.$record_id.'.addRegex(elem, addValidateTypes[j],addValidateRegex[j],addValidateRegexmes[j],addValidateRegexmestype[j]);	
											else	
												inlineAddValid'.$record_id.'.add(elem, addValidateTypes[j],addValidateUseRTE[j],addValidateCBList[j]);	
										}
									}
							}
						}
					});';	
		##endif##
		##endfor##	
	} 
	else 
	{
		$jscode.="SetToFirstControl('".$formname."');";
		if($inlineedit==ADD_SIMPLE)
			$jscode.= $bodyonload;
	}
		

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>";
	exit();
}

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

	##foreach Fields as @f 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://" && !myfile_exists(GetUploadFolder("##@f.strName s##").$thumbname))
				$thumbname=$data["##@f.strName s##"];
			$value="<a";
			##if @f.bUseiBox##
				$value .= " rel='ibox'";
			##else##
				$value .= " target=_blank";
			##endif##				
			$value.=" href=\"".htmlspecialchars(AddLinkPrefix("##@f.strName s##",$data["##@f.strName s##"]))."\">";
			$value.="<img";
			if($thumbname==$data["##@f.strName s##"])
			{
				##if @f.ListFormatObj.nImageWidth##
				$value.=" width=##@f.ListFormatObj.nImageWidth##";
				##endif##
				##if @f.ListFormatObj.nImageHeight##
				$value.=" height=##@f.ListFormatObj.nImageHeight##";
				##endif##
			}
			$value.=" 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##
		$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 IsBinaryField(@f)##
		$showRawValues[] = "";
		##else##
		$showRawValues[] = substr($data["##@f.strName s##"],0,100);
		##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>";
	exit();
} 
##endif##

/////////////////////////////////////////////////////////////
//	prepare Edit Controls
/////////////////////////////////////////////////////////////
$jscode.="\r\n window.rteIdArr=".jsreplace("new Object").";\r\n";

##foreach Fields as @f filter @f.bInlineAdd || @f.bAddPage##

##if UseRTEFCK(@f) || UseRTEINNOVA(@f)##
$jscode.="window.rteIdArr['##@f.strName s##']=new Array();\r\n";
$jscode.="window.rteIdArr['##@f.strName s##'][0]='##@BUILDER.strRTEType##';\r\n";
$jscode.="window.rteIdArr['##@f.strName s##'][1]='##@f.strName s##';\r\n";
##endif##

$control_##@f.strName g##=array();
$control_##@f.strName g##["func"]="xt_buildeditcontrol";
$control_##@f.strName g##["params"] = array();
$control_##@f.strName g##["params"]["field"]="##@f.strName s##";
$control_##@f.strName g##["params"]["value"]=@$defvalues["##@f.strName s##"];
$control_##@f.strName g##["params"]["id"]=$record_id;
##if UseRTEFCK(@f) || UseRTEINNOVA(@f) || UseRTEBASIC(@f)##
if($inlineedit==ADD_INLINE)
	$control_##@f.strName g##["params"]["mode"]="inline_add";
else
	$control_##@f.strName g##["params"]["mode"]="add";
##else##
if($inlineedit==ADD_INLINE || $inlineedit==ADD_ONTHEFLY)
	$control_##@f.strName g##["params"]["mode"]="inline_add";
else
	$control_##@f.strName g##["params"]["mode"]="add";
##endif##
	
$xt->assignbyref("##@f.strName g##_editcontrol",$control_##@f.strName g##);
##endfor##

PrepareJSCode($jscode,$record_id);

	if($inlineedit!=ADD_ONTHEFLY)
	{
		if($inlineedit==ADD_INLINE)
		{
			$jscode=str_replace(array("&","<",">"),array("&amp;","&lt;","&gt;"),$jscode);
			$xt->assignbyref("linkdata",$jscode);
		}
		$body["end"]="</form><script>".$jscode."</script>";
		$xt->assign("body",$body);
		$xt->assign("flybody",true);
	}
	else
	{
		if(!@$_POST["a"]=="added")
		{
			$jscode = str_replace(array("\\","\r","\n"),array("\\\\","\\r","\\n"),$jscode);
			echo $jscode;
			echo "\n";
		}
		else if(@$_POST["a"]=="added" && ($error_happened || $status=="DECLINED"))
		{
			echo "<textarea id=\"data\">decli";
			echo htmlspecialchars($jscode);
			echo "</textarea>";
		}
		$body["end"]="</form>";
		$xt->assign("footer","");
		$xt->assign("flybody",$body);
		$xt->assign("body",true);
	}	

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

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

if(function_exists("BeforeShowAdd"))
	BeforeShowAdd($xt,$templatefile);

if($inlineedit==ADD_ONTHEFLY)
{
	$xt->load_template($templatefile);
	$xt->display_loaded("style_block");
	$xt->display_loaded("flybody");
}
else
	$xt->display($templatefile);


?>