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


include("include/dbcommon.php");
include("include/Pending_Customers_variables.php");
include('include/xtempl.php');
include('classes/runnerpage.php');
include("classes/searchclause.php");

add_nocache_headers();

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

/////////////////////////////////////////////////////////////
//init variables
/////////////////////////////////////////////////////////////
if(postvalue("editType")=="inline")
	$inlineedit = EDIT_INLINE;
elseif(postvalue("editType")==EDIT_POPUP)
	$inlineedit = EDIT_POPUP;
else
	$inlineedit = EDIT_SIMPLE;			

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

$flyId = $id+1;	
$xt = new Xtempl();

// assign an id		
$xt->assign("id",$id);

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

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

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


$params['tName'] = $strTableName;
$params['xt'] = &$xt;
$params['mode'] = $inlineedit;
$params['includes_js']=$includes_js;
$params['includes_jsreq']=$includes_jsreq;
$params['includes_css']=$includes_css;
$params['locale_info']=$locale_info;
$params['pageEditLikeInline'] = ($inlineedit == EDIT_INLINE);
//Get array of tabs for edit page
$params['useTabsOnEdit'] = useTabsOnEdit($strTableName);
if($params['useTabsOnEdit'])
	$params['arrEditTabs'] = GetEditTabs($strTableName);
$pageObject = new RunnerPage($params);

//	For ajax request 
if($_REQUEST["action"]!="")
{
	if($pageObject->lockingObj)
	{
		$arrkeys = explode("&",refine($_REQUEST["keys"]));
		foreach($arrkeys as $ind=>$val)
			$arrkeys[$ind]=urldecode($val);
		
		if($_REQUEST["action"]=="unlock")
		{
			$pageObject->lockingObj->UnlockRecord($strTableName,$arrkeys,$_REQUEST["sid"]);
			exit();	
		}
		else if($_REQUEST["action"]=="lockadmin" && (IsAdmin() || $_SESSION["AccessLevel"] == ACCESS_LEVEL_ADMINGROUP))
		{
			$pageObject->lockingObj->UnlockAdmin($strTableName,$arrkeys,$_REQUEST["startEdit"]=="yes");
			if($_REQUEST["startEdit"]=="no")
				echo "unlock";
			else if($_REQUEST["startEdit"]=="yes")
				echo "lock";
			exit();	
		}
		else if($_REQUEST["action"]=="confirm")
		{echo '<br>confirm';
			if(!$pageObject->lockingObj->ConfirmLock($strTableName,$arrkeys,$message));
				echo $message;
			exit();	
		}
	}
	else
		exit();
}

$filename = $status = $message = $mesClass = $usermessage = $strWhereClause = $bodyonload = "";
$showValues = $showRawValues = $showFields = $showDetailKeys = $key = $next = $prev = array();
$HaveData = $enableCtrlsForEditing = true;
$error_happened = $readevalues = $IsSaved = false;

$templatefile = "Pending_Customers_edit.htm";

$auditObj = GetAuditObject($strTableName);

// SearchClause class stuff
$pageObject->searchClauseObj->parseRequest();
$_SESSION[$strTableName.'_advsearch'] = serialize($pageObject->searchClauseObj);

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

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

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

if($pageObject->lockingObj)
{
	$system_attrs = "style='display:none;'";
	$system_message = "";
}

if ($inlineedit!=EDIT_INLINE)
{
	// add button events if exist
	$pageObject->addButtonHandlers();
}

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

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

$keys = array();
$skeys = "";
$savedKeys = array();
$keys["idCL"]=urldecode(postvalue("editid1"));
$savedKeys["idCL"]=urldecode(postvalue("editid1"));
$skeys.=rawurlencode(postvalue("editid1"))."&";

if($skeys!="")
	$skeys = substr($skeys,0,-1);

//For show detail tables on master page edit
if($inlineedit!=EDIT_INLINE)	
{
	$dpParams = array();
	if($pageObject->isShowDetailTables)
	{
		$ids = $id;
			$mKeys["Contact Details"] = GetMasterKeysByDetailTable("Contact Details", $strTableName);
		$dpParams['strTableNames'][] = "Contact Details";
		$dpParams['ids'][] = ++$ids;
			$mKeys["calls"] = GetMasterKeysByDetailTable("calls", $strTableName);
		$dpParams['strTableNames'][] = "calls";
		$dpParams['ids'][] = ++$ids;
		$pageObject->jsSettings['tableSettings'][$strTableName]['dpParams'] = array('tableNames'=>$dpParams['strTableNames'], 'ids'=>$dpParams['ids']);
		$pageObject->AddJSFile("include/detailspreview");
	}	
}	
/////////////////////////////////////////////////////////////
//	process entered data, read and save
/////////////////////////////////////////////////////////////

// proccess captcha
if ($inlineedit!=EDIT_INLINE)
	if($pageObject->captchaExists())
		$pageObject->doCaptchaCode();

if(@$_POST["a"] == "edited")
{
	$strWhereClause = whereAdd($strWhereClause,KeyWhere($keys));
		//	select only owned records
	$strWhereClause = whereAdd($strWhereClause,SecuritySQL("Edit"));
	$oldValuesRead = false;
	if($eventObj->exists("AfterEdit") || $eventObj->exists("BeforeEdit") || $auditObj)
	{
		//	read old values
		$rsold = db_query(gSQLWhere($strWhereClause), $conn);
		$dataold = db_fetch_array($rsold);
		$oldValuesRead = true;
	}
	$evalues = $efilename_values = $blobfields = array();
	

//	processing Customer Name - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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;
	
				$value = false;
		if($value!==false)
		{	
	
	
	
	
	
			if(1 && "Customer Name"=="password" && $url_page=="admin_users_")
				$value = md5($value);
			$evalues["Customer Name"] = $value;
		
			}
	
		}
//	processing Customer Name - end
//	processing Address - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Address"] = $value;
		
			}
	
		}
//	processing Address - end
//	processing City - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["City"] = $value;
		
			}
	
		}
//	processing City - end
//	processing State - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["State"] = $value;
		
			}
	
		}
//	processing State - end
//	processing Country - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Country"] = $value;
		
			}
	
		}
//	processing Country - end
//	processing Postal Code - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Postal Code"] = $value;
		
			}
	
		}
//	processing Postal Code - end
//	processing Web address - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Web address"] = $value;
		
			}
	
		}
//	processing Web address - end
//	processing Area - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Area"] = $value;
		
			}
	
		}
//	processing Area - end
//	processing Customer_Category - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Customer_Category"] = $value;
		
			}
	
		}
//	processing Customer_Category - end
//	processing Breif About the Company - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Breif About the Company"] = $value;
		
			}
	
		}
//	processing Breif About the Company - end
//	processing Existing Setup - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Existing Setup"] = $value;
		
			}
	
		}
//	processing Existing Setup - end
//	processing Interaction Summary - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Interaction Summary"] = $value;
		
			}
	
		}
//	processing Interaction Summary - end
//	processing Commercial Summary - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Commercial Summary"] = $value;
		
			}
	
		}
//	processing Commercial Summary - end
//	processing Customer Status - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Customer Status"] = $value;
		
			}
	
		}
//	processing Customer Status - end
//	processing Region - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Region"] = $value;
		
			}
	
		}
//	processing Region - end
//	processing Last Updated on - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Last Updated on"] = $value;
		
			}
	
		}
//	processing Last Updated on - end
//	processing Assigned Executive - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$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);
			$evalues["Assigned Executive"] = $value;
		
			}
	
		}
//	processing Assigned Executive - end
//	processing Assigned Date - begin
	$condition = $inlineedit!=EDIT_INLINE;//(!$inlineedit) edit simple mode

	if($condition)
	{
		$value = postvalue("value_Assigned_Date_".$id);
		$type = postvalue("type_Assigned_Date_".$id);
		if(FieldSubmitted("Assigned Date_".$id))
		{
				$value = prepare_for_db("Assigned Date",$value,$type);
		}
		else
			$value = false;
	
			if($value!==false)
		{	
	
	
	
	
	
			if(1 && "Assigned Date"=="password" && $url_page=="admin_users_")
				$value = md5($value);
			$evalues["Assigned Date"] = $value;
		
			}
	
		}
//	processing Assigned Date - end

	foreach($efilename_values as $ekey=>$value)
		$evalues[$ekey] = $value;
		
	if($pageObject->lockingObj)
	{
		$lockmessage = "";
		if(!$pageObject->lockingObj->ConfirmLock($strTableName,$savedKeys,$lockmessage))
		{
			$enableCtrlsForEditing = false;
			$system_attrs = "style='display:block;'";
			if($inlineedit == EDIT_INLINE)
			{
				if(IsAdmin() || $_SESSION["AccessLevel"] == ACCESS_LEVEL_ADMINGROUP)
					$lockmessage = $pageObject->lockingObj->GetLockInfo($strTableName,$savedKeys,false,$id);
				
				$returnJSON['success'] = false;
				$returnJSON['message'] = $lockmessage;
				$returnJSON['enableCtrls'] = $enableCtrlsForEditing;
				$returnJSON['confirmTime'] = $pageObject->lockingObj->ConfirmTime;
				echo "<textarea>".htmlspecialchars(my_json_encode($returnJSON))."</textarea>";
				exit();
			}
			else
			{
				if(IsAdmin() || $_SESSION["AccessLevel"] == ACCESS_LEVEL_ADMINGROUP)
					$system_message = $pageObject->lockingObj->GetLockInfo($strTableName,$savedKeys,true,$id);
				else
					$system_message = $lockmessage;
			}
			$status = "DECLINED";
			$readevalues = true;
		}
	}
	
	if($readevalues==false)
	{
	//	do event
		$retval = true;
		if($eventObj->exists("BeforeEdit"))
			$retval=$eventObj->BeforeEdit($evalues,$strWhereClause,$dataold,$keys,$usermessage,(bool)$inlineedit);
		if($retval && $pageObject->isCaptchaOk)
		{		
			if($inlineedit!=EDIT_INLINE)
				$_SESSION[$strTableName."_count_captcha"] = $_SESSION[$strTableName."_count_captcha"]+1;
				
			if(DoUpdateRecord($strOriginalTableName,$evalues,$blobfields,$strWhereClause,$id,$pageObject))
			{
				$IsSaved = true;
				
				//	after edit event
				if($pageObject->lockingObj && $inlineedit == EDIT_INLINE)
					$pageObject->lockingObj->UnlockRecord($strTableName,$savedKeys,"");
				if($auditObj || $eventObj->exists("AfterEdit"))
				{
					foreach($dataold as $idx=>$val)
					{
						if(!array_key_exists($idx,$evalues))
							$evalues[$idx] = $val;
					}
				}

				if($auditObj)
					$auditObj->LogEdit($strTableName,$evalues,$dataold,$keys);
				if($eventObj->exists("AfterEdit"))
					$eventObj->AfterEdit($evalues,KeyWhere($keys),$dataold,$keys,(bool)$inlineedit);
							
				$mesClass = "mes_ok";	
			}
			elseif($inlineedit!=EDIT_INLINE)
				$mesClass = "mes_not";	
		}
		else
		{
			$message = $usermessage;
			$readevalues = true;
			$status = "DECLINED";
		}
	}
	if($readevalues)
		$keys = $savedKeys;
}
//else
{
	/////////////////////////
	//Locking recors
	/////////////////////////

	if($pageObject->lockingObj)
	{
		$enableCtrlsForEditing = $pageObject->lockingObj->LockRecord($strTableName,$keys);
		if(!$enableCtrlsForEditing)
		{
			if($inlineedit == EDIT_INLINE)
			{
				if(IsAdmin() || $_SESSION["AccessLevel"] == ACCESS_LEVEL_ADMINGROUP)
					$lockmessage = $pageObject->lockingObj->GetLockInfo($strTableName,$keys,false,$id);
				else
					$lockmessage = $pageObject->lockingObj->LockUser;
				$returnJSON['success'] = false;
				$returnJSON['message'] = $lockmessage;
				$returnJSON['enableCtrls'] = $enableCtrlsForEditing;
				$returnJSON['confirmTime'] = $pageObject->lockingObj->ConfirmTime;
				echo my_json_encode($returnJSON);
				exit();
			}
			
			$system_attrs = "style='display:block;'";
			$system_message = $pageObject->lockingObj->LockUser;
			
			if(IsAdmin() || $_SESSION["AccessLevel"] == ACCESS_LEVEL_ADMINGROUP)
			{
				$rb = $pageObject->lockingObj->GetLockInfo($strTableName,$keys,true,$id);
				if($rb!="")
					$system_message = $rb;
			}
		}
	}
}

if($pageObject->lockingObj && $inlineedit!=EDIT_INLINE)
	$pageObject->body["begin"] .='<div id="system_div'.$id.'" class="admin_message" '.$system_attrs.'>'.$system_message.'</div>';

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

// PRG rule, to avoid POSTDATA resend
if ($IsSaved && no_output_done() && $inlineedit == EDIT_SIMPLE)
{
	// saving message
	$_SESSION["message"] = ($message ? $message : "");
	// key get query
	$keyGetQ = "";
		$keyGetQ.="editid1=".rawurldecode($keys["idCL"])."&";
	// cut last &
	$keyGetQ = substr($keyGetQ, 0, strlen($keyGetQ)-1);	
	// redirect
	header("Location: Pending_Customers_".$pageObject->getPageType().".php?".$keyGetQ);
	// turned on output buffering, so we need to stop script
	exit();
}
// for PRG rule, to avoid POSTDATA resend. Saving mess in session
if ($inlineedit == EDIT_SIMPLE && isset($_SESSION["message"]))
{
	$message = $_SESSION["message"];
	unset($_SESSION["message"]);
}

/////////////////////////////////////////////////////////////
//	read current values from the database
/////////////////////////////////////////////////////////////
$query = $queryData_Pending_Customers->Copy();

$strWhereClause = KeyWhere($keys);
//	select only owned records
$strWhereClause = whereAdd($strWhereClause,SecuritySQL("Edit"));
$strSQL = gSQLWhere($strWhereClause);

$strSQLbak = $strSQL;
//	Before Query event
if($eventObj->exists("BeforeQueryEdit"))
	$eventObj->BeforeQueryEdit($strSQL, $strWhereClause);

if($strSQLbak == $strSQL)
	$strSQL = gSQLWhere($strWhereClause);
	
LogInfo($strSQL);

$rs = db_query($strSQL, $conn);
$data = db_fetch_array($rs);
if(!$data)
{
	if($inlineedit == EDIT_SIMPLE)
	{
		header("Location: Pending_Customers_list.php?a=return");
		exit();
	}
	else
		$data = array();
}

$readonlyfields = array();

  $readonlyfields["Customer Name"] = htmlspecialchars(GetData($data,"Customer Name", ""));
//if(!$data["Last Updated on"])
	$data["Last Updated on"] = Now();
//if(!$data["Assigned Executive"])
	$data["Assigned Executive"] = $_SESSION["UserID"];
//if(!$data["Assigned Date"])
	$data["Assigned Date"] = Now();

if($readevalues)
{
	$data["Address"] = $evalues["Address"];
	$data["City"] = $evalues["City"];
	$data["State"] = $evalues["State"];
	$data["Country"] = $evalues["Country"];
	$data["Postal Code"] = $evalues["Postal Code"];
	$data["Web address"] = $evalues["Web address"];
	$data["Area"] = $evalues["Area"];
	$data["Customer_Category"] = $evalues["Customer_Category"];
	$data["Breif About the Company"] = $evalues["Breif About the Company"];
	$data["Existing Setup"] = $evalues["Existing Setup"];
	$data["Interaction Summary"] = $evalues["Interaction Summary"];
	$data["Commercial Summary"] = $evalues["Commercial Summary"];
	$data["Customer Status"] = $evalues["Customer Status"];
	$data["Region"] = $evalues["Region"];
	$data["Last Updated on"] = $evalues["Last Updated on"];
	$data["Assigned Executive"] = $evalues["Assigned Executive"];
	$data["Assigned Date"] = $evalues["Assigned Date"];
}

if($eventObj->exists("ProcessValuesEdit"))
	$eventObj->ProcessValuesEdit($data);

/////////////////////////////////////////////////////////////
//	assign values to $xt class, prepare page for displaying
/////////////////////////////////////////////////////////////
//Basic includes js files
$includes = "";
//javascript code
	
if($inlineedit != EDIT_INLINE)
{
	if($inlineedit == EDIT_SIMPLE)
	{
		$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 language=\"JavaScript\" src=\"include/runnerJS/RunnerBase.js\"></script>\r\n";
			
		$includes.= "<script language=\"JavaScript\" src=\"include/jsfunctions.js\"></script>\r\n";
		$includes.= "<div id=\"search_suggest".$id."\"></div>\r\n";
		if($pageObject->isShowDetailTables)
			$includes.= "<div id=\"master_details\" onmouseover=\"RollDetailsLink.showPopup();\" onmouseout=\"RollDetailsLink.hidePopup();\"> </div>";
		$pageObject->body["begin"].= $includes;
	}	

	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("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(!$pageObject->isAppearOnTabs("Assigned Date"))
		$xt->assign("Assigned_Date_fieldblock",true);
	else
		$xt->assign("Assigned_Date_tabfieldblock",true);
	$xt->assign("Assigned_Date_label",true);
	if(isEnableSection508())
		$xt->assign_section("Assigned_Date_label","<label for=\"".GetInputElementId("Assigned Date", $id)."\">","</label>");
		

	$xt->assign("show_key1", htmlspecialchars(GetData($data,"idCL", "")));
	//$xt->assign('editForm',true);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Begin Next Prev button
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////    
	if(!@$_SESSION[$strTableName."_noNextPrev"] && $inlineedit == EDIT_SIMPLE)
	{
		$next = array();
		$prev = array();
		$pageObject->getNextPrevRecordKeys($data,"Edit",$next,$prev);
	}
	$nextlink = $prevlink = "";
	if(count($next))
	{
		$xt->assign("next_button",true);
				$nextlink.= "editid1=".htmlspecialchars(rawurlencode($next[1]));
		$xt->assign("nextbutton_attrs","id=\"nextButton".$id."\" align=\"absmiddle\"");
	}
	else 
		$xt->assign("next_button",false);
	if(count($prev))
	{
		$xt->assign("prev_button",true);
				$prevlink.= "editid1=".htmlspecialchars(rawurlencode($prev[1]));
		$xt->assign("prevbutton_attrs","id=\"prevButton".$id."\" align=\"absmiddle\"");
	}
	else 
		$xt->assign("prev_button",false);
	
	
	$xt->assign("resetbutton_attrs",'id="resetButton'.$id.'"');
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//End Next Prev button
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////    
	if($inlineedit == EDIT_SIMPLE)
	{
		$xt->assign("back_button",true);
		$xt->assign("backbutton_attrs","id=\"backButton".$id."\"");
	}
	// onmouseover event, for changing focus. Needed to proper submit form
	$onmouseover = "this.focus();";
	$onmouseover = 'onmouseover="'.$onmouseover.'"';
	
	$xt->assign("save_button",true);
	if(!$enableCtrlsForEditing)
		$xt->assign("savebutton_attrs", "id=\"saveButton".$id."\" disabled=\"true\" style='background-color:#dcdcdc' ".$onmouseover);
	else
		$xt->assign("savebutton_attrs", "id=\"saveButton".$id."\"".$onmouseover);
		
	$xt->assign("reset_button",true);
}

if($message)
{
	$xt->assign("message_block",true);
	$xt->assign("message",$message);
}
/////////////////////////////////////////////////////////////
//process readonly and auto-update fields
/////////////////////////////////////////////////////////////

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

foreach($editFields as $fName)
{
	$gfName = GoodFieldName($fName);
	$controls = array('controls'=>array());
	if (!$detailKeys || !in_array($fName, $detailKeys))
	{		
		$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"] = @$data[$fName];
		
		//	Begin Add validation
		$arrValidate = getValidation($fName,$strTableName);	
		$control[$gfName]["params"]["validate"] = $arrValidate;
		//	End Add validation	
		$additionalCtrlParams = array();
		$additionalCtrlParams["disabled"] = !$enableCtrlsForEditing;
		$control[$gfName]["params"]["additionalCtrlParams"] = $additionalCtrlParams;
	}
	$controls["controls"]['ctrlInd'] = 0;
	$controls["controls"]['id'] = $id;
	$controls["controls"]['fieldName'] = $fName;
	
	if($inlineedit == EDIT_INLINE)
	{
		if(!$detailKeys || !in_array($fName, $detailKeys))
			$control[$gfName]["params"]["mode"]="inline_edit";
		$controls["controls"]['mode'] = "inline_edit";
	}
	else{
			if (!$detailKeys || !in_array($fName, $detailKeys))
				$control[$gfName]["params"]["mode"] = "edit";
			$controls["controls"]['mode'] = "edit";
		}
                                                                	if(UseRTE("Last Updated on") && $fName == "Last Updated on")
	{
		$_SESSION[$strTableName."_"."Last Updated on"."_rte"] = Now();
		$control[$gfName]["params"]["mode"] = "add";
	}
    	if(UseRTE("Assigned Executive") && $fName == "Assigned Executive")
	{
		$_SESSION[$strTableName."_"."Assigned Executive"."_rte"] = $_SESSION["UserID"];
		$control[$gfName]["params"]["mode"] = "add";
	}
    	if(UseRTE("Assigned Date") && $fName == "Assigned Date")
	{
		$_SESSION[$strTableName."_"."Assigned Date"."_rte"] = Now();
		$control[$gfName]["params"]["mode"] = "add";
	}
	
	if(!$detailKeys || !in_array($fName, $detailKeys))
		$xt->assignbyref($gfName."_editcontrol",$control[$gfName]);
	elseif($detailKeys && in_array($fName, $detailKeys))
		$controls["controls"]['value'] = @$data[$fName];
		
	// category control field
	$strCategoryControl = $pageObject->hasDependField($fName);
	
	if($strCategoryControl!==false && in_array($strCategoryControl, $editFields))
		$vals = array($fName => @$data[$fName],$strCategoryControl => @$data[$strCategoryControl]);
	else
		$vals = array($fName => @$data[$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, $data[$fName]);
	
	if(ViewFormat($fName) == FORMAT_MAP)	
		$pageObject->googleMapCfg['isUseGoogleMap'] = true;
		
	if($detailKeys && in_array($fName, $detailKeys) && array_key_exists($fName, $data))
	{
		if((GetEditFormat($fName)==EDIT_FORMAT_LOOKUP_WIZARD || GetEditFormat($fName)==EDIT_FORMAT_RADIO) && GetpLookupType($fName) == LT_LOOKUPTABLE)
			$value=DisplayLookupWizard($fName,$data[$fName],$data,"",MODE_VIEW);
		elseif(NeedEncode($fName))
			$value = ProcessLargeText(GetData($data,$fName, ViewFormat($fName)),"field=".rawurlencode(htmlspecialchars($fName)),"",MODE_VIEW);
		else
			$value = GetData($data,$fName, ViewFormat($fName));
		
		$xt->assign($gfName."_editcontrol",$value);
	}
}
//fill tab groups name and sections name to controls
$pageObject->fillCntrlTabGroups();
			
$pageObject->jsSettings['tableSettings'][$strTableName]["keys"] = $keys;
$pageObject->jsSettings['tableSettings'][$strTableName]["prevKeys"] = $prev;
$pageObject->jsSettings['tableSettings'][$strTableName]["nextKeys"] = $next; 
if($pageObject->lockingObj)
{
	$pageObject->jsSettings['tableSettings'][$strTableName]["sKeys"] = $skeys;
	$pageObject->jsSettings['tableSettings'][$strTableName]["enableCtrls"] = $enableCtrlsForEditing;
	$pageObject->jsSettings['tableSettings'][$strTableName]["confirmTime"] = $pageObject->lockingObj->ConfirmTime;
}
//fill jsSettings and ControlsHTMLMap
$pageObject->fillSetCntrlMaps();

/////////////////////////////////////////////////////////////
if($pageObject->isShowDetailTables && $inlineedit!=EDIT_INLINE)
{
	$options = array();
	//array of params for classes
	$options["mode"] = LIST_DETAILS;
	$options["pageType"] = PAGE_LIST;
	$options["masterPageType"] = PAGE_EDIT;
	$options["mainMasterPageType"] = PAGE_EDIT;
	$options['masterTable'] = $strTableName;
	$options['firstTime'] = 1;
	
	if(count($dpParams['ids']))
	{
		include('classes/listpage.php');
		include('classes/listpage_embed.php');
		include('classes/listpage_dpinline.php');
		$xt->assign("detail_tables",true);	
	}
	
	$dControlsMap = array();
	
	$flyId = $ids+1;
	for($d=0;$d<count($dpParams['ids']);$d++)
	{
		$strTableName = $dpParams['strTableNames'][$d];
		include("include/".GetTableURL($strTableName)."_settings.php");
		if(!CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Search"))
		{
			$strTableName = "Pending Customers";		
			continue;
		}
		$options['xt'] = new Xtempl();
		$options['id'] = $dpParams['ids'][$d];
		$options['flyId'] = $flyId++;
		$mkr=1;
		foreach($mKeys[$strTableName] as $mk)
			$options['masterKeysReq'][$mkr++] = $data[$mk];

		$listPageObject = ListPage::createListPage($strTableName, $options);
		// prepare code
		$listPageObject->prepareForBuildPage();
		$flyId = $listPageObject->recId+1;
		// show page
		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 = "Pending Customers";
	$pageObject->controlsHTMLMap[$strTableName][PAGE_EDIT][$id]['dControlsMap'] = $dControlsMap;	
}
/////////////////////////////////////////////////////////////	

if($inlineedit == EDIT_SIMPLE)
{
	$pageObject->jsSettings["global"]['idStartFrom'] =  $flyId + 1;
	$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($inlineedit==EDIT_SIMPLE)
{
	$pageObject->body["end"].= "<script>".$jscode."</script>";
	$xt->assign("body",$pageObject->body);
	$xt->assign("flybody",true);	
}
elseif($inlineedit==EDIT_POPUP){
		$xt->assign("footer","");
		$xt->assign("flybody",$pageObject->body);
		$xt->assign("body",true);
	}
	
$xt->assign("style_block",true);
$pageObject->xt->assign("legend", true);



/////////////////////////////////////////////////////////////
//display the page
/////////////////////////////////////////////////////////////
if($eventObj->exists("BeforeShowEdit"))
	$eventObj->BeforeShowEdit($xt,$templatefile,$data);
if($inlineedit==EDIT_POPUP)
{
	$xt->load_template($templatefile);
	$returnJSON['html'] = $xt->fetch_loaded('style_block').$xt->fetch_loaded('flybody');
	if($pageObject->isShowDetailTables)
		$returnJSON['html'].= $xt->fetch_loaded('detail_tables');
	$returnJSON['idStartFrom'] = $flyId + 1;
	echo (my_json_encode($returnJSON)); 
}
elseif($inlineedit == EDIT_INLINE)
{
	$xt->load_template($templatefile);
	$returnJSON["html"] = array();
	foreach($editFields as $fName)
	{
		if($detailKeys && in_array($fName, $detailKeys))
			continue;
		$returnJSON["html"][$fName] = $xt->fetchVar(GoodFieldName($fName)."_editcontrol");	
	}
	
	echo (my_json_encode($returnJSON)); 
}
else	
	$xt->display($templatefile);

?>
