<?php 
include("include/dbcommon.php");

@ini_set("display_errors","1");
@ini_set("display_startup_errors","1");

add_nocache_headers();
include("include/List_Management_variables.php");
include('include/xtempl.php');
include('classes/runnerpage.php');

//	check if logged in
if(!@$_SESSION["UserID"] || !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Add"))
{ 
	$_SESSION["MyURL"]=$_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
	
	header("Location: login.php?message=expired"); 
	return;
}

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

$keys = array();
$showValues = array();
$showRawValues = array();
$showFields = array();
$showDetailKeys = array();
$IsSaved = false;
$HaveData = true;
$popUpSave = false;

$sessionPrefix = $strTableName;

$onFly = false;
if(postvalue("onFly"))
	$onFly = true;

if(@$_REQUEST["editType"]=="inline")
	$inlineadd = ADD_INLINE;
elseif(@$_REQUEST["editType"]==ADD_POPUP)
{
	$inlineadd = ADD_POPUP;
	if(@$_POST["a"]=="added" && postvalue("field")=="" && postvalue("category")=="")
		$popUpSave = true;	
}
elseif(@$_REQUEST["editType"]=="addmaster")
	$inlineadd = ADD_MASTER;
elseif($onFly)
{
	$inlineadd = ADD_ONTHEFLY;
	$sessionPrefix = $strTableName."_add";
}
else
	$inlineadd = ADD_SIMPLE;

if($inlineadd == ADD_INLINE)
	$templatefile = "List_Management_inline_add.htm";
else
	$templatefile = "List_Management_add.htm";

$id = postvalue("id");	
if(intval($id)==0)
	$id = 1;

//If undefined session value for mastet table, but exist post value master table, than take second
//It may be happen only when use dpInline mode on page add
if(!@$_SESSION[$sessionPrefix."_mastertable"] && postvalue("mastertable"))
	$_SESSION[$sessionPrefix."_mastertable"] = postvalue("mastertable");

$xt = new Xtempl();
	
// assign an id		
$xt->assign("id",$id);
	
$auditObj = GetAuditObject($strTableName);

//array of params for classes
$params = array("pageType" => PAGE_ADD,"id" => $id,"mode" => $inlineadd);

////////////////////// data picker
$params["calendar"] = true;

////////////////////// time picker

$params['tName'] = $strTableName;
$params['strOriginalTableName'] = $strOriginalTableName;
$params['menuTablesArr'] = $menuTablesArr;
$params['xt'] = &$xt;
$params['needSearchClauseObj'] = false;
$params['includes_js']=$includes_js;
$params['includes_jsreq']=$includes_jsreq;
$params['includes_css']=$includes_css;
$params['locale_info']=$locale_info;
$params['pageAddLikeInline'] = ($inlineadd==ADD_INLINE);
$params['useTabsOnAdd'] = useTabsOnAdd($strTableName);
if($params['useTabsOnAdd'])
	$params['arrAddTabs'] = GetAddTabs($strTableName);
$pageObject = new RunnerPage($params);

//Get detail table keys	
$detailKeys = $pageObject->detailKeysByM;

//Array of fields, which appear on add page
$addFields = $pageObject->getFieldsByPageType();

// add onload event
//$onLoadJsCode = GetTableData($pageObject->tName, ".jsOnloadAdd", '');
//$pageObject->addOnLoadJsEvent($onLoadJsCode);

if ($inlineadd==ADD_SIMPLE)
{
	// add button events if exist
	$pageObject->addButtonHandlers();
}

$url_page=substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1,12);

//For show detail tables on master page add
if($inlineadd==ADD_SIMPLE || $inlineadd==ADD_MASTER || $inlineadd==ADD_POPUP)
{
	$dpParams = array();
	if($pageObject->isShowDetailTables)
	{
		$ids = $id;
			$pageObject->jsSettings['tableSettings'][$strTableName]['dpParams'] = array('tableNames'=>$dpParams['strTableNames'], 'ids'=>$dpParams['ids']);
		if($inlineadd==ADD_SIMPLE)
			$pageObject->AddJSFile("include/detailspreview");	
	}
}

//	Before Process event
if($eventObj->exists("BeforeProcessAdd"))
	$eventObj->BeforeProcessAdd($conn);

// proccess captcha
if ($inlineadd==ADD_SIMPLE || $inlineadd==ADD_MASTER || $inlineadd==ADD_POPUP)
	if($pageObject->captchaExists())
		$pageObject->doCaptchaCode();	
	
// insert new record if we have to
if(@$_POST["a"]=="added")
{
	$afilename_values=array();
	$avalues=array();
	$blobfields=array();
//	processing Region - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Region_".$id);
		$type=postvalue("type_Region_".$id);
		if (FieldSubmitted("Region_".$id))
		{
				$value=prepare_for_db("Region",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Region"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Region"]=$value;
		}
		}
//	processibng Region - end
//	processing Customer Name - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Customer_Name_".$id);
		$type=postvalue("type_Customer_Name_".$id);
		if (FieldSubmitted("Customer Name_".$id))
		{
				$value=prepare_for_db("Customer Name",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Customer Name"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Customer Name"]=$value;
		}
		}
//	processibng Customer Name - end
//	processing Address - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Address_".$id);
		$type=postvalue("type_Address_".$id);
		if (FieldSubmitted("Address_".$id))
		{
				$value=prepare_for_db("Address",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Address"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Address"]=$value;
		}
		}
//	processibng Address - end
//	processing City - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_City_".$id);
		$type=postvalue("type_City_".$id);
		if (FieldSubmitted("City_".$id))
		{
				$value=prepare_for_db("City",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "City"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["City"]=$value;
		}
		}
//	processibng City - end
//	processing State - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_State_".$id);
		$type=postvalue("type_State_".$id);
		if (FieldSubmitted("State_".$id))
		{
				$value=prepare_for_db("State",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "State"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["State"]=$value;
		}
		}
//	processibng State - end
//	processing Country - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Country_".$id);
		$type=postvalue("type_Country_".$id);
		if (FieldSubmitted("Country_".$id))
		{
				$value=prepare_for_db("Country",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Country"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Country"]=$value;
		}
		}
//	processibng Country - end
//	processing Postal Code - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Postal_Code_".$id);
		$type=postvalue("type_Postal_Code_".$id);
		if (FieldSubmitted("Postal Code_".$id))
		{
				$value=prepare_for_db("Postal Code",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Postal Code"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Postal Code"]=$value;
		}
		}
//	processibng Postal Code - end
//	processing Web address - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Web_address_".$id);
		$type=postvalue("type_Web_address_".$id);
		if (FieldSubmitted("Web address_".$id))
		{
				$value=prepare_for_db("Web address",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Web address"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Web address"]=$value;
		}
		}
//	processibng Web address - end
//	processing Area - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Area_".$id);
		$type=postvalue("type_Area_".$id);
		if (FieldSubmitted("Area_".$id))
		{
				$value=prepare_for_db("Area",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Area"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Area"]=$value;
		}
		}
//	processibng Area - end
//	processing Customer_Category - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Customer_Category_".$id);
		$type=postvalue("type_Customer_Category_".$id);
		if (FieldSubmitted("Customer_Category_".$id))
		{
				$value=prepare_for_db("Customer_Category",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Customer_Category"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Customer_Category"]=$value;
		}
		}
//	processibng Customer_Category - end
//	processing Breif About the Company - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Breif_About_the_Company_".$id);
		$type=postvalue("type_Breif_About_the_Company_".$id);
		if (FieldSubmitted("Breif About the Company_".$id))
		{
				$value=prepare_for_db("Breif About the Company",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Breif About the Company"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Breif About the Company"]=$value;
		}
		}
//	processibng Breif About the Company - end
//	processing Existing Setup - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Existing_Setup_".$id);
		$type=postvalue("type_Existing_Setup_".$id);
		if (FieldSubmitted("Existing Setup_".$id))
		{
				$value=prepare_for_db("Existing Setup",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Existing Setup"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Existing Setup"]=$value;
		}
		}
//	processibng Existing Setup - end
//	processing Interaction Summary - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Interaction_Summary_".$id);
		$type=postvalue("type_Interaction_Summary_".$id);
		if (FieldSubmitted("Interaction Summary_".$id))
		{
				$value=prepare_for_db("Interaction Summary",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Interaction Summary"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Interaction Summary"]=$value;
		}
		}
//	processibng Interaction Summary - end
//	processing Commercial Summary - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Commercial_Summary_".$id);
		$type=postvalue("type_Commercial_Summary_".$id);
		if (FieldSubmitted("Commercial Summary_".$id))
		{
				$value=prepare_for_db("Commercial Summary",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Commercial Summary"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Commercial Summary"]=$value;
		}
		}
//	processibng Commercial Summary - end
//	processing Customer Status - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Customer_Status_".$id);
		$type=postvalue("type_Customer_Status_".$id);
		if (FieldSubmitted("Customer Status_".$id))
		{
				$value=prepare_for_db("Customer Status",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Customer Status"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Customer Status"]=$value;
		}
		}
//	processibng Customer Status - end
//	processing Last Updated on - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Last_Updated_on_".$id);
		$type=postvalue("type_Last_Updated_on_".$id);
		if (FieldSubmitted("Last Updated on_".$id))
		{
				$value=prepare_for_db("Last Updated on",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Last Updated on"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Last Updated on"]=$value;
		}
		}
//	processibng Last Updated on - end
//	processing Created on - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Created_on_".$id);
		$type=postvalue("type_Created_on_".$id);
		if (FieldSubmitted("Created on_".$id))
		{
				$value=prepare_for_db("Created on",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Created on"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Created on"]=$value;
		}
		}
//	processibng Created on - end
//	processing Assigned Executive - start
	$inlineAddOption = true;
	$inlineAddOption = $inlineadd!=ADD_INLINE;
	if($inlineAddOption)
	{
		$value = postvalue("value_Assigned_Executive_".$id);
		$type=postvalue("type_Assigned_Executive_".$id);
		if (FieldSubmitted("Assigned Executive_".$id))
		{
				$value=prepare_for_db("Assigned Executive",$value,$type);
		}
		else
			$value=false;
		
		if(!($value===false))
		{
	
	
						if(1 && "Assigned Executive"=="password" && $url_page=="admin_users_")
				$value=md5($value);
			$avalues["Assigned Executive"]=$value;
		}
		}
//	processibng Assigned Executive - end

//	insert ownerid value if exists
	if($strOriginalTableName == GetFieldData($strTableName, "Region", "ownerTable", ""))
		$avalues["Region"]=prepare_for_db("Region",$_SESSION["_".$strTableName."_OwnerID"]);



	$failed_inline_add=false;
//	add filenames to values
	foreach($afilename_values as $akey=>$value)
		$avalues[$akey]=$value;
	
//	before Add event
	$retval = true;
	if($eventObj->exists("BeforeAdd"))
		$retval=$eventObj->BeforeAdd($avalues,$usermessage,(bool)$inlineadd);
	if($retval && $pageObject->isCaptchaOk)
	{
		$_SESSION[$strTableName."_count_captcha"] = $_SESSION[$strTableName."_count_captcha"]+1;
		if(DoInsertRecord($strOriginalTableName,$avalues,$blobfields,$id,$pageObject))
		{
			$IsSaved=true;
//	after edit event
			if($auditObj || $eventObj->exists("AfterAdd"))
			{
				foreach($keys as $idx=>$val)
					$avalues[$idx]=$val;
			}
			
			if($auditObj)
				$auditObj->LogAdd($strTableName,$avalues,$keys);

			if($eventObj->exists("AfterAdd"))
				$eventObj->AfterAdd($avalues,$keys,(bool)$inlineadd);
				
			if($inlineadd==ADD_SIMPLE || $inlineadd==ADD_MASTER)
			{
				$permis = array();
				$keylink = "";$k = 0;
				foreach($keys as $idx=>$val)
				{
					if($k!=0)
						$keylink .="&";
					$keylink .="editid".(++$k)."=".htmlspecialchars(rawurlencode(@$val));
				}
				$permis = $pageObject->getPermissions();				
				if (count($keys))
				{
					$message .="</br>";
					if(GetTableData($strTableName,".edit",false) && $permis['edit'])
						$message .='&nbsp;<a href=\'List_Management_edit.php?'.$keylink.'\'>'."Edit".'</a>&nbsp;';
					if(GetTableData($strTableName,".view",false) && $permis['search'])
						$message .='&nbsp;<a href=\'List_Management_view.php?'.$keylink.'\'>'."View".'</a>&nbsp;';
				}
				$mesClass = "mes_ok";	
			}
		}
		elseif($inlineadd!=ADD_INLINE)
			$mesClass = "mes_not";	
	}
	else
	{
		$message = $usermessage;
		$status="DECLINED";
		$readavalues=true;
	}
}

$message = "<div class='message ".$mesClass."'>".$message."</div>";

// PRG rule, to avoid POSTDATA resend
if (no_output_done() && $inlineadd==ADD_SIMPLE && $IsSaved)
{
	// saving message
	$_SESSION["message"] = ($message ? $message : "");
	// redirect
	header("Location: List_Management_".$pageObject->getPageType().".php");
	// turned on output buffering, so we need to stop script
	exit();
}

if($inlineadd==ADD_MASTER && $IsSaved)
	$_SESSION["message"] = ($message ? $message : "");
	
// for PRG rule, to avoid POSTDATA resend. Saving mess in session
if($inlineadd==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))
	{
		$copykeys["idCL"]=postvalue("copyid1");
	}
	else
	{
		$copykeys["idCL"]=postvalue("editid1");
	}
	$strWhere=KeyWhere($copykeys);
	$strWhere=whereAdd($strWhere,SecuritySQL("Search"));
	$strSQL = gSQLWhere($strWhere);

	LogInfo($strSQL);
	$rs=db_query($strSQL,$conn);
	$defvalues=db_fetch_array($rs);
	if(!$defvalues)
		$defvalues=array();
//	clear key fields
	$defvalues["idCL"]="";
//call CopyOnLoad event
	if($eventObj->exists("CopyOnLoad"))
		$eventObj->CopyOnLoad($defvalues,$strWhere);
}
else
{
	$defvalues["Country"]="India";
	$defvalues["Customer Status"]="Pending";
	$defvalues["Last Updated on"]=Now();
	$defvalues["Created on"]=Now();
	$defvalues["Assigned Executive"]=$_SESSION["UserID"];
}


if($readavalues)
{
	$defvalues["Customer Name"]=@$avalues["Customer Name"];
	$defvalues["Address"]=@$avalues["Address"];
	$defvalues["City"]=@$avalues["City"];
	$defvalues["State"]=@$avalues["State"];
	$defvalues["Country"]=@$avalues["Country"];
	$defvalues["Postal Code"]=@$avalues["Postal Code"];
	$defvalues["Web address"]=@$avalues["Web address"];
	$defvalues["Area"]=@$avalues["Area"];
	$defvalues["Customer_Category"]=@$avalues["Customer_Category"];
	$defvalues["Breif About the Company"]=@$avalues["Breif About the Company"];
	$defvalues["Existing Setup"]=@$avalues["Existing Setup"];
	$defvalues["Interaction Summary"]=@$avalues["Interaction Summary"];
	$defvalues["Commercial Summary"]=@$avalues["Commercial Summary"];
	$defvalues["Customer Status"]=@$avalues["Customer Status"];
	$defvalues["Region"]=@$avalues["Region"];
	$defvalues["Last Updated on"]=@$avalues["Last Updated on"];
	$defvalues["Created on"]=@$avalues["Created on"];
	$defvalues["Assigned Executive"]=@$avalues["Assigned Executive"];
}

if($eventObj->exists("ProcessValuesAdd"))
	$eventObj->ProcessValuesAdd($defvalues);


//for basic files
$includes="";

if($inlineadd!=ADD_INLINE)
{
	if($inlineadd!=ADD_ONTHEFLY && $inlineadd!=ADD_POPUP)
	{
		$includes .="<script language=\"JavaScript\" src=\"include/jquery.js\"></script>\r\n";
		if ($pageObject->debugJSMode===true)
		{
			/*$includes.="<script type=\"text/javascript\" src=\"include/runnerJS/Runner.js\"></script>\r\n".
				"<script type=\"text/javascript\" src=\"include/runnerJS/Util.js\"></script>\r\n".
				"<script type=\"text/javascript\" src=\"include/runnerJS/Observer.js\"></script>\r\n";*/
			$includes.="<script language=\"JavaScript\" src=\"include/runnerJS/RunnerBase.js\"></script>\r\n";
		}
		else 
			$includes .= "<script type=\"text/javascript\" src=\"include/runnerJS/RunnerBase.js\"></script>";
		
		$includes.="<script language=\"JavaScript\" src=\"include/jsfunctions.js\"></script>\r\n";
		$includes.="<div id=\"search_suggest\"></div>\r\n";
	}
	
	if(!$pageObject->isAppearOnTabs("Customer Name"))
		$xt->assign("Customer_Name_fieldblock",true);
	else
		$xt->assign("Customer_Name_tabfieldblock",true);
	$xt->assign("Customer_Name_label",true);
	if(isEnableSection508())
		$xt->assign_section("Customer_Name_label","<label for=\"".GetInputElementId("Customer Name", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Address"))
		$xt->assign("Address_fieldblock",true);
	else
		$xt->assign("Address_tabfieldblock",true);
	$xt->assign("Address_label",true);
	if(isEnableSection508())
		$xt->assign_section("Address_label","<label for=\"".GetInputElementId("Address", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("City"))
		$xt->assign("City_fieldblock",true);
	else
		$xt->assign("City_tabfieldblock",true);
	$xt->assign("City_label",true);
	if(isEnableSection508())
		$xt->assign_section("City_label","<label for=\"".GetInputElementId("City", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("State"))
		$xt->assign("State_fieldblock",true);
	else
		$xt->assign("State_tabfieldblock",true);
	$xt->assign("State_label",true);
	if(isEnableSection508())
		$xt->assign_section("State_label","<label for=\"".GetInputElementId("State", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Country"))
		$xt->assign("Country_fieldblock",true);
	else
		$xt->assign("Country_tabfieldblock",true);
	$xt->assign("Country_label",true);
	if(isEnableSection508())
		$xt->assign_section("Country_label","<label for=\"".GetInputElementId("Country", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Postal Code"))
		$xt->assign("Postal_Code_fieldblock",true);
	else
		$xt->assign("Postal_Code_tabfieldblock",true);
	$xt->assign("Postal_Code_label",true);
	if(isEnableSection508())
		$xt->assign_section("Postal_Code_label","<label for=\"".GetInputElementId("Postal Code", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Web address"))
		$xt->assign("Web_address_fieldblock",true);
	else
		$xt->assign("Web_address_tabfieldblock",true);
	$xt->assign("Web_address_label",true);
	if(isEnableSection508())
		$xt->assign_section("Web_address_label","<label for=\"".GetInputElementId("Web address", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Area"))
		$xt->assign("Area_fieldblock",true);
	else
		$xt->assign("Area_tabfieldblock",true);
	$xt->assign("Area_label",true);
	if(isEnableSection508())
		$xt->assign_section("Area_label","<label for=\"".GetInputElementId("Area", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Customer_Category"))
		$xt->assign("Customer_Category_fieldblock",true);
	else
		$xt->assign("Customer_Category_tabfieldblock",true);
	$xt->assign("Customer_Category_label",true);
	if(isEnableSection508())
		$xt->assign_section("Customer_Category_label","<label for=\"".GetInputElementId("Customer_Category", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Breif About the Company"))
		$xt->assign("Breif_About_the_Company_fieldblock",true);
	else
		$xt->assign("Breif_About_the_Company_tabfieldblock",true);
	$xt->assign("Breif_About_the_Company_label",true);
	if(isEnableSection508())
		$xt->assign_section("Breif_About_the_Company_label","<label for=\"".GetInputElementId("Breif About the Company", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Existing Setup"))
		$xt->assign("Existing_Setup_fieldblock",true);
	else
		$xt->assign("Existing_Setup_tabfieldblock",true);
	$xt->assign("Existing_Setup_label",true);
	if(isEnableSection508())
		$xt->assign_section("Existing_Setup_label","<label for=\"".GetInputElementId("Existing Setup", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Interaction Summary"))
		$xt->assign("Interaction_Summary_fieldblock",true);
	else
		$xt->assign("Interaction_Summary_tabfieldblock",true);
	$xt->assign("Interaction_Summary_label",true);
	if(isEnableSection508())
		$xt->assign_section("Interaction_Summary_label","<label for=\"".GetInputElementId("Interaction Summary", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Commercial Summary"))
		$xt->assign("Commercial_Summary_fieldblock",true);
	else
		$xt->assign("Commercial_Summary_tabfieldblock",true);
	$xt->assign("Commercial_Summary_label",true);
	if(isEnableSection508())
		$xt->assign_section("Commercial_Summary_label","<label for=\"".GetInputElementId("Commercial Summary", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Customer Status"))
		$xt->assign("Customer_Status_fieldblock",true);
	else
		$xt->assign("Customer_Status_tabfieldblock",true);
	$xt->assign("Customer_Status_label",true);
	if(isEnableSection508())
		$xt->assign_section("Customer_Status_label","<label for=\"".GetInputElementId("Customer Status", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Region"))
		$xt->assign("Region_fieldblock",true);
	else
		$xt->assign("Region_tabfieldblock",true);
	$xt->assign("Region_label",true);
	if(isEnableSection508())
		$xt->assign_section("Region_label","<label for=\"".GetInputElementId("Region", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Last Updated on"))
		$xt->assign("Last_Updated_on_fieldblock",true);
	else
		$xt->assign("Last_Updated_on_tabfieldblock",true);
	$xt->assign("Last_Updated_on_label",true);
	if(isEnableSection508())
		$xt->assign_section("Last_Updated_on_label","<label for=\"".GetInputElementId("Last Updated on", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Created on"))
		$xt->assign("Created_on_fieldblock",true);
	else
		$xt->assign("Created_on_tabfieldblock",true);
	$xt->assign("Created_on_label",true);
	if(isEnableSection508())
		$xt->assign_section("Created_on_label","<label for=\"".GetInputElementId("Created on", $id)."\">","</label>");
	
	if(!$pageObject->isAppearOnTabs("Assigned Executive"))
		$xt->assign("Assigned_Executive_fieldblock",true);
	else
		$xt->assign("Assigned_Executive_tabfieldblock",true);
	$xt->assign("Assigned_Executive_label",true);
	if(isEnableSection508())
		$xt->assign_section("Assigned_Executive_label","<label for=\"".GetInputElementId("Assigned Executive", $id)."\">","</label>");
	
	
	
	if($inlineadd!=ADD_ONTHEFLY && $inlineadd!=ADD_POPUP)
	{
		$pageObject->body["begin"] .= $includes;
		if($pageObject->isShowDetailTables)
			$pageObject->body["begin"].= "<div id=\"master_details\" onmouseover=\"RollDetailsLink.showPopup();\" onmouseout=\"RollDetailsLink.hidePopup();\"> </div>";
		$xt->assign("backbutton_attrs","id=\"backButton".$id."\"");
		$xt->assign("back_button",true);
		//$xt->assign('addForm', true);
	}
	else
	{		
		$xt->assign("cancelbutton_attrs", "id=\"cancelButton".$id."\"");
		$xt->assign("cancel_button",true);
		$xt->assign("header","");
	}
	$xt->assign("save_button",true);
}
$xt->assign("savebutton_attrs","id=\"saveButton".$id."\"");
if($message)
{
	$xt->assign("message_block",true);
	$xt->assign("message",$message);
}
/*
if($inlineadd == ADD_ONTHEFLY || $inlineadd == ADD_POPUP)
{
	$xt->assign("message_block",true);
}
*/

$readonlyfields=array();

//	show readonly fields
$linkdata="";

if(@$_POST["a"]=="added" && $inlineadd==ADD_ONTHEFLY)
{
	if( !$error_happened && $status!="DECLINED")
	{
		$LookupSQL = "";
		$linkfield = "";
		$dispfield = "";
		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)
		{
			$respData = array($linkfield=>@$data[0], $dispfield=>@$data[1]);
		}
		else
		{
			$respData = array($linkfield=>@$avalues[$linkfield], $dispfield=>@$avalues[$dispfield]);
		}		
		$returnJSON['success'] = true;
		$returnJSON['keys'] = $keys;
		$returnJSON['vals'] = $respData;
		$returnJSON['fields'] = $showFields;
	}
	else
	{
		$returnJSON['success'] = false;
		$returnJSON['message'] = $message;
	}
	echo "<textarea>".htmlspecialchars(my_json_encode($returnJSON))."</textarea>";
	exit();
}

if(@$_POST["a"]=="added" && ($inlineadd == ADD_INLINE || $inlineadd == ADD_MASTER || $inlineadd==ADD_POPUP)) 
{
	//Preparation   view values
	//	get current values and show edit controls
	$dispFieldAlias = "";
	$data=0;
	if(count($keys))
	{
		$where=KeyWhere($keys);
		//	select only owned records
		$where=whereAdd($where,SecuritySQL("Search"));
		
		$sqlHead = $gQuery->HeadToSql();
		$sqlGroupBy = $gQuery->GroupByToSql();
		$oHaving = $gQuery->Having();
		$sqlHaving = $oHaving->toSql($gQuery);
		
		$dispFieldAlias = postvalue('dispFieldAlias');
		$dispField = postvalue('dispField');
		
		if ($dispFieldAlias)
		{
			$sqlHead.=", ".($dispField)." as ".AddFieldWrappers($dispFieldAlias)." ";
		}
		$strSQL = gSQLWhere_having($sqlHead, $gsqlFrom, $gsqlWhereExpr, $sqlGroupBy, $sqlHaving, $where, '');		
		
		LogInfo($strSQL);
		$rs=db_query($strSQL,$conn);
		$data=db_fetch_array($rs);
	}
	if(!$data)
	{
		$data=$avalues;
		$HaveData=false;
	}
	//check if correct values added
	$masterquery="mastertable=List+Management";
	$masterquery.="&masterkey1=".rawurlencode($data["Customer Name"]);
	$showDetailKeys["Contact_Details"]=$masterquery;

	$keylink="";
	$keylink.="&key1=".htmlspecialchars(rawurlencode(@$data["idCL"]));
	
////////////////////////////////////////////
//	idCL - 
	$display = false;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"idCL", ""),"field=idCL".$keylink,"",MODE_LIST);
	$showValues["idCL"] = $value;
	$showFields[] = "idCL";
		$showRawValues["idCL"] = substr($data["idCL"],0,100);
	}	
//	Customer Name - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Customer Name", ""),"field=Customer+Name".$keylink,"",MODE_LIST);
	$showValues["Customer Name"] = $value;
	$showFields[] = "Customer Name";
		$showRawValues["Customer Name"] = substr($data["Customer Name"],0,100);
	}	
//	Address - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Address", ""),"field=Address".$keylink,"",MODE_LIST);
	$showValues["Address"] = $value;
	$showFields[] = "Address";
		$showRawValues["Address"] = substr($data["Address"],0,100);
	}	
//	City - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"City", ""),"field=City".$keylink,"",MODE_LIST);
	$showValues["City"] = $value;
	$showFields[] = "City";
		$showRawValues["City"] = substr($data["City"],0,100);
	}	
//	State - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"State", ""),"field=State".$keylink,"",MODE_LIST);
	$showValues["State"] = $value;
	$showFields[] = "State";
		$showRawValues["State"] = substr($data["State"],0,100);
	}	
//	Country - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Country", ""),"field=Country".$keylink,"",MODE_LIST);
	$showValues["Country"] = $value;
	$showFields[] = "Country";
		$showRawValues["Country"] = substr($data["Country"],0,100);
	}	
//	Postal Code - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Postal Code", ""),"field=Postal+Code".$keylink,"",MODE_LIST);
	$showValues["Postal Code"] = $value;
	$showFields[] = "Postal Code";
		$showRawValues["Postal Code"] = substr($data["Postal Code"],0,100);
	}	
//	Web address - Hyperlink
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = GetData($data,"Web address", "Hyperlink");
	$showValues["Web address"] = $value;
	$showFields[] = "Web address";
		$showRawValues["Web address"] = substr($data["Web address"],0,100);
	}	
//	Area - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Area", ""),"field=Area".$keylink,"",MODE_LIST);
	$showValues["Area"] = $value;
	$showFields[] = "Area";
		$showRawValues["Area"] = substr($data["Area"],0,100);
	}	
//	Customer_Category - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Customer_Category", ""),"field=Customer%5FCategory".$keylink,"",MODE_LIST);
	$showValues["Customer_Category"] = $value;
	$showFields[] = "Customer_Category";
		$showRawValues["Customer_Category"] = substr($data["Customer_Category"],0,100);
	}	
//	Breif About the Company - HTML
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = GetData($data,"Breif About the Company", "HTML");
	$showValues["Breif About the Company"] = $value;
	$showFields[] = "Breif About the Company";
		$showRawValues["Breif About the Company"] = substr($data["Breif About the Company"],0,100);
	}	
//	Existing Setup - HTML
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = GetData($data,"Existing Setup", "HTML");
	$showValues["Existing Setup"] = $value;
	$showFields[] = "Existing Setup";
		$showRawValues["Existing Setup"] = substr($data["Existing Setup"],0,100);
	}	
//	Interaction Summary - HTML
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = GetData($data,"Interaction Summary", "HTML");
	$showValues["Interaction Summary"] = $value;
	$showFields[] = "Interaction Summary";
		$showRawValues["Interaction Summary"] = substr($data["Interaction Summary"],0,100);
	}	
//	Commercial Summary - HTML
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = GetData($data,"Commercial Summary", "HTML");
	$showValues["Commercial Summary"] = $value;
	$showFields[] = "Commercial Summary";
		$showRawValues["Commercial Summary"] = substr($data["Commercial Summary"],0,100);
	}	
//	Customer Status - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Customer Status", ""),"field=Customer+Status".$keylink,"",MODE_LIST);
	$showValues["Customer Status"] = $value;
	$showFields[] = "Customer Status";
		$showRawValues["Customer Status"] = substr($data["Customer Status"],0,100);
	}	
//	Region - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Region", ""),"field=Region".$keylink,"",MODE_LIST);
	$showValues["Region"] = $value;
	$showFields[] = "Region";
		$showRawValues["Region"] = substr($data["Region"],0,100);
	}	
//	Last Updated on - Short Date
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Last Updated on", "Short Date"),"field=Last+Updated+on".$keylink,"",MODE_LIST);
	$showValues["Last Updated on"] = $value;
	$showFields[] = "Last Updated on";
		$showRawValues["Last Updated on"] = substr($data["Last Updated on"],0,100);
	}	
//	Created on - Short Date
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Created on", "Short Date"),"field=Created+on".$keylink,"",MODE_LIST);
	$showValues["Created on"] = $value;
	$showFields[] = "Created on";
		$showRawValues["Created on"] = substr($data["Created on"],0,100);
	}	
//	Assigned Executive - 
	$display = false;
	if($inlineadd==ADD_MASTER)
		$display = true;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Assigned Executive", ""),"field=Assigned+Executive".$keylink,"",MODE_LIST);
	$showValues["Assigned Executive"] = $value;
	$showFields[] = "Assigned Executive";
		$showRawValues["Assigned Executive"] = substr($data["Assigned Executive"],0,100);
	}	
//	Aligned Partner - 
	$display = false;
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		$display = true;
	if($display)
	{	
		$value="";
			$value = ProcessLargeText(GetData($data,"Aligned Partner", ""),"field=Aligned+Partner".$keylink,"",MODE_LIST);
	$showValues["Aligned Partner"] = $value;
	$showFields[] = "Aligned Partner";
		$showRawValues["Aligned Partner"] = substr($data["Aligned Partner"],0,100);
	}	
	
	// for custom expression for display field
	if ($dispFieldAlias)
	{
		$showValues[] = $data[$dispFieldAlias];	
		$showFields[] = $dispFieldAlias;
		$showRawValues[] = substr($data[$dispFieldAlias],0,100);
	}		
	
	if($inlineadd==ADD_INLINE || $inlineadd==ADD_POPUP)
	{	
		if($IsSaved && count($showValues))
		{		
			$returnJSON['success'] = true;	
			if($HaveData){
				$returnJSON['noKeys'] = false;
			}else{
				$returnJSON['noKeys'] = true;
			}
				
			$returnJSON['keys'] = $keys;
			$returnJSON['vals'] = $showValues;
			$returnJSON['fields'] = $showFields;
			$returnJSON['rawVals'] = $showRawValues;
			$returnJSON['detKeys'] = $showDetailKeys;
			$returnJSON['userMess'] = $usermessage;
		}
		else
		{
			$returnJSON['success'] = false;
			$returnJSON['message'] = $message;
		}
		echo "<textarea>".htmlspecialchars(my_json_encode($returnJSON))."</textarea>";
		exit();
	}	
} 

/////////////////////////////////////////////////////////////
if($inlineadd==ADD_MASTER)
{		
	$respJSON = array();
	if(($_POST["a"]=="added" && $IsSaved))
	{
		$respJSON['success'] = true;
		$respJSON['fields'] = $showFields;
		$respJSON['vals'] = $showValues;
		if($onFly){
			if($HaveData)
				$returnJSON['noKeys'] = false;
			else
				$returnJSON['noKeys'] = true;
			$respJSON['keys'] = $keys;
			$respJSON['rawVals'] = $showRawValues;
			$respJSON['detKeys'] = $showDetailKeys;
			$respJSON['userMess'] = $usermessage;
		}
		$respJSON['mKeys'] = array();	
		for($i=0;$i<count($dpParams['ids']);$i++)
		{
			$data=0;
			if(count($keys))
			{
				$where=KeyWhere($keys);
							//	select only owned records
				$where=whereAdd($where,SecuritySQL("Search"));
				$strSQL = gSQLWhere($where);
				LogInfo($strSQL);
				$rs=db_query($strSQL,$conn);
				$data=db_fetch_array($rs);
			}
			if(!$data)
				$data=$avalues;
			
			$mKeyId = 1;
			foreach($mKeys[$dpParams['strTableNames'][$i]] as $mk)	
			{
				if($data[$mk])
					$respJSON['mKeys'][$dpParams['strTableNames'][$i]]['masterkey'.$mKeyId++] = $data[$mk];
				else
					$respJSON['mKeys'][$dpParams['strTableNames'][$i]]['masterkey'.$mKeyId++] = '';
			}		
		}
		if((isset($_SESSION[$strTableName."_count_captcha"])) or ($_SESSION[$strTableName."_count_captcha"]>0) or ($_SESSION[$strTableName."_count_captcha"]<5))
			$respJSON['hideCaptha'] = true;
	}
	else{
			$respJSON['success'] = false;
			if(!$pageObject->isCaptchaOk)
				$respJSON['captha'] = false;
			else		
				$respJSON['error'] = $message;
			if($onFly)
				$respJSON['message'] = $message;				
		}
	echo "<textarea>".htmlspecialchars(my_json_encode($respJSON))."</textarea>";	
	exit();
}

/////////////////////////////////////////////////////////////
//	prepare Edit Controls
/////////////////////////////////////////////////////////////

//	validation stuff
$regex='';
$regexmessage='';
$regextype = '';
$control = array();

foreach($addFields as $fName)
{
	$gfName = GoodFieldName($fName);
	$controls = array('controls'=>array());
	if(!$detailKeys || !in_array($fName, $detailKeys) || $fName == postvalue("category"))
	{		
		$control[$gfName] = array();
		$control[$gfName]["func"]="xt_buildeditcontrol";
		$control[$gfName]["params"] = array();
		$control[$gfName]["params"]["id"]= $id;
		$control[$gfName]["params"]["field"]=$fName;
		$control[$gfName]["params"]["value"]=@$defvalues[$fName];
		if(UseRTE($fName))
			$_SESSION[$strTableName."_".$fName."_rte"]=@$defvalues[$fName];
		
		//	Begin Add validation
		$arrValidate = getValidation($fName,$strTableName);	
		$control[$gfName]["params"]["validate"] = $arrValidate;
		//	End Add validation	
	}
	$controls["controls"]['ctrlInd'] = 0;
	$controls["controls"]['id'] = $id;
	$controls["controls"]['fieldName'] = $fName;
	
	if(UseRTEFCK($fName) || UseRTEInnova($fName) || UseRTEBasic($fName))
	{
		if(!$detailKeys || !in_array($fName, $detailKeys))	
			$control[$gfName]["params"]["mode"]="add";
		$controls["controls"]['mode'] = "add";
	}
	else
	{
		if($inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
		{
			if(!$detailKeys || !in_array($fName, $detailKeys) || $fName == postvalue("category"))	
				$control[$gfName]["params"]["mode"]="inline_add";
			$controls["controls"]['mode'] = "inline_add";
		}
		else
		{
			if(!$detailKeys || !in_array($fName, $detailKeys) || $fName == postvalue("category"))	
				$control[$gfName]["params"]["mode"]="add";
			$controls["controls"]['mode'] = "add";
		}
	}
			
	if(!$detailKeys || !in_array($fName, $detailKeys))
		$xt->assignbyref($gfName."_editcontrol",$control[$gfName]);
	elseif($detailKeys && in_array($fName, $detailKeys))
		$controls["controls"]['value'] = @$defvalues[$fName];
		
	// category control field
	$strCategoryControl = $pageObject->hasDependField($fName);
	
	if($strCategoryControl!==false && in_array($strCategoryControl, $addFields))
		$vals = array($fName => @$defvalues[$fName],$strCategoryControl => @$defvalues[$strCategoryControl]);
	else
		$vals = array($fName => @$defvalues[$fName]);
	
	$preload = $pageObject->fillPreload($fName, $vals);
	if($preload!==false)
		$controls["controls"]['preloadData'] = $preload;
	
	$pageObject->fillControlsMap($controls);
	
	//fill field tool tips
	$pageObject->fillFieldToolTips($fName);
	
	// fill special settings for timepicker 	
	if(GetEditFormat($fName) == 'Time')	
		$pageObject->fillTimePickSettings($fName, @$defvalues[$fName]);
	
	if((($detailKeys && in_array($fName, $detailKeys)) || $fName == postvalue("category")) && array_key_exists($fName, $defvalues))
	{
		if((GetEditFormat($fName)==EDIT_FORMAT_LOOKUP_WIZARD || GetEditFormat($fName)==EDIT_FORMAT_RADIO) && GetpLookupType($fName) == LT_LOOKUPTABLE)
			$value=DisplayLookupWizard($fName,$defvalues[$fName],$defvalues,"",MODE_VIEW);
		elseif(NeedEncode($fName))
			$value = ProcessLargeText(GetData($defvalues,$fName, ViewFormat($fName)),"field=".rawurlencode(htmlspecialchars($fName)),"",MODE_VIEW);
		else
			$value = GetData($defvalues,$fName, ViewFormat($fName));
		
		$xt->assign($gfName."_editcontrol", $value);
	}
}
//fill tab groups name and sections name to controls
$pageObject->fillCntrlTabGroups();

//fill jsSettings and ControlsHTMLMap
$pageObject->fillSetCntrlMaps();

/////////////////////////////////////////////////////////////
if($pageObject->isShowDetailTables && ($inlineadd==ADD_SIMPLE || $inlineadd==ADD_POPUP))
{
	$options = array();
	//array of params for classes
	$options["mode"] = LIST_DETAILS;
	$options["pageType"] = PAGE_LIST;
	$options["masterPageType"] = PAGE_ADD;
	$options["mainMasterPageType"] = PAGE_ADD;
	$options['masterTable'] = $strTableName;
	$options['firstTime'] = 1;

	if(count($dpParams['ids']))
	{
		$xt->assign("detail_tables",true);
		include('classes/listpage.php');
		include('classes/listpage_embed.php');
		include('classes/listpage_dpinline.php');
		include("classes/searchclause.php");
	}
	
	$dControlsMap = array();
		
	$flyId = $ids+1;
	for($d=0;$d<count($dpParams['ids']);$d++)
	{
		$strTableName = $dpParams['strTableNames'][$d];
		include("include/".GetTableURL($strTableName)."_settings.php");
		$options['xt'] = new Xtempl();
		$options['id'] = $dpParams['ids'][$d];
		$options['flyId'] = $flyId++;
		$mkr=1;
		
		foreach($mKeys[$strTableName] as $mk)
		{
			if($defvalues[$mk])
				$options['masterKeysReq'][$mkr++] = $defvalues[$mk];
			else
				$options['masterKeysReq'][$mkr++] = '';
		}
		
		$listPageObject = ListPage::createListPage($strTableName,$options);
		// prepare code
		$listPageObject->prepareForBuildPage();
		$flyId = $listPageObject->recId+1;
		
		if($listPageObject->isDispGrid())
		{
			//add detail settings to master settings
			$listPageObject->fillSetCntrlMaps();
			$pageObject->jsSettings['tableSettings'][$strTableName]	= $listPageObject->jsSettings['tableSettings'][$strTableName];		
			$dControlsMap[$strTableName]['gridRows'] = $listPageObject->controlsHTMLMap[$strTableName][PAGE_LIST][$dpParams['ids'][$d]]['gridRows'];
			$dControlsMap[$strTableName]['video'] = $listPageObject->controlsHTMLMap[$strTableName][PAGE_LIST][$dpParams['ids'][$d]]['video'];
			$dControlsMap[$strTableName]['gMaps'] = $listPageObject->controlsHTMLMap[$strTableName][PAGE_LIST][$dpParams['ids'][$d]]['gMaps'];
			foreach($listPageObject->jsSettings['global']['shortTNames'] as $key=>$val)
			{
				if(!array_key_exists($key,$pageObject->jsSettings['global']['shortTNames']))
					$pageObject->jsSettings['global']['shortTNames'][$key] = $val;
			}	
			
			//Add detail's js files to master's files
			$pageObject->copyAllJSFiles($listPageObject->grabAllJSFiles());
			
			//Add detail's css files to master's files	
			$pageObject->copyAllCSSFiles($listPageObject->grabAllCSSFiles());
		}
		$xt->assign("displayDetailTable_".GoodFieldName($strTableName), array("func" => "showDetailTable","params" => array("dpObject" => $listPageObject, "dpParams" => $strTableName)));
	}
	$strTableName = "List Management";
	$pageObject->controlsHTMLMap[$strTableName][PAGE_ADD][$id]['dControlsMap'] = $dControlsMap;	
}
/////////////////////////////////////////////////////////////

if($inlineadd == ADD_SIMPLE)
{
	$pageObject->body['end'] .= '<script>';
	$pageObject->body['end'] .= "window.controlsMap = '".jsreplace(my_json_encode($pageObject->controlsHTMLMap))."';";
	$pageObject->body['end'] .= "window.settings = '".jsreplace(my_json_encode($pageObject->jsSettings))."';";
	$pageObject->body['end'] .= '</script>';
}
else{
		$returnJSON['controlsMap'] = $pageObject->controlsHTMLMap;
		//if($isNeedSettings)
		$returnJSON['settings'] = $pageObject->jsSettings;	
	}

$pageObject->addCommonJs();

$jscode = $pageObject->PrepareJS();
if($inlineadd==ADD_SIMPLE)
{
	$pageObject->body["end"] .= "<script>".$jscode."</script>";
	$xt->assign("body",$pageObject->body);
	$xt->assign("flybody",true);
}
elseif($inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_MASTER || $inlineadd==ADD_POPUP)
{ 
	$xt->assign("footer","");
	$xt->assign("flybody",$pageObject->body);
	$xt->assign("body",true);
}	

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

if($eventObj->exists("BeforeShowAdd"))
	$eventObj->BeforeShowAdd($xt,$templatefile);

if($inlineadd==ADD_ONTHEFLY || $inlineadd==ADD_POPUP)
{
	$xt->load_template($templatefile);
	$returnJSON['html'] = $xt->fetch_loaded('style_block').$xt->fetch_loaded('flybody');
	if($inlineadd==ADD_POPUP && $pageObject->isShowDetailTables)
		$returnJSON['html'].= $xt->fetch_loaded('detail_tables');
	$returnJSON['idStartFrom'] = $id+1;	
	echo (my_json_encode($returnJSON)); 
}
elseif ($inlineadd == ADD_INLINE)
{
	$xt->load_template($templatefile);
	$returnJSON["html"] = array();
	foreach($addFields as $fName)
	{
		$returnJSON["html"][$fName] = $xt->fetchVar(GoodFieldName($fName)."_editcontrol");	
	}	
	echo (my_json_encode($returnJSON)); 
}
else
	$xt->display($templatefile);

?>
