<?php
	set_time_limit(0);
	define("LOC_SENDER", "sLOC21");
	define("LOC_RECIPIENT", "sLOC22");
	define('XMPIE_AGGREGATION_PATH', 'E:\\XMPie\\uStore\\App\\CustomerApp\\uStoreShared\\JobAggregation\\MasterAggregation\\');
	
	class uProduce
	{		
			/**
			* 
			*********************************************************************************/	
			public static function csv_to_array($filename='', $delimiter=',', $enclosure='"'){
				if(!file_exists($filename) || !is_readable($filename))
					return FALSE;
			
				$header = NULL;
				$data = array();
				if (($handle = fopen($filename, 'r')) !== FALSE)
				{
					while (($row = fgetcsv($handle, 0, $delimiter, $enclosure)) !== FALSE)
					{
						if(!$header)
							$header = $row;
						else
							$data[] = array_combine($header, $row);
					}
					fclose($handle);
				}
				return $data;
			}
			
			/**
			*
			*********************************************************************************/
			private static function SaveNewRecipientListFile($JobGroupId=0, $arrayCodeExtraData=array())
			{
				$Us2JobGroup 		= Us2JobGroupPeer::retrieveByPk($JobGroupId);
				$RecipientCsvFile	= $Us2JobGroup->getRecipientCsvFile();
				$arrayData 			= self::csv_to_array($RecipientCsvFile, $delimiter=',', $enclosure='"');
				$arrayFields		= array();
				
				foreach($arrayData[0] as $keyName => $keyValue) {
					$arrayFields[$keyName] = $keyName;
				}
				
				foreach($arrayCodeExtraData as $code => $arrayFieldValue)
				{
					foreach($arrayFieldValue as $field => $value)
						$arrayFields[$field] = $field;
				}
				
				
				$text = join(",", $arrayFields). "\r\n";
				
				foreach($arrayData as $i => $arrayFieldValue)
				{
					foreach($arrayFields as $fieldName)
					{
						$val	= $arrayFieldValue[$fieldName];
						if(!$val) {
							$code 	= $arrayFieldValue['CODE'];
							$val	= $arrayCodeExtraData[$code][$fieldName];
						}
						
						$text .= "\"$val\",";
					}
					$text = substr($text, 0, strlen($text)-1);
					$text .= "\r\n";
				}
				
				#echo $text; die("**********");
				$filename = "/var/www/web3/web/aggregation/jobgroup2/$JobGroupId/recipient_2.csv";
				$fh = fopen($filename, 'w');
				fwrite($fh, $text);
				fclose($fh);
				
				$Us2JobGroup->setRecipientCsvFile($filename);
				$Us2JobGroup->save();
				
				#	$woNumber				= $Us2JobGroup->getWoNumber();			
				#	$createMailingRecord 	= true;
				#	$mailDate 				= date('n/d/y');						
			}
			
						
			/**
			* Get PDF Proof Location
			*********************************************************************************/
			public static function GetProofLocation ($JobId=0)
			{
				if (!$JobId) return array();

				$Status = self::GetJobStatus ($JobId);
				
				switch ($Status)
				{
					case '1':	$StatusId=1;	$Message = 'Queued, please wait...';		break;
					case '2':	$StatusId=2;	$Message = 'In progress, please wait...'; 	break;
					case '3':
						$$StatusId=3;
						$Message = 'Done';
						$Path = self::GetFolderPath ($JobId);$Files = self::GetOutputResult ($JobId);
									
						foreach ($Files as $File)
						{
							$HTML.= "<img src=\"$Path$File\"><p><br>";
						}
						$PDFLocation = "$Path$Files";
					break;
					default:
						$StatusId=4;
						$Message = 'Failed, please try again...';
					break;
				}
				
				return array(
					'StatusId'		=> $StatusId,
					'Message'		=> $Message,
					'PdfLocation'	=> $PDFLocation,
				);
			}
			
			/**
			* Get font list by campaign
			*********************************************************************************/
			public static function GetFonts($inCampaignID=0)
			{
				if (!$inCampaignID) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Campaign_objects.php");
				$CCampaign = new Xmpie_uProduceCampaign();

				$CCampaign->GetFontsDataSet($inCampaignID);

				
				$xml 	= $CCampaign->result->any;
				$fonts 	= array();

				try {
					$xml = new SimpleXMLElement($xml);

					foreach($xml->NewDataSet->Table as $font)
					{
						$fonts[] = array(
							'name'		=> "$font->fontName",
							'filename'	=> "$font->fontFile",
							'family'	=> "$font->fontFamily",
							'face'		=> "$font->fontFace",
						);
					}

				} catch (Exception $Error){}
						
						return $fonts;
			}

			/**
			* Get All Job Properties
			*********************************************************************************/
			public static function GetAllProperties ($JobId=0)
			{
				if (!$JobId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Job_objects.php");
				$CJob = new Xmpie_uProduceJob();

				$CJob->GetAllProperties($JobId);
				#print_r($CJob);
				return $Status = $CJob->result;
			}
			/**
			* Get job Message data set
			*********************************************************************************/
			public static function GetMessagesDataSet ($JobId=0)
			{
				if (!$JobId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Job_objects.php");
				$CJob = new Xmpie_uProduceJob();

				$CJob->GetMessagesDataSet($JobId);
				print_r($CJob);
				return $Status = $CJob->result;
			}			
			/**
			* Delete Job 
			*********************************************************************************/
			public static function Delete ($JobId=0)
			{
				if (!$JobId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Job_objects.php");
				$CJob = new Xmpie_uProduceJob();

				$CJob->Delete($JobId);
				return $Status = $CJob->result;
			}
			/**
			* Delete Job messages
			*********************************************************************************/
			public static function DeleteMessages ($JobId=0)
			{
				if (!$JobId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Job_objects.php");
				$CJob = new Xmpie_uProduceJob();

				$CJob->DeleteMessages($JobId);
				return $Status = $CJob->result;
			}
									
			/**
			* Get Job Messages
			*********************************************************************************/
			public static function GetJobMessages ($JobId=0)
			{
				if (!$JobId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Job_objects.php");
				$CJob = new Xmpie_uProduceJob();

				$CJob->GetDataSet($JobId);
				print_r($CJob);
				return $Status = $CJob->result;
			}
			
			/**
			* Get ALL Document Properties
			*********************************************************************************/
			public static function GetAllDocumentProperties ($uProduceDocId=0)
			{
				if (!$uProduceDocId) return false;
				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Document_objects.php");
				$CDocument = new Xmpie_uProduceDocument();

				$CDocument->GetAllProperties($uProduceDocId);
				return $CDocument->properties;
			}
				
			/**
			* Get Document Property
			*********************************************************************************/
			public static function GetDocumentProperties ($uProduceDocId=0, $inPropertyName='')
			{
				if (!$uProduceDocId) return false;
				if (! is_array($inPropertyName))
					$inPropertyName = array($inPropertyName);

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Document_objects.php");
				$CDocument = new Xmpie_uProduceDocument();

				//echo "<!--- Debug: inPropertyName = " . print_r($inPropertyName, true) . "--><br />";
				$CDocument->GetProperties($uProduceDocId, $inPropertyName);
				//echo "<!--- Debug: " . $CDocument->Dump(true) . "-->";
				return $CDocument->properties;
			}
	
			/**
			* Get Output Folder Path
			*********************************************************************************/
			public static function GetFolderPath ($JobId=0)
			{
				if (!$JobId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Job_objects.php");
				$CJob = new Xmpie_uProduceJob();

				$CJob->GetFolderPath($JobId);
				
				$Path = $CJob->properties['folderPath'];
				$Path = str_ireplace ("\\\\TINMAN\Xmpie\\XMPiEOutput\\", "http://img.printhd.us/proof/", $Path);
				$Path = str_ireplace ("\\\\gazoo\\", "http://img2.printhd.us/", $Path);
				$Path = str_ireplace ("\\\\thing1\\", "http://img6.printhd.us/", $Path);					
				$Path = str_ireplace ("\\", "/", $Path);
				
				return $Path;
			}
			
			/**
			* Get Output Result
			*********************************************************************************/
			public static function GetOutputResult ($JobId=0)
			{
				if (!$JobId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Job_objects.php");
				$CJob = new Xmpie_uProduceJob();

				$CJob->GetOutputResults($JobId);
				return $File = $CJob->properties['outputResult'];
			}
			
				
			/**
			* Get Job Status
			*********************************************************************************/
			public static function GetJobStatus ($JobId=0)
			{
				if (!$JobId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Job_objects.php");
				$CJob = new Xmpie_uProduceJob();

				$CJob->GetStatus($JobId);
				return $Status = $CJob->properties['jobStatus'];
			}

			public static function GetGazooJobStatus($JobId=0)
			{
				if (!$JobId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_gazoo_job_object.php");
				$CJob = new Xmpie_uProduceJob();

				$CJob->GetStatus($JobId);
				return $Status = $CJob->properties['jobStatus'];
			}
	
			/**
			* Proof Document
			*********************************************************************************/
			public static function Proof ($uProduceDocId=0, $OutputType='PDFO', $Customization=array())
			{
				if (!$uProduceDocId) return false;

				define('_VALID_RBS', 1);
				
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Document_objects.php");
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_JobTicket_objects.php");
				require_once(SF_ROOT_DIR . "/xmpie/class.xmpie_Production_objects.php");

				$CDocument			= new Xmpie_uProduceDocument();
				$CJobTicket			= new Xmpie_uProduceJobTicket();
				$CProduction		= new Xmpie_uProduceProduction();
		
		

				/*``
				` Get the name of the uProduce document
				```````````````````````````````````````````````````````````````````````*/
				if (! $CDocument->GetName ($uProduceDocId)) return false;
				$DocumentName = $CDocument->result;
	

				/*``
				` Create a new job ticket for this document.
				```````````````````````````````````````````````````````````````````````*/
				$Result = $CJobTicket->CreateNewTicketForDocument($uProduceDocId, "", false);
				if (!$Result) return false;
				
	
				/*``
				` IMPORTANT! Set the UseTrivialPlan property.
				```````````````````````````````````````````````````````````````````````*/
				if(Us2SheetSpecsPeer::UseTrivialPlan($uProduceDocId)) {
					#$CJobTicket->GetUseTrivialPlan( $CJobTicket->jobticket_id);
					#$UseTrivialPlan = $CJobTicket->result;
					
					#$CJobTicket->GetOutputType  ($CJobTicket->jobticket_id);
					#$OutputType = $CJobTicket->result;
					
					$CJobTicket->SetUseTrivialPlan( $CJobTicket->jobticket_id,  true);
				}
				else
					$CJobTicket->SetUseTrivialPlan( $CJobTicket->jobticket_id,  false);				


				/*``
				` Set job output info
				```````````````````````````````````````````````````````````````````````*/
				$OutputFilename = str_replace(array(' ', '.'), '_', $DocumentName) . time();
				
				$ValidOutput = array('PROOF_SET','VPS','PDF','PDFO','PPML','VDX','VIPP','JPG','PS');
				
				if (! in_array($OutputType, $ValidOutput) ) $OutputType = 'PDF';
				
				if ($OutputType =='JPG')
				{
					$MediaType = 2; #WEB
					$OutputParams = array(
						array('m_Name' => 'JPG_RES', 'm_Value'=> 100),
						);					
				}
				elseif ($OutputType =='PDF' || $OutputType =='PDFO')
				{
					$OutputType = 'PDF';
					#$OutputType = 'PROOF_SET';
					$MediaType = 2; #EMAIL , 1 = print
					$OutputParams = array(
						array('m_Name' => 'JPG_RES', 'm_Value'=> 100),
						#array('m_Name' => 'NATIVE_PDF_OPTIONS', 'm_Value'=> "xmpiequalityproof"),
						#array('m_Name' => 'NATIVE_PDF_OPTIONS', 'm_Value'=> "XMPIEQualityProof"),
						array('m_Name' => 'NATIVE_PDF_OPTIONS', 'm_Value'=> "XMPiEWebProof"),
						);					
				}
				else
				{
					$MediaType = 2; #PRINT
					$OutputParams = array();
				}
					#die("$MediaType");
				#die("--");
				//if (! $CJobTicket->SetDistillJobOptionName($CJobTicket->jobticket_id, "PROOF") ) return false;
				if (! $CJobTicket->SetOutputInfo($CJobTicket->jobticket_id, $OutputType, $MediaType, "", "$OutputFilename", $OutputParams ) ) return false;
				if (! $CJobTicket->SetOutputMedia($CJobTicket->jobticket_id, 2/*web*/) ) return false;
				if (! $CJobTicket->SetJobType($CJobTicket->jobticket_id, "PROOF") ) return false;
				#if (! $CJobTicket->RemoveAllSchemaDataSources($CJobTicket->jobticket_id) ) return false;



				
//				/*``
//				` Set job recipient list
//				```````````````````````````````````````````````````````````````````````*/
//				$Pathinfo	= pathinfo($File);
//				$Path		= $Pathinfo['dirname'];
//				$Basename	= $Pathinfo['basename'];
//		
//				$RecipientsInfo = array(
//					'm_From'=>'-1',
//					'm_To'=>'-1',
//					'm_Filter'=> str_replace('.', '#', $Basename),
//					'm_FilterType'=>'3' #TABLE							
//				);
//								
//				$Connection = array(
//					'm_AdditionalInfo'=>"$Basename@,@,", #FILENAME
//					'm_ConnectionString'=>"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=$Path;Extended Properties=text;",
//					'm_Type'=>'TXT'
//				);
//		
//				if (! $CJobTicket->SetRI ($CJobTicket->jobticket_id, $RecipientsInfo, $Connection)) return false;
//								
//									
//				/*``
//				` Set job recipient list range
//				```````````````````````````````````````````````````````````````````````*/	
//				if (! $CJobTicket->SetRIRange($CJobTicket->jobticket_id, '1', '-1')) return false;
		
				/*``
				` Set Customization
				```````````````````````````````````````````````````````````````````````*/
				$CustomizationArray = array();
				
				foreach ($Customization as $DialName => $DialValue)
				{
					$CustomizationArray[] = array(
						'm_Name'=>"$DialName",
						'm_IOType'=>"R",
						'm_Type'=>"ADOR",
						'm_Expression'=>"$DialValue"
					);
				}
				#print_r($CustomizationArray); exit;
				if (! $CJobTicket->SetCustomizations($CJobTicket->jobticket_id, $CustomizationArray, true)) return false;
						
				/*``
				` Submit job for production
				```````````````````````````````````````````````````````````````````````*/
				if (! $CProduction->SubmitJob($CJobTicket->jobticket_id, 0)) return false;
	
				# Return JobId
				return $CProduction->result;
				#return true;
			}
			
		
			/**
			* Send To Production
			*********************************************************************************/
			public static function SendToProduction ($uProduceDocId=0, $File='', $OutputType='VPS', $OutputName='', $inCopyDestination='', $isTestOnly=false)
			{
				$UseTrivialPlan = Us2SheetSpecsPeer::UseTrivialPlan($uProduceDocId);
				$SheetSpecs		= json_encode(unserialize(Us2SheetSpecsPeer::GetData($uProduceDocId)));

				$arrayPost = array(
					'key'				=> '10OYwla0238JKasd897123jkaDALPQAv',
					'action'			=> 'SubmitJob',
					'uProduceDocId'		=> $uProduceDocId,
					'File'				=> $File,
					'OutputType'		=> $OutputType,
					'OutputName'		=> $OutputName,
					'inCopyDestination'	=> $inCopyDestination,
					'UseTrivialPlan'	=> $UseTrivialPlan,
					'SheetSpecs'		=> $SheetSpecs,
					'isTestOnly'		=> $isTestOnly
				);

				$Curl = curl_init();
				curl_setopt($Curl, CURLOPT_URL, "http://img4.printhd.us/service/xmpie.php");
				curl_setopt($Curl, CURLOPT_POST, 8);
				curl_setopt($Curl, CURLOPT_POSTFIELDS, $arrayPost);
				curl_setopt($Curl, CURLOPT_BINARYTRANSFER, 1);
				curl_setopt($Curl, CURLOPT_RETURNTRANSFER, 1); 
				curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 0); 
				curl_setopt($Curl, CURLOPT_TIMEOUT, 1200); # 20 minutes 
				$Result = curl_exec($Curl);
				curl_close($Curl);

				
				try { $response = json_decode($Result, true); } catch(Exception $e){ }
				
				if(! is_array($response) || $response['success']==false || !$response['job_id']) 
				{
					return false;
				}

				return $response['job_id'];
			}


			/**
			* Send file to uProduce server 07/30/2010
			*********************************************************************************/
			public static function SendFile2_NEW ($From)
			{
					ini_set("memory_limit", "3072M");
					ini_set("upload_max_filesize", "1024M");
					ini_set("post_max_size", "1024M");
								
					$bytesToSend 	= 100000; 	# send 100kb at a time
					$chunk			= 0;		# current part
					$totalChunk		= 0;		# total parts
					
					/******************************************************/
					/* Send this file to the uProduct shared asset folder */
					#$SaveToPath = 'E:\\XMPie\\uStore\\App\\CustomerApp\\uStoreShared\\JobAggregation\\MasterAggregation\\';
					$SaveToPath = XMPIE_AGGREGATION_PATH;
					$pathinfo 	= pathinfo($From);
					$filename 	= $pathinfo['filename'];
			
					/**`````````````````````````````````````````````````````````````````````````**/
					/* Base64 encode this file so we can transport it over soap as a string  */				
					$Handle	= fopen ($From, 'r');
					if (!$Handle) { echo "Internal System Error, please try again."; exit; }
							
					$Data = fread($Handle, filesize($From));
					fclose($Handle);
						

					$arrayChunk 	= str_split($Data, $bytesToSend);
					$totalChunk		= count($arrayChunk);
					
					/**`````````````````````````````````````````````````````````````````````````**/
					/* Transfer each chunk one at a time  */	
					foreach($arrayChunk as $i => $chunkData)
					{
							$arrayPost = array(
								'EntryKey'		=> '10OYwla0238JKasd897123jkaDALPQAv',
								'SaveToPath'	=> $SaveToPath,
								'FileName'		=> $filename .'.'. $pathinfo['extension'],
								'Data'			=> $chunkData,
								'Chunk'			=> $i,
								'TotalChunk'	=> $totalChunk
							);
		
							$Curl = curl_init();
							curl_setopt($Curl, CURLOPT_URL, "http://71.99.204.144:8080/postdata.php");
							curl_setopt($Curl, CURLOPT_POST, 6);
							curl_setopt($Curl, CURLOPT_POSTFIELDS, $arrayPost);
							curl_setopt($Curl, CURLOPT_BINARYTRANSFER, 1);
							curl_setopt($Curl, CURLOPT_RETURNTRANSFER, 1); 
							curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 0); 
							curl_setopt($Curl, CURLOPT_TIMEOUT, 1200); # 20 minutes 
							$Result = curl_exec($Curl);
							curl_close($Curl);						

							if($Result!="1") { echo "Result => $Result <p>". 'Internal System Error: Unable to save uploaded file into server. Missing parts.'; exit; }
					}



					if($Result!="1") { echo "Result => $Result <p>". 'Internal System Error: Unable to save uploaded file into server.'; exit; }
			}	
			
			

			/**
			* Send file to uProduce server 07/30/2010
			*********************************************************************************/
			public static function SendFile2 ($From, $halt=true)
			{
					ini_set("memory_limit", "3072M");
					ini_set("upload_max_filesize", "1024M");
					ini_set("post_max_size", "1024M");
								
								
					/******************************************************/
					/* Send this file to the uProduct shared asset folder */
					$SaveToPath = XMPIE_AGGREGATION_PATH;
					$pathinfo 	= pathinfo($From);
					$filename 	= $pathinfo['filename'];
			
					/**`````````````````````````````````````````````````````````````````````````**/
					/* Base64 encode this file so we can transport it over soap as a string  */				
					$Handle	= fopen ($From, 'r');
					if (!$Handle) { echo "Internal System Error, please try again."; exit; }
							
					$Data = fread ($Handle, filesize($From));
					fclose($Handle);
				
					$arrayPost = array(
						'key'			=> '10OYwla0238JKasd897123jkaDALPQAv',
						'action'		=> 'upload',
						'SaveToPath'	=> $SaveToPath,
						'FileName'		=> $filename .'.'. $pathinfo['extension'],
						'Data'			=> $Data
					);
					

					$Curl = curl_init();
					curl_setopt($Curl, CURLOPT_URL, "http://img4.printhd.us/service/assets.php");
					curl_setopt($Curl, CURLOPT_POST, 4);
					curl_setopt($Curl, CURLOPT_POSTFIELDS, $arrayPost);
					curl_setopt($Curl, CURLOPT_BINARYTRANSFER, 1);
					curl_setopt($Curl, CURLOPT_RETURNTRANSFER, 1); 
					curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 0); 
					curl_setopt($Curl, CURLOPT_TIMEOUT, 1200); # 20 minutes 
					$Result = curl_exec($Curl);
					curl_close($Curl);
					
					try { $response = json_decode($Result, true); } catch(Exception $e){ echo "exception error: <pre>" . print_r($e, true) . "</pre><br />"; }
					
					if(! is_array($response) || $response['success']==false) 
					{
						if($halt) { echo 'lib/uProduce.class.php::SendFile2() Internal System Error: Unable to save uploaded file into server. #2<br /><pre>post vars = ' . print_r($arrayPost, true) . "</pre><br /><pre>response=" . print_r($response, true) . "</pre>"; exit; }
						else return false;
					}


					return true;
			}
			
			
			/**
			* Send file to uProduce server
			*********************************************************************************/
			public static function SendFile ($From)
			{
					/******************************************************/
					/* Send this file to the uProduct shared asset folder */
					require_once (SF_ROOT_DIR. '/apps/webservices/amms/includes/inc.config.php');
					require_once (SF_ROOT_DIR. '/apps/webservices/amms/includes/class.variables.php');
			
					# Set up the wsdl soap client.
					$Client = new SoapClient ("http://img2.printhd.us/ustore/webservices/wsdl/ammsinternal.wsdl", $Options);
			
					#$Path = 'E:\\XMPie\\uStore\\App\\CustomerApp\\uStoreShared\\JobAggregation\\MasterAggregation\\';
					$Path = XMPIE_AGGREGATION_PATH;
					#$Path = 'E:\\XMPie\\uStore\\JobAggregation\\';
					
					$pathinfo = pathinfo ($From);
					$filename = $pathinfo['filename'];
			
					
						/******************************************************/
						/* Base64 encode this file so we can transport it over
						/* soap as a string  */				
						$Handle	= fopen ($From, 'r');
						
						if (!$Handle)
							{ echo "Internal System Error, please try again."; exit; }
							
						$Data	= fread ($Handle, filesize($From));
						fclose ($Handle);
						
						
						$Input = new SaveProgramImage();
						$Input->FileName	= $filename;
						$Input->FileSize 	= '';
						$Input->FileBase64 	= base64_encode($Data);
						$Input->FileExt		= $pathinfo['extension'];
						$Input->SaveToPath	= $Path;
						$Response = $Client->SaveProgramImage ($Input);	
						if ($Response->Code != 'SUCCESS') { echo 'Internal System Error: Unable to save uploaded file into server.'; exit; }

			}


			/**
			* Private Function: CreateuProduceCsvFile()
			*********************************************************************************/
			public static function CreateuProduceCsvFile($JobGroupId, $RecipientCsvFile, $recordLimit=999999, $blankRecord=0, $arrayOrderProductGroupName=array(), $mailDate)
			{	
				set_time_limit(0);	
					$arrayCustomerOverrideDialValue = array();
					# Triggermail :: Executive Jeep Nissan
					$arrayCustomerOverrideDialValue[3385] = array(
						'JEEP' 		=> 'jeep',
						'NISSAN' 	=> 'nissan'
					);
					$arrayCustomerOverrideDialValue[4042] = array(
						'JEEP' 		=> 'jeep',
						'DODGE' 	=> 'dodge'
					);
					
					$arrayBogusVehicleMake= array(
						'vehicle', 'unknown'
					);
					
//					$testString = '2007 Vehicle 4RUNNER';
//					$testString = str_ireplace($arrayBogusVehicleMake, '', $testString);
//					echo $testString; exit;
					
					
					define( '_VALID_RBS', '1' );
					include ("/var/www/web3/classes/config.inc.php");				
					require_once ("/var/www/web3/classes/class.nameserver_objects.php");
					
					$database 		= new database($sSQLServer, $sSQLUser, $sSQLPass, $sSQLDatabase );
					$CNameMaster 	= new NameMaster($database);
					
						"/var/www/web3/classes/config.inc.php")				
					# Open the data file to read in the csv data.
					$file = fopen($RecipientCsvFile, 'r') or die("Can't open csv file: $RecipientCsvFile  \n\n");
				
					# Extract the CSV data file content.
					$data = array();
					while (!feof($file)) array_push($data, fgetcsv($file, 4096));
		
		
		
					# Get Indexes
					$KEY_INDEX		= array_search('INDEX',		$data[0]);
					$KEY_CODE		= array_search('CODE',		$data[0]);
					$KEY_FIRSTNAME	= array_search('FIRSTNAME',	$data[0]);
					$KEY_LASTNAME	= array_search('LASTNAME',	$data[0]);
					$KEY_FULLNAME	= array_search('FULLNAME',	$data[0]);
					$KEY_ADDRESS	= array_search('ADDRESS',	$data[0]);
					$KEY_CITY		= array_search('CITY',		$data[0]);
					$KEY_STATE		= array_search('STATE',		$data[0]);
					$KEY_ZIP		= array_search('ZIP',		$data[0]);
					$KEY_BARCODE	= array_search('BARCODE',	$data[0]);
					$KEY_ENDORSE	= array_search('ENDORSE',	$data[0]);
					$KEY_NAMEMASTER	= array_search('NAMEMASTER',$data[0]);
					$KEY_MATCHCODE	= array_search('MATCHCODE',	$data[0]);
					$KEY_SEQ		= array_search('SEQ',		$data[0]);
					$KEY_PURLNAME	= array_search('PURLNAME',	$data[0]);
					$KEY_PURLCODE	= array_search('PURLCODE',	$data[0]);
					
												
					if ($KEY_INDEX===false)		{ die("Recipient list csv file doesn't have the INDEX field, can't process file."); }
					if ($KEY_CODE===false) 		{ die("Recipient list csv file doesn't have the CODE field, can't process file."); }
					if ($KEY_FIRSTNAME===false) { die("Recipient list csv file doesn't have the FIRSTNAME field, can't process file."); }
					if ($KEY_LASTNAME===false)	{ die("Recipient list csv file doesn't have the LASTNAME field, can't process file."); }
					if ($KEY_FULLNAME===false)	{ die("Recipient list csv file doesn't have the FULLNAME field, can't process file."); }
					if ($KEY_ADDRESS===false)	{ die("Recipient list csv file doesn't have the ADDRESS field, can't process file."); }
					if ($KEY_CITY===false)		{ die("Recipient list csv file doesn't have the CITY field, can't process file."); }
					if ($KEY_STATE===false) 	{ die("Recipient list csv file doesn't have the STATE field, can't process file."); }
					if ($KEY_ZIP===false) 		{ die("Recipient list csv file doesn't have the ZIP field, can't process file."); }
					if ($KEY_BARCODE===false) 	{ die("Recipient list csv file doesn't have the BARCODE field, can't process file."); }
					if ($KEY_ENDORSE===false) 	{ die("Recipient list csv file doesn't have the ENDORSE field, can't process file."); }
		
		
		
					# Use memory caching to store data that already loaded from the 
					# database so we dont have to reload it again.
					$Cached 	= array();
					$Headers	= array('RI_PrimaryField'=>1);
			
			
					$UPRODUCE_DOC_ID = NULL;

					# For every record, add csv data row.
					for ($i=1; $i<count($data); $i++)
					{
							if ($i > $recordLimit) break;
			
							$Index		= $data[$i][$KEY_INDEX];
							$Code		= $data[$i][$KEY_CODE];
							//$FirstName	= $data[$i][$KEY_FIRSTNAME];
							//$LastName	= $data[$i][$KEY_LASTNAME];
							//$FullName	= $data[$i][$KEY_FULLNAME];
							//$Address	= $data[$i][$KEY_ADDRESS];
							//$City		= $data[$i][$KEY_CITY];
							//$State		= $data[$i][$KEY_STATE];
							//$Zip		= $data[$i][$KEY_ZIP];
							//$Barcode	= $data[$i][$KEY_BARCODE];
							//$Endorse	= $data[$i][$KEY_ENDORSE];
							//$Seq		= $data[$i][$KEY_SEQ];
							
				
							# Explode the code, [0] contains order product id, [1] contains list data id
							# for the associcated recipient.
							$Code = explode('-', $Code);
							
							# Code contains the OrderProductId
							$OrderProductId = $Code[0];
							if (! $OrderProductId) continue;

							# If this order product item is not yet loaded from the database
							# then load it's associated data and cache it.
							if (! in_array($OrderProductId, $Cached['OrderProductId']) )
							{
								$Cached['OrderProductId'][] = $OrderProductId;

								$ProductId			= Us2OrderProductPeer::GetProductId ($OrderProductId);
								$ProductTemplateId	= Us2ProductPeer::GetProductTemplateId ($ProductId);
								$CustomerId			= Us2OrderProductPeer::GetCustomerId ($OrderProductId);
								$uProduceDocId		= Us2ProductTemplatePeer::GetuProduceDocId ($ProductTemplateId);

								if ($UPRODUCE_DOC_ID && ($UPRODUCE_DOC_ID != $uProduceDocId) )
								{
									echo "UPRODUCE_DOC_ID: $UPRODUCE_DOC_ID<br>";
									echo "uProduceDocId: $uProduceDocId<p>";
									echo "ProductId: $ProductId<br>";
									echo "ProductTemplateId: $ProductTemplateId";
									die ("Cannot create data file for different uProduce docs");
								}
		
								$UPRODUCE_DOC_ID = $uProduceDocId;
		
								# Get dial names and type
								# (1) Get all the uProduce dial header for this product template
								$DialTypes = Us2ProductTemplateDialPeer::GetuProduceNameAndType ($ProductTemplateId);
								$Headers = array_merge($Headers, $DialTypes);
								
								# (2) Get all the default dial values for this template
								# Get all the dials for this product template
								# Get name and default value
								$Dials = Us2ProductTemplateDialPeer::GetTemplateDefaultAsset ($ProductTemplateId);
								$Cached['Dials'][$OrderProductId]['Template'] = $Dials;
								$Cached['Dials'][$OrderProductId]['Final'] = $Dials;
		
								# (3) Get all the default dial values for this product
								# Get product default dial value
								$Dials = Us2ProductDialPeer::GetProductDefaultAsset ($ProductId);
								if (!$Dials) $Dials = array();
								$Cached['Dials'][$OrderProductId]['Product'] = $Dials;
								$Cached['Dials'][$OrderProductId]['Final'] = array_merge($Cached['Dials'][$OrderProductId]['Final'], $Dials);
		

								# Get list of customization groups for this customer
								# then for each group, merge those variables as final values
								$arrayGroupName = Us2ProductCustomerDialPeer::GetGroups ($ProductId, $CustomerId);
								foreach($arrayGroupName as $groupName)
								{
									if(!$groupName) continue;
									$Dials = Us2ProductCustomerDialPeer::GetCustomerDefaultAsset ($CustomerId, $ProductId, $groupName);
									if (!$Dials) $Dials = array();
									$Cached['Dials'][$OrderProductId]['Groups'][$groupName] = $Cached['Dials'][$OrderProductId]['Final'];
									$Cached['Dials'][$OrderProductId]['Groups'][$groupName] = array_merge($Cached['Dials'][$OrderProductId]['Groups'][$groupName], $Dials);
								}
								
								# (4) Get all the default dial values for this customer
								# Get customer default dial value
								$Dials = Us2ProductCustomerDialPeer::GetCustomerDefaultAsset ($CustomerId, $ProductId, $arrayOrderProductGroupName[$OrderProductId]  );
								if (!$Dials) $Dials = array();
								$Cached['Dials'][$OrderProductId]['Customer'] = $Dials;
								$Cached['Dials'][$OrderProductId]['Final'] = array_merge($Cached['Dials'][$OrderProductId]['Final'], $Dials);
										
										
																

								# (5) Get all the dial/coupon group values for this product
								$arrayDialValue = Us2DialGroupOptsPeer::GetDialValue ($ProductId, 0);
								if (!$arrayDialValue) $arrayDialValue = array();
								$Cached['Dials'][$OrderProductId]['Final'] = array_merge($Cached['Dials'][$OrderProductId]['Final'], $arrayDialValue);


								# (6) Get all the dial/coupon group values for this product and customer
								$arrayDialValue = Us2DialGroupOptsPeer::GetDialValue ($ProductId, $CustomerId);
								if (!$arrayDialValue) $arrayDialValue = array();
								$Cached['Dials'][$OrderProductId]['Final'] = array_merge($Cached['Dials'][$OrderProductId]['Final'], $arrayDialValue);


								
								# (-) Get all the dial values for this order
								# Get order dial values
								$Dials = Us2OrderProductDialValuePeer::GetDialValues ($OrderProductId);
								if (!$Dials) $Dials = array();
								$Cached['Dials'][$OrderProductId]['Order'] = $Dials;
								$Cached['Dials'][$OrderProductId]['Final'] = array_merge($Cached['Dials'][$OrderProductId]['Final'], $Dials);		
								
								foreach($arrayGroupName as $groupName)
								{
									if(!$groupName) continue;
									$Cached['Dials'][$OrderProductId]['Groups'][$groupName] = array_merge($Cached['Dials'][$OrderProductId]['Groups'][$groupName], $Dials);
								}

								
								
								
							
								# IF IMAGE THEN DialValue contains image id
								foreach(  $Cached['Dials'][$OrderProductId]['Final'] as $uProduceDialName => $DialValue)
								{
									# TYPE IMAGE
									if ($Headers[$uProduceDialName] == 2)
									{
										$Us2Image = Us2ImagePeer::retrieveByPk ($DialValue);
										
										if ($Us2Image)
											$Cached['Dials'][$OrderProductId]['Final'][$uProduceDialName] = $Us2Image->getValue();
									}							
								}
								
								# IF IMAGE THEN DialValue contains image id
								foreach($arrayGroupName as $groupName)
								{
									foreach(  $Cached['Dials'][$OrderProductId]['Groups'][$groupName] as $uProduceDialName => $DialValue)
									{
										# TYPE IMAGE
										if ($Headers[$uProduceDialName] == 2)
										{
											$Us2Image = Us2ImagePeer::retrieveByPk ($DialValue);
											
											if ($Us2Image)
												$Cached['Dials'][$OrderProductId]['Groups'][$groupName][$uProduceDialName] = $Us2Image->getValue();
										}							
									}
								}
								
																
								
							}
					}
					

		

		
					# Attempt to create uProduce CSV file
					if ($JobGroupId)
						$uProduceCsvFile = "/var/www/web3/web/aggregation/jobgroup2/$JobGroupId/";
					else
						$uProduceCsvFile = "/var/www/web3/web/aggregation/jobgroup2/_temp/";

	
					if (! file_exists($uProduceCsvFile)) mkdir ($uProduceCsvFile);
			
					$uProduceCsvFile .= md5(time()) . '1.csv';
					#~-----
					if ($JobGroupId)
						$uProduceCsvFile2 = "/var/www/web3/web/aggregation/jobgroup2/$JobGroupId/";
					else
						$uProduceCsvFile2 = "/var/www/web3/web/aggregation/jobgroup2/_temp/";

					if (! file_exists($uProduceCsvFile2)) mkdir ($uProduceCsvFile2);
			
					$uProduceCsvFile2 .= md5(time()) . '2.csv';
					
					
					
					$file = fopen($uProduceCsvFile, 'w+') or die("Error: Can't open file on server for processing #1");
		
		
		
					# Double quote all csv headers
					$CsvHeader = '';
					
					foreach ($Headers as $uProduceDialName => $DialType)
					{
						$CsvHeader .= "\"$uProduceDialName\",";
					}
					$CsvHeader = substr($CsvHeader, 0, strlen($CsvHeader)-1);
					$CsvHeader .= "\r\n";
					



		
					# To fix the uProduce VPS issue.
					$StarredDials = array();
		
		
		
		
					# Cache order product property for better performance.
					$ArrayOrderProductProp = array();
					$Opp = array(); # Order Product Property
					#	['OrderProductId']
					#			['CustomerId']
					#			['ClientId']
					#			['ProductId']
					#			['JobGroupId']
					#			['MailingId']		
					#			['Coupons']
					
						$countData = count($data);
						# For every record, add csv data row.
						for ($i=1; $i<$countData; $i++)
						{
							if ($i > $recordLimit) break;

							
							$Index		= $data[$i][$KEY_INDEX];
							$Code		= $data[$i][$KEY_CODE];
							$FirstName	= $data[$i][$KEY_FIRSTNAME];
							$LastName	= $data[$i][$KEY_LASTNAME];
							$FullName	= $data[$i][$KEY_FULLNAME];
							$Address	= $data[$i][$KEY_ADDRESS];
							$City		= $data[$i][$KEY_CITY];
							$State		= $data[$i][$KEY_STATE];
							$Zip		= $data[$i][$KEY_ZIP];
							$Barcode	= $data[$i][$KEY_BARCODE];
							$Endorse	= $data[$i][$KEY_ENDORSE];
							$NameMaster	= $data[$i][$KEY_NAMEMASTER];
							$Matchcode	= $data[$i][$KEY_MATCHCODE];
							$Seq		= $data[$i][$KEY_SEQ];
							$PurlName	= $data[$i][$KEY_PURLNAME];
							$PurlCode	= $data[$i][$KEY_PURLCODE];
		
							$useGroup = NULL;
			
		
		
							if (! $Index) continue;	
			
							# Explode the code, [0] contains order product id, [1] contains list data id
							# for the associcated recipient.
							$Code = explode('-', $Code);
							
							# Code contains the OrderProductId
							$OrderProductId = $Code[0];
							$ListDataId		= $Code[1];
							if (! $OrderProductId) continue;
		
	
							# Check to see if we already have this order product property. If not
							# then load and cache it.
							if (! in_array($OrderProductId, $ArrayOrderProductProp) )
							{
								$ArrayOrderProductProp[] = $OrderProductId;
								
								$Us2OrderProduct 	= Us2OrderProductPeer::retrieveByPk ($OrderProductId);
								if(!$Us2OrderProduct) die("Error trying to load the order from the names in the list. You may have an old list, try downloading the new list file and try again.");
								$Us2Order			= Us2OrderPeer::retrieveByPk ($Us2OrderProduct->getOrderId() );
								
								$CustomerId			= $Us2Order->getCustomerId();
								$ClientId			= CustomerPeer::GetClientByCustomer($CustomerId);
								$ProductId			= $Us2OrderProduct->getProductId();
								#$JobGroupId		= $Us2OrderProduct->getJobGroupId();
								$ProgramTypeId		= $Us2OrderProduct->getProgramTypeId();
								$ProductTemplateId	= Us2ProductPeer::GetProductTemplateId ($ProductId);
								$MailTrackTypeId	= Us2ProductTemplatePeer::GetMailTrackTypeId ($ProductTemplateId);

//								if ($recordLimit==999999)
//								{
//									$Mailing = new Mailing();
//									$Mailing->setClientId		($ClientId);
//									$Mailing->setCustomerId		($CustomerId);
//									$Mailing->setUs2JobGroupId	($JobGroupId);
//									$Mailing->setUs2OrderId		($Us2Order->getOrderId());
//									$Mailing->setMailDate		(date('Y-m-d H:i:s'));
//									$Mailing->setMailTrackTypeId($MailTrackTypeId);
//									$Mailing->setTrackingCodes	('');
//									$Mailing->setTrackingData	('');
//									$Mailing->setCreatedByUserId(0);
//									$Mailing->setCreatedDate	(date('Y-m-d H:i:s'));
//									$Mailing->setUpdatedByUserId(0);
//									$Mailing->setUpdatedDate	(date('Y-m-d H:i:s'));
//									$Mailing->save();
//									
//									$MailingId	= $Mailing->getMailingId();
//								}
								
								$Opp[$OrderProductId]['CustomerId']		= $CustomerId;
								$Opp[$OrderProductId]['ClientId']		= $ClientId;
								$Opp[$OrderProductId]['ProductId']		= $ProductId;
								$Opp[$OrderProductId]['JobGroupId']		= $JobGroupId;
								$Opp[$OrderProductId]['ProgramTypeId']	= $JobGroupId;
//								$Opp[$OrderProductId]['MailingId']	= $MailingId;
							}
							else
							{
								$ClientId		= $Opp[$OrderProductId]['ClientId'];
								$CustomerId		= $Opp[$OrderProductId]['CustomerId'];
								$ProductId		= $Opp[$OrderProductId]['ProductId'];
								$JobGroupId		= $Opp[$OrderProductId]['JobGroupId'];
								$ProgramTypeId	= $Opp[$OrderProductId]['ProgramTypeId'];
//								$MailingId	= $Opp[$OrderProductId]['MailingId'];
							}
		

							# If this recipient record contains extra list data info then
							# extract the serialized data from the database.
							if ($ListDataId)
							{
								$Us2ListData = Us2ListDataPeer::retrieveByPk($ListDataId);
								if ($Us2ListData)
								{

									$Data = $Us2ListData->getSerializedData();
									$Data = unserialize($Data);
								}
							}
							else
							{
								$Data = array();
							}
							#print_r($Data);exit;
		


							$AddressId = AddressPeer::CreateIfNotExist($CNameMaster, $NameMaster);
							if(!$AddressId)
								$AddressId = $Data['ADDRESS_ID'];

							# If a sample barcode already exist for this customer, delete it
							# so we can generate another one.
							$CustomerBarcode = $Data['CUSTOMER_BARCODE'];
							
							if ($recordLimit==999999 && $AddressId)
							{
								$MailHistoryId = 0;
								
								$C = new Criteria();
								$C->addSelectColumn (MailHistoryPeer::MAIL_HISTORY_ID);
								$C->addAnd (MailHistoryPeer::US2_JOB_GROUP_ID, $JobGroupId);
								$C->addAnd (MailHistoryPeer::ADDRESS_ID, $AddressId);
								$C->addAnd (MailHistoryPeer::EXTERNAL_ID, $ProductId);
								#$C->addAnd (MailHistoryPeer::INAMEMASTERINDEX, $NameMaster);
								#$C->addAnd (MailHistoryPeer::LAST_NAME, $LastName);
								#$C->addAnd (MailHistoryPeer::FIRST_NAME, $FirstName);
								
								$Rs = MailHistoryPeer::doSelectRs ($C);
								while ($Rs->next())
								{
									#continue;
									$MailHistoryId = $Rs->get(1);
								
									if ($MailHistoryId)
									{
										$C = new Criteria();
										$C->add (MailHistoryPeer::MAIL_HISTORY_ID, $MailHistoryId);
										MailHistoryPeer::doDelete($C);
										
										$C = new Criteria();
										$C->add (MailHistoryDetailPeer::MAIL_HISTORY_ID, $MailHistoryId);
										MailHistoryDetailPeer::doDelete($C);									
									}
								}								
//								$arrayTrackingCode = array (
//									"{$CustomerBarcode}01",
//									"{$CustomerBarcode}02",
//									"{$CustomerBarcode}03",
//									"{$CustomerBarcode}04",
//									"{$CustomerBarcode}05",
//									"{$CustomerBarcode}06",
//									"{$CustomerBarcode}07",
//									"{$CustomerBarcode}08",
//									"{$CustomerBarcode}09",
//									"{$CustomerBarcode}10",
//									"{$CustomerBarcode}11",
//									"{$CustomerBarcode}12",
//									"{$CustomerBarcode}13",
//									"{$CustomerBarcode}14",
//									"{$CustomerBarcode}15",
//								);
//								
//								$MailHistoryId = MailHistoryDetailPeer::GetMailHistoryByCode ($arrayTrackingCode);
//								
								# If this record already exist then delete it
								# Probably created it when we do samples

							}
							
		
		
								# Save Mail History
								#################################################################
								$MailHistory = new MailHistory();
								$MailHistory->setiNameMasterIndex	($NameMaster);
								$MailHistory->setAddressId			($AddressId);
								$MailHistory->setClientId			($ClientId);
								$MailHistory->setCustomerId			($CustomerId);
								$MailHistory->setExternalId			($ProductId);
								$MailHistory->setUs2JobGroupId		($JobGroupId);
								$MailHistory->setFirstName			($FirstName);
								$MailHistory->setLastName			($LastName);
								$MailHistory->setMailDate			( date('Y-m-d') );
								$MailHistory->setProgramTypeId		($ProgramTypeId);
								$MailHistory->save();
								
								$MailHistoryId = $MailHistory->getMailHistoryId();




							$make = $Data['MAKE'];
							$make = trim(strtoupper($make));
							
							if($make && $Cached['Dials']["$OrderProductId"]['Groups'][$make])
								$useGroup = $make;


		
							$CSV = "";

							foreach ($Headers as $uProduceDialName => $DialType)
							{	
								$DialValue = $Cached['Dials']["$OrderProductId"]['Final']["$uProduceDialName"];
								if($useGroup)
									$DialValue = $Cached['Dials']["$OrderProductId"]['Groups'][$useGroup]["$uProduceDialName"];

								# If data exist for this recipient, use this instead of the product value
								if ($Data[$uProduceDialName])
									$DialValue = $Data[$uProduceDialName];
																		
								switch ($uProduceDialName)
								{
									case 'PURL_DOMAIN':
										if(  $arrayCustomerOverrideDialValue[$CustomerId][$make]  )
											$DialValue = $arrayCustomerOverrideDialValue[$CustomerId][$make];
										#print_r($Cached);
										break;
//									case 'PURL_NAME':
//										#$DialValue = $PurlName;
//										break;
//									case 'PURL_CODE':
//										#$DialValue = $PurlCode;
//										break;
									#case 'PURL_CO':
									#	break;
									#case 'PURL_DOMAIN':
									#	break;
									case 'FIRST':
										$DialValue = $FirstName;
										break;
									case 'LAST':
										$DialValue = $LastName;
										break;													
									case 'NAME':
										$DialValue = $FullName;
										break;
									case 'ADDRESS':
										$DialValue = $Address;
										break;
									case 'CITY':
										$DialValue = $City;
										break;
									case 'ST':
										$DialValue = $State;
										break;
									case 'ZIP':
										$DialValue = $Zip;
										break;
									case 'BARCODE':
										$DialValue = $Barcode;
										break;
									case 'ENDORSE':
										$DialValue = $Endorse;
										break;
									case 'GC_SEQ':
										$DialValue = $CustomerBarcode;
										break;
									case 'MSEQ':
										$DialValue = $Matchcode;
										break;
									case 'SEQ':
										$DialValue = $Seq;
										break;
									case 'EXP_DATE1': #COUPON EXP DATE
											# % = 90 days from expire date
											# (blank) = (blank)
											# (any) = (any)
										if (trim($DialValue)=='%')
											$DialValue = date('n/d/y', strtotime("+3 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='@')
											$DialValue = date('n/d/y', strtotime("+2 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='#')
											$DialValue = date('n/d/y', strtotime("+1 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='&')
											$DialValue = date('n/d/y', strtotime("+45 days", strtotime($mailDate)));																						
										break;
									case 'EXP_DATE2': #COUPON EXP DATE
										if (trim($DialValue)=='%')
											$DialValue = date('n/d/y', strtotime("+3 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='@')
											$DialValue = date('n/d/y', strtotime("+2 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='#')
											$DialValue = date('n/d/y', strtotime("+1 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='&')
											$DialValue = date('n/d/y', strtotime("+45 days", strtotime($mailDate)));												
										break;	
									case 'EXP_DATE3': #COUPON EXP DATE
										if (trim($DialValue)=='%')
											$DialValue = date('n/d/y', strtotime("+3 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='@')
											$DialValue = date('n/d/y', strtotime("+2 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='#')
											$DialValue = date('n/d/y', strtotime("+1 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='&')
											$DialValue = date('n/d/y', strtotime("+45 days", strtotime($mailDate)));												
										break;
									case 'EXP_DATE4': #COUPON EXP DATE
										if (trim($DialValue)=='%')
											$DialValue = date('n/d/y', strtotime("+3 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='@')
											$DialValue = date('n/d/y', strtotime("+2 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='#')
											$DialValue = date('n/d/y', strtotime("+1 months", strtotime($mailDate)));
										elseif (trim($DialValue)=='&')
											$DialValue = date('n/d/y', strtotime("+45 days", strtotime($mailDate)));												
										break;																														
									case 'EXP_DATE6': # WO MAIL DATE
										if (trim($DialValue)=='%')
											$DialValue = $mailDate;
										#$DialValue = $mailDate; #date('n/d/y', time()+86400 );#'3/31/2008';#
										break;
									case 'YEAR':
									case 'MAKE':
									case 'MAKE2':
									case 'YEAR_MAKE_MODEL':
									case 'MODEL':
										$DialValue = trim(strtolower($DialValue));
										
										if(in_array($DialValue, $arrayBogusVehicleMake))
											$DialValue = '';
										
										$DialValue = str_replace('&amp;', '&', $DialValue);
										$DialValue = ucwords($DialValue);
										$DialValue = str_ireplace($arrayBogusVehicleMake, '', $DialValue);
										$DialValue = str_replace('  ', ' ', $DialValue);
										
										if($uProduceDialName=='MODEL' && !$DialValue)
											$DialValue = 'Vehicle';

										break;	
									case 'INDICIA':
										# If we're not sending to an address, dont put in the
										# indicia, probably overrun
										if (!$DialValue || $DialValue==1)
										{
											if($ClientId==114) #JETMAIL
												$DialValue = '5733';
											else
												$DialValue = '7923';
										}
										if (!$Address)
											$DialValue = '5744'; # No Indicia Image, Blank
										break;
									case 'RI_NumberOfCopies':
										if (! $DialValue)
										$DialValue=1; # Default to 1 Copy per recipient									
										break;																					
									#default:
									#	$DialValue = $Cached['Dials'][$OrderProductId]['Final'][$uProduceDialName];
									#	break;
								}
								

								switch ($uProduceDialName)
								{
									case 'CPN_TXT1':
									{ 
										if (!$DialValue) break;

										$CustomerBarcode = $Data['CUSTOMER_BARCODE'];
										

											$Data['F5'] = "{$CustomerBarcode}01";
											
											$CouponDropId	= 0;
											$CouponBarcode	= "01";
											$CouponName		= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXT1'];
											$CouponAmount	= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXTB1'];
											$CouponOpcode	= $Cached['Dials'][$OrderProductId]['Final']['OPT1'];
											
											$tracking_detail = array (
												'coupon_drop_id'	=> $CouponDropId,
												'coupon_barcode'	=> $CouponBarcode,
												'coupon_name'		=> $CouponName,
												'coupon_amount'		=> $CouponAmount,
												'coupon_opcode'		=> $CouponOpcode
											);
											
											$tracking_detail = serialize($tracking_detail);
											

												$MailHistoryDetail = new MailHistoryDetail();
												$MailHistoryDetail->setMailHistoryId	($MailHistoryId);
												$MailHistoryDetail->setTrackingCode 	($Data['F5']);
												$MailHistoryDetail->setTrackingDetail 	($tracking_detail);
												$MailHistoryDetail->save();
											
//											$Opp[$OrderProductId]['Coupons']["{$CouponName}{$CouponOpcode}"] = array(
//												'coupon_name'		=> $CouponName,
//												'coupon_amount'		=> $CouponAmount,
//												'coupon_opcode'		=> $CouponOpcode,
//											);



									}
										break;
									case 'CPN_TXT2':
									{
										if (!$DialValue) break;
										$CustomerBarcode = $Data['CUSTOMER_BARCODE'];


											$Data['F6'] = "{$CustomerBarcode}02";
											
											$CouponDropId	= 0;
											$CouponBarcode	= "02";
											$CouponName		= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXT2'];
											$CouponAmount	= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXTB2'];
											$CouponOpcode	= $Cached['Dials'][$OrderProductId]['Final']['OPT2'];
											
											$tracking_detail = array (
												'coupon_drop_id'	=> $CouponDropId,
												'coupon_barcode'	=> $CouponBarcode,
												'coupon_name'		=> $CouponName,
												'coupon_amount'		=> $CouponAmount,
												'coupon_opcode'		=> $CouponOpcode
											);
											
											$tracking_detail = serialize($tracking_detail);
											

												$MailHistoryDetail = new MailHistoryDetail();
												$MailHistoryDetail->setMailHistoryId	($MailHistoryId);
												$MailHistoryDetail->setTrackingCode 	($Data['F6']);
												$MailHistoryDetail->setTrackingDetail 	($tracking_detail);
												$MailHistoryDetail->save();
												
												
//											$Opp[$OrderProductId]['Coupons']["{$CouponName}{$CouponOpcode}"] = array(
//												'coupon_name'		=> $CouponName,
//												'coupon_amount'		=> $CouponAmount,
//												'coupon_opcode'		=> $CouponOpcode,
//											);

									}
										break;
									case 'CPN_TXT3':
									{
										if (!$DialValue) break;
										$CustomerBarcode = $Data['CUSTOMER_BARCODE'];


											$Data['F7'] = "{$CustomerBarcode}03";
											
											$CouponDropId	= 0;
											$CouponBarcode	= "03";
											$CouponName		= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXT3'];
											$CouponAmount	= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXTB3'];
											$CouponOpcode	= $Cached['Dials'][$OrderProductId]['Final']['OPT3'];
											
											$tracking_detail = array (
												'coupon_drop_id'	=> $CouponDropId,
												'coupon_barcode'	=> $CouponBarcode,
												'coupon_name'		=> $CouponName,
												'coupon_amount'		=> $CouponAmount,
												'coupon_opcode'		=> $CouponOpcode
											);
											
											$tracking_detail = serialize($tracking_detail);
											

												$MailHistoryDetail = new MailHistoryDetail();
												$MailHistoryDetail->setMailHistoryId	($MailHistoryId);
												$MailHistoryDetail->setTrackingCode 	($Data['F7']);
												$MailHistoryDetail->setTrackingDetail 	($tracking_detail);
												$MailHistoryDetail->save();
												
												
//											$Opp[$OrderProductId]['Coupons']["{$CouponName}{$CouponOpcode}"] = array(
//												'coupon_name'		=> $CouponName,
//												'coupon_amount'		=> $CouponAmount,
//												'coupon_opcode'		=> $CouponOpcode,
//											);
								
									}
										break;	
									case 'CPN_TXT4':
									{
										if (!$DialValue) break;
										$CustomerBarcode = $Data['CUSTOMER_BARCODE'];


											$Data['F8'] = "{$CustomerBarcode}04";
											
											$CouponDropId	= 0;
											$CouponBarcode	= "04";
											$CouponName		= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXT4'];
											$CouponAmount	= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXTB4'];
											$CouponOpcode	= $Cached['Dials'][$OrderProductId]['Final']['OPT4'];
											
											$tracking_detail = array (
												'coupon_drop_id'	=> $CouponDropId,
												'coupon_barcode'	=> $CouponBarcode,
												'coupon_name'		=> $CouponName,
												'coupon_amount'		=> $CouponAmount,
												'coupon_opcode'		=> $CouponOpcode
											);
											
											$tracking_detail = serialize($tracking_detail);
											

												$MailHistoryDetail = new MailHistoryDetail();
												$MailHistoryDetail->setMailHistoryId	($MailHistoryId);
												$MailHistoryDetail->setTrackingCode 	($Data['F8']);
												$MailHistoryDetail->setTrackingDetail 	($tracking_detail);
												$MailHistoryDetail->save();
												
												
//											$Opp[$OrderProductId]['Coupons']["{$CouponName}{$CouponOpcode}"] = array(
//												'coupon_name'		=> $CouponName,
//												'coupon_amount'		=> $CouponAmount,
//												'coupon_opcode'		=> $CouponOpcode,
//											);
										
									}
										break;
									case 'CPN_TXT5':
									{
										if (!$DialValue) break;
										$CustomerBarcode = $Data['CUSTOMER_BARCODE'];


											$Data['F9'] = "{$CustomerBarcode}05";
											
											$CouponDropId	= 0;
											$CouponBarcode	= "05";
											$CouponName		= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXT5'];
											$CouponAmount	= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXTB5'];
											$CouponOpcode	= $Cached['Dials'][$OrderProductId]['Final']['OPT5'];
											
											$tracking_detail = array (
												'coupon_drop_id'	=> $CouponDropId,
												'coupon_barcode'	=> $CouponBarcode,
												'coupon_name'		=> $CouponName,
												'coupon_amount'		=> $CouponAmount,
												'coupon_opcode'		=> $CouponOpcode
											);
											
											$tracking_detail = serialize($tracking_detail);
											

												$MailHistoryDetail = new MailHistoryDetail();
												$MailHistoryDetail->setMailHistoryId	($MailHistoryId);
												$MailHistoryDetail->setTrackingCode 	($Data['F9']);
												$MailHistoryDetail->setTrackingDetail 	($tracking_detail);
												$MailHistoryDetail->save();
												
												
//											$Opp[$OrderProductId]['Coupons']["{$CouponName}{$CouponOpcode}"] = array(
//												'coupon_name'		=> $CouponName,
//												'coupon_amount'		=> $CouponAmount,
//												'coupon_opcode'		=> $CouponOpcode,
//											);
										
									}
										break;	
									case 'CPN_TXT6':
									{
										if (!$DialValue) break;
										$CustomerBarcode = $Data['CUSTOMER_BARCODE'];


											$Data['F10'] = "{$CustomerBarcode}06";
											
											$CouponDropId	= 0;
											$CouponBarcode	= "06";
											$CouponName		= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXT6'];
											$CouponAmount	= $Cached['Dials'][$OrderProductId]['Final']['CPN_TXTB6'];
											$CouponOpcode	= $Cached['Dials'][$OrderProductId]['Final']['OPT6'];
											
											$tracking_detail = array (
												'coupon_drop_id'	=> $CouponDropId,
												'coupon_barcode'	=> $CouponBarcode,
												'coupon_name'		=> $CouponName,
												'coupon_amount'		=> $CouponAmount,
												'coupon_opcode'		=> $CouponOpcode
											);
											
											$tracking_detail = serialize($tracking_detail);
											

												$MailHistoryDetail = new MailHistoryDetail();
												$MailHistoryDetail->setMailHistoryId	($MailHistoryId);
												$MailHistoryDetail->setTrackingCode 	($Data['F10']);
												$MailHistoryDetail->setTrackingDetail 	($tracking_detail);
												$MailHistoryDetail->save();
												
//											$Opp[$OrderProductId]['Coupons']["{$CouponName}{$CouponOpcode}"] = array(
//												'coupon_name'		=> $CouponName,
//												'coupon_amount'		=> $CouponAmount,
//												'coupon_opcode'		=> $CouponOpcode,
//											);
										
									}
										break;																	
								}
								
		
		
		
								# If this dial is an image, try to load the full path to the image
								# TYPE IMAGE
								if ($Headers[$uProduceDialName] == 2)
								{
									if(intval($DialValue))
									{
										$Us2Image = Us2ImagePeer::retrieveByPk ($DialValue);
										
										if ($Us2Image)
											$DialValue = $Us2Image->getValue();
									}
								}	
									
								
								###################################################
								if ( isset($StarredDials["$uProduceDialName"]) )
								{
									if (  strlen($DialValue) > $StarredDials["$uProduceDialName"] )
									{
										$StarredDials["$uProduceDialName"] = strlen($DialValue);
									}
								}
								else
								{
									$StarredDials["$uProduceDialName"] = strlen($DialValue);
								}
								
								
														
								
														
								$DialValue = str_replace('"', '""', $DialValue);
								$DialValue = str_replace("\r\n", "\n", $DialValue);
		
								if ($uProduceDialName == 'RI_NumberOfCopies')
								{
									$CSV .= "$DialValue,";	
								}
								else
								{
									$CSV .= "\"$DialValue\",";	
								}
							
								
							}
	
								$CSV = substr($CSV, 0, strlen($CSV)-1);
								$CSV .= "\r\n";
		
								if( fwrite($file, $CSV)===false ) die ("Error: Can't write data into file");
								fflush($file);
		#print_r($Cached);
						#echo $OrderProductId;
						#echo $CSV;
								
						}
						



						#print_r($Opp); exit;
						# For each Order Product, load the Mailing and set the coupons 
						# we sent out along with the opcodes
//						foreach ($Opp as $OrderProductId => $Property)
//						{
//							$MailingId	= $Property['MailingId'];
//							$Coupons	= $Property['Coupons'];
//							
//							if ($MailingId)
//							{
//								$Mailing = MailingPeer::retrieveByPk ($MailingId);
//								$TrackingCodes = $Mailing->getTrackingCodes();
//								$TrackingCodes = unserialize($TrackingCodes);
//								
//								foreach ($Coupons as $Coupon => $C)
//								{
//									$TrackingCodes['COUPONS'][] = array(
//										'amount'	=> $C['coupon_amount'],
//										'text'		=> $C['coupon_name'],
//										'opcode'	=> $C['coupon_opcode']
//									);
//								}
//								
//								$Mailing->setTrackingCodes ( serialize($TrackingCodes) );
//								$Mailing->save();
//							}
//						}
						
						
					
					
					
					
						
								fclose($file);
						
								$file2 = fopen($uProduceCsvFile2, 'w+') or die("Error: Can't open file on server for processing #2");
								
								if( fwrite($file2, $CsvHeader)===false ) die ("Error: Can't write data into file");
								fflush($file2);
		
								$data = '';
								foreach ($StarredDials as $uProduceDialName => $value)
								{
									$data .= '"' . str_repeat (' ', $value) . '",';
								}
								$data = substr($data, 0, strlen($data)-1);
								$data .= "\r\n";
								
								for($i=0; $i<$blankRecord; $i++)
								{
									if( fwrite($file2, $data)===false ) die ("Error: Can't write data into file");
									fflush($file2);							
								}
								
		
						
						
								$file = fopen($uProduceCsvFile, 'r') or die("Error: Can't open file on server for processing #3");
				
								while (!feof($file)) // Loop til end of file.
								{
									$buffer = fgets($file, 4096); // Read a line.
									if( fwrite($file2, $buffer)===false ) die ("Error: Can't write data into file");
									fflush($file2);	
								}
				
								fclose($file);
								fclose($file2);
		

					if ($JobGroupId)
					{
						$Us2JobGroup = Us2JobGroupPeer::retrieveByPk ($JobGroupId);
						$Us2JobGroup->setuProduceCsvFile ($uProduceCsvFile2);
						$Us2JobGroup->setuProduceDocId($UPRODUCE_DOC_ID);
						$Us2JobGroup->save();
					}
					else
					{
						return $uProduceCsvFile2;
					}

			}	
	
			/**
			* Private Function: GenerateFinalCsvFile()
			*********************************************************************************/
			public static function GenerateFinalCsvFile($JobGroupId, $RecipientCsvFile, $recordLimit=999999, $blankRecord=0, $arrayOrderProductGroupName=array(), $mailDate, $woNumber='', $isProduction=false, $dieOnError=true)
			{						
				$time = microtime(true);
				require_once ("/var/www/web3/lib/aggregator.class.php");

				$Aggregation = new Aggregator();
				
				if($isProduction) #$JobGroupId==20174
					$Aggregation->SetProductionMode(true);

				$Aggregation->_flagTriggerBatchRecipient = true;	# Save all recipient triggered from amms lite process
				$Aggregation->SetRecordLimit("$recordLimit");
				$Aggregation->SetMailDate($mailDate);
				$Aggregation->SetBlankRecord($blankRecord);
				$Aggregation->InitRecipientData("$RecipientCsvFile");
				$Aggregation->PreloadOrderValues($arrayOrderProductGroupName);
				$Aggregation->CreateRecipientRecord();
				$Aggregation->GenerateFinalValue();
				
				# If we find ABC DEALERSHIP, then die
				# 
				/*
				if($Aggregation->_foundABCInOrderProduct)
				{
					if($dieOnError)
					{
						echo "FOUND <b>ABC DEALERSHIP</b>, <b>USA TOYOTA</b>, OR <b>*NAME*</b> IS NOT SET IN THE FOLLOWING ORDERS<p>";
						foreach($Aggregation->_foundABCInOrderProduct as $x) {
							$customerName 	= CustomerPeer::GetNameById($x['customer_id']);
							$productName	= Us2ProductPeer::GetNameById($x['product_id']);

							echo "<b>Order:</b> {$x[order_product_id]} <b>Customer:</b>$customerName <b>Product:</b>$productName <b>Desc:</b> $x[desc]<br>";
						}
						die("**");
					}
					else
					{
						$message = "FOUND <b>ABC DEALERSHIP</b>, <b>USA TOYOTA</b>, OR <b>*NAME*</b> IS NOT SET IN THE FOLLOWING ORDERS<p>";
						foreach($Aggregation->_foundABCInOrderProduct as $x) {
							$customerName 	= CustomerPeer::GetNameById($x['customer_id']);
							$productName	= Us2ProductPeer::GetNameById($x['product_id']);

							$message .= "<b>Order:</b> {$x[order_product_id]} <b>Customer:</b>$customerName <b>Product:</b>$productName <b>Desc:</b> $x[desc]<br>";
						}

						return array(
							'status' 	=> 'error',
							'message'	=> $message
						);
					}
				}
				*/
				
			
				$Aggregation->CreateFinalCsvFile($JobGroupId);			
				$Aggregation->CreateMailingRecord($JobGroupId);
				
				/*``
				` If we have list of recipients from the amms lite trigger process,
				` go back and update all the "prep_data" for those records so the email
				` trigger can send with matching data.
				````````````````````````````````````````````````````````````````````````*/
				if($Aggregation->_arrayBatchTriggerRecipient)
				{
						require_once('/var/www/web3/classes/class.dms_functions.php');
						
						foreach($Aggregation->_arrayBatchTriggerRecipient as $CustomerId => $arrayList)
						{
							#$Dms = new Dms($CustomerId);
							#
							#foreach($arrayList as $data)
							#{
							#	$TriggerBatchId		= $data['TRIGGER_BATCH_ID'];
							#	$TriggerBatchListId	= $data['TRIGGER_BATCH_LIST_ID'];
							#	$RecipientCsvData	= $data['RecipientCsvData'];
							#	
							#	UpdateTriggerBatchListPrepData($CustomerId, $TriggerBatchId, $TriggerBatchListId, $RecipientCsvData);
							#}
						}
				}

				return true;
			}
			
			
			/**
			* Private Function: SetJobForHandwriting()
			*********************************************************************************/
			public static function SetJobForHandwriting($arrayJobGroupId, $blankRecord=0, $maxRecord=999999)
			{			
				# Get Work Order Mail Date
				#``````````````````````````````````````````````````````````````````````````
				define( '_VALID_RBS' , '1');
				define( '_VALID_MOS' , '1');
				
				
				require_once (SF_ROOT_DIR . '/classes/config.inc.php');
				require_once (SF_ROOT_DIR . '/classes/class.workorder_objects.php');
				
				$database				= new database ($sDwSQLServer, $sDwSQLUser, $sDwSQLPass, $sDwSQLDatabase);
				$WO_database			= new database ($sWoSqlServer, $sWoSqlUser, $sWoSqlPass, $sWoSqlDatabase);
				$CMasterClient			= new TblMasterClients($WO_database);
				$arrayProductCustomData	= array();
				$layoutType				= 'A6';
				
				/*`
				`````````````````````````````````````````````````````````````````````````````````*/			
				require_once ("/var/www/web3/lib/aggregator.class.php");

				foreach($arrayJobGroupId as $JobGroupId)
				{
					$Us2JobGroup 			= Us2JobGroupPeer::retrieveByPk($JobGroupId);
					$uProduceCsvFile		= $Us2JobGroup->getuProduceCsvFile();
					$RecipientCsvFile		= $Us2JobGroup->getRecipientCsvFile();
					$woNumber				= $Us2JobGroup->getWoNumber();			
					$createMailingRecord 	= true;
					$mailDate 				= date('n/d/y');					
					
					if($CMasterClient->GetByClientCode($woNumber))
						$ClientId = $CMasterClient->idclient;
		
					$CTblWorkOrderMailDates	= new TblWorkOrderMailDates($WO_database,$ClientId);
												
					if($CTblWorkOrderMailDates->GetByWorkOrder($woNumber))
						$mailDate = date('n/d/y', strtotime($CTblWorkOrderMailDates->dtmail));
					
					
					/*` New handwriting
					`````````````````````````````````````````````````````````````````````````````````*/	
					/*
					 * Deprecated: 01/04/2011 Eliot
					 
					$Handwriting = new Handwriting();
					$Handwriting->setJobGroupId($JobGroupId);
					
					$Handwriting->save();
					$HandwritingId = $Handwriting->getHandwritingId();
					
					$Us2JobGroup->setHandwritingId($HandwritingId);
					$Us2JobGroup->save();
					*/
					
					/* Returns a Handwriting Record, by passing in Us2JobGroup  $the handwriting_id on it will be set
					  After Creation and it will be saved
					*/
					$Handwriting = HandwritingPeer::_CreateHandwritingUProduce($JobGroupId, $Us2JobGroup);
					
					
						
					/*` Aggregation
					`````````````````````````````````````````````````````````````````````````````````*/	
					$Aggregation = new Aggregator();			
					$Aggregation->setRecordLimit($maxRecord);
					$Aggregation->SetMailDate($mailDate);
					$Aggregation->SetBlankRecord($blankRecord);
					$Aggregation->InitRecipientData("$RecipientCsvFile");
					$Aggregation->PreloadOrderValues();
					$Aggregation->CreateRecipientRecord();
					$Aggregation->GenerateFinalValue();	
					
					$arrayListData 		= $Aggregation->getFinalList();
					$arrayCodeExtraData = array();
					$envelopeStyle		= '';
	
					/*` Create the handwriting record for each person
					`````````````````````````````````````````````````````````````````````````````````*/			
					foreach($arrayListData as $i => $recipient)
					{
						$personalData	= $recipient['PersonalData'];
						$csvData		= $recipient['RecipientCsvData'];
						$productId		= $personalData['PRODUCT_ID'];
						$customerId		= $personalData['CUSTOMER_ID'];
						$orderProductId	= $personalData['ORDER_PRODUCT_ID'];
						$code			= $personalData['CODE'];
						$index			= $personalData['::INDEX::'];
						$orderData		= $Aggregation->arrayOrderProperty[$orderProductId];
						$customData		= $arrayProductCustomData[$productId];
						
						#$personalData['FIRSTNAME']	= ucwords(strtolower($personalData['FIRSTNAME']));
						#$personalData['LASTNAME']	= ucwords(strtolower($personalData['LASTNAME']));
						#$personalData['FULLNAME']	= ucwords(strtolower($personalData['FULLNAME']));
						#$personalData['FIRST']		= ucwords(strtolower($personalData['FIRST']));
						#$personalData['MIDDLE']		= ucwords(strtolower($personalData['MIDDLE']));
						#$personalData['LAST']		= ucwords(strtolower($personalData['LAST']));
						#$personalData['ADDRESS']	= ucwords(strtolower($personalData['ADDRESS']));
						#$personalData['CITY']		= ucwords(strtolower($personalData['CITY']));
						#$personalData['ZIP']		= substr($personalData['FIRSTNAME'], 0, 5);
						
						
						if($productId && !isset($customData)) {
							 $customData = Us2ProductPeer::GetCustomData($productId);
							 $arrayProductCustomData[$productId] = $customData;
						}
						
						$envelopeStyle	= $customData['ENVELOPE_STYLE'];
						$returnFirst	= ucwords(strtolower($orderData['Return To: First']));
						$returnLast		= ucwords(strtolower($orderData['Return To: Last']));
						$returnAddress	= ucwords(strtolower($orderData['Return To: Address']));
						$returnCity		= ucwords(strtolower($orderData['Return To: City']));
						$returnState	= $orderData['Return To: State'];
						$returnZip		= substr($orderData['Return To: Zip'], 0, 5);

						if(!$returnFirst)	$returnFirst 	= 'Patrick';		
						if(!$returnLast) 	$returnLast 	= 'Jacobson';	
						if(!$returnAddress) $returnAddress 	= '9427 Corporate Lake Dr.';	
						if(!$returnCity) 	$returnCity 	= 'Tampa';	
						if(!$returnState) 	$returnState 	= 'FL';	
						if(!$returnZip) 	$returnZip		= '33634';					
													
													
						$arrayData			= array();
						$arrayProperties	= array();
						$arrayBody			= array();
						$Color				= array('Red'=>0, 'Green'=>0, 'Blue'=>0);
		
						# Clean up unused fields in the array				
						foreach($personalData as $field => $value)
							if(!$value) unset($personalData[$field]);
	
						/*`
						` Create an image for each paragraph field, send that image to xmpie, and
						` set the associated image field value with the new image path.
						``````````````````````````````````````````````````````````````````````````````*/
						foreach($Aggregation->arrayCustomTextImageDial[$productId][$customerId] as $imageField => $textField)
						{
							$data 		= $csvData;
							$text		= $csvData[$textField]."<br />";
							$text		= str_replace("\n", '<br />', $text);
							$fontSize	= $Aggregation->arrayOrderProductDialProperty[$orderProductId][$textField]['FONTSIZE'];
							$fontFile	= $Aggregation->arrayOrderProductDialProperty[$orderProductId][$textField]['FONTFILE'];
							$fontColor	= $Aggregation->arrayOrderProductDialProperty[$orderProductId][$textField]['FONTCOLOR'];
							
							if(!$fontSize) $fontSize = 124;
							$fontAngle	= 1.0;
							$yNoise		= 0.1;
							if($fontFile) $fontFile = SF_ROOT_DIR.'/web/fonts/'.$fontFile;
							
							switch($fontColor) {
								case 'DARKBLUE':	$fontColor = array('Red'=>0, 'Green'=>32, 'Blue'=>179); break;
								default: 			$fontColor = array('Red'=>0, 'Green'=>0, 'Blue'=>0); 	break;
							}
												
							
							$Color = $fontColor;
							
							$arrayData['body'] 		= $personalData;
							$arrayData['sender'] 	= array("FIRSTNAME" => $returnFirst, "LASTNAME" => $returnLast, "ADDRESS" => $returnAddress, "CITY" => $returnCity, "STATE" => $returnState, "ZIP" => $returnZip);
							$arrayData['recipient'] = $personalData;
							/* Deprecated :  01-04-2011 Eliot 
							$arrayProperties['body']		= array('font_points'=>$fontSize, 'font_angle'=>$fontAngle, 'y_noise'=>$yNoise, 'height_inches'=>4, 'width_inches'=>8, 'dpi'=>300);
							*/
							
							$arrayProperties['body']			= array('font_points'=>$fontSize,"font_file"=>$fontFile);
							$arrayProperties['sender']			= array('font_points'=>$fontSize,"font_file"=>$fontFile);
							$arrayProperties['recipient']		= array('font_points'=>$fontSize,"font_file"=>$fontFile);
							//$arrayBody['body']				= $text;
							if (!$Handwriting->is_body_set("body")){
								$Handwriting->bodies_body($text);
							}
						    /*
                            $arrayProperties['recipient']	= array('font_angle'	=> 0.2, "y_noise" => 0.1);
							$arrayProperties['sender']	= array('font_angle'	=> 0.2, "y_noise" => 0.1);
							*/





                             /*
							$arrayBody['recipient']			= "{FIRSTNAME} {LASTNAME}<br />{ADDRESS}<br />{CITY}, {STATE} {ZIP}";
							$arrayBody['sender']			= "{FIRSTNAME} {LASTNAME}<br />{ADDRESS}<br />{CITY}, {STATE} {ZIP}";
							*/
							
							# Update csv data for xmpie
							$Aggregation->arrayRecipientRecord[$i]['RecipientCsvData'][$imageField] = "\\\\TINMAN\\NameServer\\www\\handwriting\\images\\in\\" . $woNumber . "\\body\\" . $index . ".eps";
						 	#$Aggregation->arrayRecipientRecord[$i]['RecipientCsvData'][LOC_SENDER] = "\\\\TINMAN\\NameServer\\www\\handwriting\\images\\in\\" . $woNumber . "\\sender\\" . $index . ".bmp";
						 	#$Aggregation->arrayRecipientRecord[$i]['RecipientCsvData'][LOC_RECIPIENT] = "\\\\TINMAN\\NameServer\\www\\handwriting\\images\\in\\" . $woNumber . "\\recipient\\" . $index . ".bmp";
							
							#$arrayCodeExtraData[$code][LOC_SENDER] 		= "\\\\TINMAN\\NameServer\\www\\handwriting\\images\\in\\" . $woNumber . "\\sender\\" . $index . ".bmp";
							#$arrayCodeExtraData[$code][LOC_RECIPIENT] 	= "\\\\TINMAN\\NameServer\\www\\handwriting\\images\\in\\" . $woNumber . "\\recipient\\" . $index . ".bmp";
							$arrayCodeExtraData[$code][LOC_SENDER] 		= $index . ".bmp";
							$arrayCodeExtraData[$code][LOC_RECIPIENT] 	= $index . ".bmp";

						}
						
						/*
						* Deprecated: 01/04/2011 Eliot
						
						
						$HandwritingRecipient = new HandwritingRecipient();
						$HandwritingRecipient->setHandwritingId($HandwritingId);
						$HandwritingRecipient->setRecordNumber($i);
						$HandwritingRecipient->setData(serialize($arrayData));
						$HandwritingRecipient->setBodyProperties(serialize($arrayProperties));
						$HandwritingRecipient->setBody(serialize($arrayBody));
						$HandwritingRecipient->save();
						
						# Use the first person in the list for the default
						if($isMasterDataCreated == false) {
							$Handwriting->setBodyProperties(serialize($arrayProperties));
							$Handwriting->setBody(serialize($arrayBody));
							$Handwriting->save();
							$isMasterDataCreated = true;
						}
						
						*/
						/* 
						* New Code: 01-04-2011 Eliot
		
						*/
						$arrayProperties['Color'] = $Color;
						$params = array("Color"=>$Color, "body_properties" => $arrayProperties);

						$HandwritingRecipient = $Handwriting->_add_recipient($arrayData, $index, $params);
						
					}
					
					
					/*` Update handwriting
					`````````````````````````````````````````````````````````````````````````````````*/	
					$Handwriting->setReadyYn('Y');
					$Handwriting->setLayoutType($envelopeStyle ? $envelopeStyle : $layoutType);
					$Handwriting->save();


					#$uProduceCsvFile = $Aggregation->CreateFinalPrintFile();
					#$Aggregation->SaveJobGroupPrintCsv($JobGroupId, "$uProduceCsvFile");
					self::SaveNewRecipientListFile($JobGroupId, $arrayCodeExtraData);
				}
			}
			
			
			/**
			* Private Function: GenerateuProduceCsvFile()
			* This is the new function with Automagic 11/26/2008
			*********************************************************************************/
			public static function GenerateuProduceCsvFile($JobGroupId, $RecipientCsvFile, $recordLimit=999999, $blankRecord=0, $arrayOrderProductGroupName=array(), $mailDate, $woNumber='')
			{			
				/*`
				`````````````````````````````````````````````````````````````````````````````````*/		
				$time = microtime(true);	
				require_once ("/var/www/web3/lib/aggregator.class.php");

				$Aggregation = new Aggregator();
				
				if(true) #$JobGroupId==20174
					$Aggregation->SetProductionMode(true);
					
							
				$Aggregation->SetRecordLimit("$recordLimit");
				$Aggregation->SetMailDate($mailDate);
				$Aggregation->SetBlankRecord($blankRecord);
				$Aggregation->InitRecipientData("$RecipientCsvFile");
				$Aggregation->PreloadOrderValues($arrayOrderProductGroupName);
				$Aggregation->CreateRecipientRecord();
				$Aggregation->GenerateFinalValue();
				
				
//				if($JobGroupId==21231)
//				{
//					echo '<pre>';
//					print_r($Aggregation);
//					exit;
//				}
				
				/**
				` Jan 07, 2011
				` If we have custom handwriting jobs, load the fields that need to be updated with
				` the correct handwriting image path and replace it with the path to the image file.
				``````````````````````````````````````````````````````````````````````````````````````*/
				if($Aggregation->arrayCustomTextImageDial)
				{
					$arrayListData = $Aggregation->getFinalList();

					/*` Create the handwriting record for each person
					`````````````````````````````````````````````````````````````````````````````````*/			
					foreach($arrayListData as $i => $recipient)
					{
						$personalData	= $recipient['PersonalData'];
						$productId		= $personalData['PRODUCT_ID'];
						$customerId		= $personalData['CUSTOMER_ID'];
						$orderProductId	= $personalData['ORDER_PRODUCT_ID'];
						$index			= $personalData['::INDEX::'];
	
						foreach($Aggregation->arrayCustomTextImageDial[$productId][$customerId] as $imageField => $textField)
						{
							# Update csv data for xmpie
							$Aggregation->arrayRecipientRecord[$i]['RecipientCsvData'][$imageField] = "\\\\TINMAN\\NameServer\\www\\handwriting\\images\\in\\" . $woNumber . "\\body\\" . $index . ".eps";
						}
					}				
				}
				
				
				$uProduceCsvFile = $Aggregation->CreateFinalPrintFile($JobGroupId);
				$Aggregation->SaveJobGroupPrintCsv($JobGroupId, "$uProduceCsvFile");

				/* If print job, create the mailing record
				``````````````````````````````````````````````*/
				#if($recordLimit==999999)
				#	$Aggregation->CreateMailingRecord($JobGroupId);
			}	
			

			/**
			* Prepare job group to production
			* Generate the final uProduce csv file and save it ofr future reference
			*********************************************************************************/
			public static function PrepareJobGroup ($jobGroupId=0, $arrayOrderProductGroupName=array(), $dieOnError=true)
			{
				ini_set('memory_limit', '3072M');
				if(!$jobGroupId) return false;
				$Us2JobGroup = Us2JobGroupPeer::retrieveByPk($jobGroupId);
				
				if(!$Us2JobGroup) return false;
				$uProduceCsvFile		= $Us2JobGroup->getuProduceCsvFile();
				$RecipientCsvFile		= $Us2JobGroup->getRecipientCsvFile();
				$woNumber				= $Us2JobGroup->getWoNumber();			
				$createMailingRecord 	= true;
				$mailDate 				= date('n/d/y');
				
				
				if(!$RecipientCsvFile) return false;
				$file = fopen($RecipientCsvFile, 'r');
				$i=0;
				while(!feof($file))
				{
				  fgets($file);
				  $i++;
				  if($i>5) break;
				}
				fclose($file);
				
				if($i<=2) return false; ### NO RECORDS!!
				
				
				
				# Do this so we don't create mailing records....
				if( strpos($woNumber, 'GS_SAMP') !== false)
					$createMailingRecord = false;
					
								
				# Get Work Order Mail Date
				#``````````````````````````````````````````````````````````````````````````
				define( '_VALID_RBS' , '1');
				define( '_VALID_MOS' , '1');
				
				require_once (SF_ROOT_DIR . '/classes/config.inc.php');
				require_once (SF_ROOT_DIR . '/classes/class.workorder_objects.php');
				
				$database				= new database ($sDwSQLServer, $sDwSQLUser, $sDwSQLPass, $sDwSQLDatabase);
				$WO_database			= new database ($sWoSqlServer, $sWoSqlUser, $sWoSqlPass, $sWoSqlDatabase);
				$CMasterClient			= new TblMasterClients($WO_database);
				
				if($CMasterClient->GetByClientCode($woNumber))
					$ClientId = $CMasterClient->idclient;
		
				$CTblWorkOrderMailDates	= new TblWorkOrderMailDates($WO_database,$ClientId);
												
				if($CTblWorkOrderMailDates->GetByWorkOrder($woNumber))
					$mailDate = date('n/d/y', strtotime($CTblWorkOrderMailDates->dtmail));
						
				if($mailDate=='12/31/1969' || $mailDate=='12/31/69')
					return false;


				# Re-create the uProduce CSV file in case one doesn't exist
				# or the recipient list file is replaced with another one.
				return self::GenerateFinalCsvFile($jobGroupId, $RecipientCsvFile, $printRecord=999999, $blankRecord=0, $arrayOrderProductGroupName, $mailDate, $woNumber, $isProduction=true, $dieOnError);
			}
			
			
			/**
			* Send job to production
			*********************************************************************************/
			public static function SendJobToProduction ($arrayJobGroupId=array(), $outputType='VPS', $blankRecord=1, $maxRecord=999999, $arrayOrderProductGroupName=array(), $inCopyDestination='', $RenderEngine='')
			{
				if (! $arrayJobGroupId)
				{
					return array (
						'status'	=> false,
						'message'	=> 'Please select at least one job group to send to production.'
					);
				}

				# Get Work Order Mail Date
				#``````````````````````````````````````````````````````````````````````````
				define( '_VALID_RBS' , '1');
				define( '_VALID_MOS' , '1');
				
				require_once (SF_ROOT_DIR . '/classes/config.inc.php');
				require_once (SF_ROOT_DIR . '/classes/class.workorder_objects.php');
				
				$database		= new database ($sDwSQLServer, $sDwSQLUser, $sDwSQLPass, $sDwSQLDatabase);
				$WO_database	= new database ($sWoSqlServer, $sWoSqlUser, $sWoSqlPass, $sWoSqlDatabase);
				$IntegrityCheck	= 0; #2 = 3 times



				if (! is_array($arrayJobGroupId) )
					$arrayJobGroupId = array($arrayJobGroupId);
		
				foreach ($arrayJobGroupId as $JobGroupId)
				{
						$Us2JobGroup = Us2JobGroupPeer::retrieveByPk ($JobGroupId);
						if(! $Us2JobGroup) die("Error: Job Group doesn't exist");

						# Do this so we don't create mailing records....
						$printRecord = $maxRecord;
						if( strpos($Us2JobGroup->getWoNumber(), 'GS_SAMP') !== false)
							$printRecord = 888888;

							
							
						$uProduceCsvFile	= $Us2JobGroup->getuProduceCsvFile();
						$RecipientCsvFile	= $Us2JobGroup->getRecipientCsvFile();


						$CMasterClient				= new TblMasterClients($WO_database);
						
						if ($CMasterClient->GetByClientCode($Us2JobGroup->getWoNumber()))
						{
							$ClientId = $CMasterClient->idclient;
						}
						
						$CTblWorkOrderMailDates		= new TblWorkOrderMailDates($WO_database,$ClientId);
												
						if ($CTblWorkOrderMailDates->GetByWorkOrder($Us2JobGroup->getWoNumber())   )
						{
							$mailDate = date('n/d/y', strtotime($CTblWorkOrderMailDates->dtmail));
						}
						else
						{
							$mailDate = date('n/d/y');
						}
						
						if($mailDate=='12/31/1969' || $mailDate=='12/31/69')
							die("*THERE IS NO MAIL DATE SET FOR THIS ORDER. PLEASE CONTACT IT DEPT.");


						# Re-create the uProduce CSV file in case one doesn't exist
						# or the recipient list file is replaced with another one.
						
						/*`
						` Use the handwriting csv file if this job is handwriting else use the original one
						`````````````````````````````````````````````````````````````````````````````````*/
						if($Us2JobGroup->getHandwritingId() > 0)
						{
							#$Us2JobGroup->setuProduceCsvFile( $Us2JobGroup->getHandwritingUproduceCsvFile() );
							
							$Handwriting = HandwritingPeer::retrieveByPk($Us2JobGroup->getHandwritingId());
							if($Handwriting->getCompleteYn()!='Y')
								return array (
									'status'	=> false,
									'message'	=> "Error: The variable handwriting image process is not yet completed for job group $JobGroupId."
								);
					
						}
						
						$LastFileMD5 = '';
						
						for($ic=0; $ic<=$IntegrityCheck; $ic++)
						{
							if($RenderEngine=='3.0')	self::GenerateuProduceCsvFile ($JobGroupId, $RecipientCsvFile, $printRecord, $blankRecord, $arrayOrderProductGroupName, $mailDate, $Us2JobGroup->getWoNumber());
							else						self::CreateuProduceCsvFile ($JobGroupId, $RecipientCsvFile, $printRecord, $blankRecord, $arrayOrderProductGroupName, $mailDate);
	
							# Reload just in case we had to re-create uProduce CSV file. (get new filename)
							$Us2JobGroup 	= Us2JobGroupPeer::retrieveByPk ($JobGroupId);
							$CsvFile		= $Us2JobGroup->getuProduceCsvFile();
							$pathinfo 		= pathinfo($CsvFile);
							$filename 		= $pathinfo['basename'];
							$md5			= md5_file($CsvFile);

							if(! $LastFileMD5) $LastFileMD5 = $md5;
							if($LastFileMD5 != $md5)
							{
								return array (
									'status'	=> false,
									'message'	=> 'The production engine cannot produce consistent output for this job. Please contact the IT dept.<p><br>'
								);
								die("** AN ERROR HAVE OCCURRED, PLEASE CONTACT THE IT DEPT **");	
							}
						}					
						
						# Check to see if this job group/uProduce doc already have production properties set.
						# If not, return an error.
						$uProduceDocId = $Us2JobGroup->getuProduceDocId();


						$isExist = Us2SheetSpecsPeer::LoadByDocId ($uProduceDocId);
						if (! $isExist)
						{
							return array (
								'status'	=> false,
								'message'	=> 'The production specs for one or more product you selected for production
								doesn\'t exist. To fix this problem, go to Global Setting and set the specs.<p><br>'
							);
						}						
						
						# Transfer the new uProduce CSV file to the uProduce server
						# Otherwise, uProduce wont be able to access this file.
						self::SendFile2 ($From = $Us2JobGroup->getUproduceCsvFile() );


						if ($printRecord==999999)
						{
							$SubmitCount = $Us2JobGroup->getSubmitCount();
							$SubmitCount+=1;
						}
						else
							$SubmitCount = 'SAMPLE';
										
						# Set the output filename as the WO NUMBER 
						$outputName = $Us2JobGroup->getWoNumber() . "_$SubmitCount";
						
						# If we're doing samples, use the group name
						if(strtoupper($Us2JobGroup->getWoNumber())=='SAMPLE')
							$outputName = $Us2JobGroup->getGroupName();
						
						# Take out funky characters else it will crash xmpie (4/22/2010)
						$outputName = str_replace('*', '', $outputName);
						

						#$xPath = 'E:\\XMPie\\uStore\\App\\CustomerApp\\uStoreShared\\JobAggregation\\MasterAggregation\\';
						$xPath = XMPIE_AGGREGATION_PATH;
						#$xPath = 'E:\\XMPie\\uStore\\JobAggregation\\';
						

						# Send this job to production
						# Return job id if successful
						if($JobId != 3617)
							$JobId = self::SendToProduction ($Us2JobGroup->getuProduceDocId(), "{$xPath}$filename", $outputType, $outputName, $inCopyDestination);


						# CREATE JPG
						//self::SendToProduction ($Us2JobGroup->getuProduceDocId(), "E:\\XMPie\\uStore\\App\\CustomerApp\\uStoreShared\\JobAggregation\\MasterAggregation\\$filename", $outputType='JPG', "{$outputName}_LIVE_PREVIEW", $inCopyDestination='');


						if (! $JobId) die("Error when sending to production");
						
						if ($printRecord==999999)
							$Us2JobGroup->setSubmitCount ($SubmitCount);
						
						$Us2JobGroup->setuProduceHandlingJobId ($JobId);
						#$Us2JobGroup->setOrderHandlingStatusId (4); # PRODUCTION IN PROGRESS
						$Us2JobGroup->save();
						
				}
		
			}			
			

			/**
			* Send job to production as purl
			*********************************************************************************/
			public static function SendOrderToPurl ($OrderProductId, $outputType='JPG', $blankRecord=1, $maxRecord=888888)
			{
				if (! $OrderProductId) return false;


				$Us2OrderProduct 	= Us2OrderProductPeer::retrieveByPk ($OrderProductId);
				if(! $Us2OrderProduct) die("Error: Order Product doesn't exist");
				
				$ProductId			= $Us2OrderProduct->getProductId();
				$ProductTemplateId	= Us2ProductPeer::GetProductTemplateId ($ProductId);
				$uProduceDocId		= Us2ProductTemplatePeer::GetuProduceDocId ($ProductTemplateId);
				

				# Re-create the uProduce CSV file in case one doesn't exist
				# or the recipient list file is replaced with another one.
				$uProduceCsvFile = self::CreateuProduceCsvFile ('', $Us2OrderProduct->getFlatCsvFilePath(), $maxRecord, $blankRecord, $arrayOrderProductGroupName, $mailDate);

				$pathinfo = pathinfo ($uProduceCsvFile);
				$filename = $pathinfo['basename'];	
											
				$isExist = Us2SheetSpecsPeer::LoadByDocId ($uProduceDocId);
				if (! $isExist) return false;


				# Transfer the new uProduce CSV file to the uProduce server
				# Otherwise, uProduce wont be able to access this file.
				self::SendFile2 ($From = $uProduceCsvFile);

				# Remove temporary file we just sent
				unlink($uProduceCsvFile);
				
				# Set the output filename as the WO NUMBER 
				$outputName = 'purl_'.time();

				# Send this job to production
				# Return job id if successful
				$JobId = self::SendToProduction ($uProduceDocId, XMPIE_AGGREGATION_PATH."$filename", $outputType, $outputName, $inCopyDestination);

						
				if (! $JobId) die("Error when sending to production");
				return $JobId;
			}
			
					
			/**
			* Get final dial name and value array
			*********************************************************************************/
			public static function GetFinalDialValue ($ProductTemplateId=0, $ProductId=0, $CustomerId=0, $OrderProductId=0, $GroupName='')
			{
				$arrayHeader		= array('RI_PrimaryField'=>1);	
				$arrayDialValue		= array();
				$arrayuProduceValue	= array();
				
				# Get dial names and type
				# (1) Get all the uProduce dial header for this product template
				$arrayDialType 	= Us2ProductTemplateDialPeer::GetuProduceNameAndType ($ProductTemplateId);
				$arrayHeader	= array_merge($arrayHeader, $arrayDialType);
				
				# (2) Get all the default dial values for this template
				# Get all the dials for this product template
				# Get name and default value
				$arrayDial = Us2ProductTemplateDialPeer::GetTemplateDefaultAsset ($ProductTemplateId);
				$arrayDialValue = $arrayDial;

				# (3) Get all the default dial values for this product
				# Get product default dial value
				$arrayDial = Us2ProductDialPeer::GetProductDefaultAsset ($ProductId);
				if (!$arrayDial) $arrayDial = array();
				$arrayDialValue = array_merge($arrayDialValue, $arrayDial);

				# (4) Get all the default dial values for this customer
				# Get customer default dial value
				$arrayDial = Us2ProductCustomerDialPeer::GetCustomerDefaultAsset ($CustomerId, $ProductId, $GroupName);
				if (!$arrayDial) $arrayDial = array();
				$arrayDialValue = array_merge($arrayDialValue, $arrayDial);

				# (-) Get all the dial values for this order
				# Get order dial values
				$arrayDial = Us2OrderProductDialValuePeer::GetDialValues ($OrderProductId);
				if (!$arrayDial) $arrayDial = array();
				$arrayDialValue = array_merge($arrayDialValue, $arrayDial);		



				foreach($arrayHeader as $uProduceDialName => $headerType)
				{
					$dialValue = $arrayDialValue["$uProduceDialName"];
					
					if($headerType==2)
						$dialValue = Us2ImagePeer::GetFullImagePathById($dialValue);
					
					$arrayuProduceValue["$uProduceDialName"] = $dialValue;
				}
				
				return $arrayuProduceValue;
			}

			
			/**
			* CreateTrackingCoupon
			*********************************************************************************/
			public static function CreateTrackingCoupon($MailHistoryId, $CustomerBarcode, $CouponNumber, $arrayFinalOrderValue)
			{
				$arrayCouponData = array(
					1 => array('01', 'CPN_TXT1', 'CPN_TXTB1', 'OPT1'),
					2 => array('02', 'CPN_TXT2', 'CPN_TXTB2', 'OPT2'),
					3 => array('03', 'CPN_TXT3', 'CPN_TXTB3', 'OPT3'),
					4 => array('04', 'CPN_TXT4', 'CPN_TXTB4', 'OPT4'),
					5 => array('05', 'CPN_TXT5', 'CPN_TXTB5', 'OPT5'),
					6 => array('06', 'CPN_TXT6', 'CPN_TXTB6', 'OPT6'),
				);

				$CouponDropId	= 0;
				$CouponBarcode	= $arrayCouponData["$CouponNumber"][0];
				$CouponName		= $arrayFinalOrderValue[  $arrayCouponData["$CouponNumber"][1] ];
				$CouponAmount	= $arrayFinalOrderValue[  $arrayCouponData["$CouponNumber"][2] ];
				$CouponOpcode	= $arrayFinalOrderValue[  $arrayCouponData["$CouponNumber"][3] ];
								
				$arrayTrackingDetail = array (
					'coupon_drop_id'	=> $CouponDropId,
					'coupon_barcode'	=> $CouponBarcode,

					'coupon_name'		=> $CouponName,
					'coupon_amount'		=> $CouponAmount,
					'coupon_opcode'		=> $CouponOpcode
				);
								
				$arrayTrackingDetail = serialize($arrayTrackingDetail);
								

				$MailHistoryDetail = new MailHistoryDetail();
				$MailHistoryDetail->setMailHistoryId	($MailHistoryId);
				$MailHistoryDetail->setTrackingCode 	($CustomerBarcode);
				$MailHistoryDetail->setTrackingDetail 	($arrayTrackingDetail);
				$MailHistoryDetail->save();				
			}
			
			
			/**
			* GetExpirationDate
			*********************************************************************************/
			public static function GetExpirationDate($DialValue, $mailDate)
			{
				$DialValue = trim($DialValue);
				
				switch($DialValue)
				{
					case '%90':
						$DialValue = date('n/d/y', strtotime("+3 months", strtotime($mailDate)));
						break;
					case '%60':
						$DialValue = date('n/d/y', strtotime("+2 months", strtotime($mailDate)));
						break;
					case '%30':
						$DialValue = date('n/d/y', strtotime("+1 months", strtotime($mailDate)));
						break;
				}
				
				return $DialValue;			
			}
			
			
			/**
			* GetuProduceCsvData
			*********************************************************************************/
			public static function GetuProduceCsvData($mailDate, $arrayHeader, $arrayFinalOrderValue, $arrayPersonalData)
			{
				$arrayResult 			= array();
				$arrayBogusVehicleMake	= array('vehicle', 'unknown');
					
					
				foreach ($arrayHeader as $uProduceDialName => $DialType)
				{	
					$DialValue = $arrayFinalOrderValue["$uProduceDialName"];

					# If data exist for this recipient, use this instead of the product value
					if ($arrayPersonalData["$uProduceDialName"]) $DialValue = $arrayPersonalData["$uProduceDialName"];
															
					switch ($uProduceDialName)
					{
						case 'FIRST':	$DialValue = $arrayPersonalData['FirstName'];		break;
						case 'LAST':	$DialValue = $arrayPersonalData['LastName'];		break;													
						case 'NAME':	$DialValue = $arrayPersonalData['FullName'];		break;
						case 'ADDRESS':	$DialValue = $arrayPersonalData['Address'];			break;
						case 'CITY':	$DialValue = $arrayPersonalData['City'];			break;
						case 'ST':		$DialValue = $arrayPersonalData['State'];			break;
						case 'ZIP':		$DialValue = $arrayPersonalData['Zip'];				break;
						case 'BARCODE':	$DialValue = $arrayPersonalData['Barcode'];			break;
						case 'ENDORSE':	$DialValue = $arrayPersonalData['Endorse'];			break;
						case 'GC_SEQ':	$DialValue = $arrayPersonalData['CustomerBarcode'];	break;
						case 'MSEQ':	$DialValue = $arrayPersonalData['Matchcode'];		break;
						case 'SEQ':		$DialValue = $arrayPersonalData['Seq'];				break;
						
						case 'EXP_DATE1':
						case 'EXP_DATE2':
						case 'EXP_DATE3':
						case 'EXP_DATE4':
							$DialValue	= self::GetExpirationDate($DialValue, $mailDate);										
							break;
																													
						case 'EXP_DATE6': # WO MAIL DATE
							if (trim($DialValue)=='%') $DialValue = $mailDate;
							break;

						case 'CPN_TXT1':
							if (!$DialValue) break;
							$CustomerBarcode			= $arrayPersonalData['CUSTOMER_BARCODE'];
							$arrayPersonalData['F5'] 	= "{$CustomerBarcode}01";
							self::CreateTrackingCoupon($MailHistoryId, $arrayPersonalData['F5'], 1, $arrayFinalOrderValue);
							break;
						case 'CPN_TXT2':
							if (!$DialValue) break;
							$CustomerBarcode			= $arrayPersonalData['CUSTOMER_BARCODE'];
							$arrayPersonalData['F6'] 	= "{$CustomerBarcode}02";
							self::CreateTrackingCoupon($MailHistoryId, $arrayPersonalData['F6'], 2, $arrayFinalOrderValue);
							break;						
						case 'CPN_TXT3':
							if (!$DialValue) break;
							$CustomerBarcode			= $arrayPersonalData['CUSTOMER_BARCODE'];
							$arrayPersonalData['F7'] 	= "{$CustomerBarcode}03";
							self::CreateTrackingCoupon($MailHistoryId, $arrayPersonalData['F7'], 3, $arrayFinalOrderValue);
							break;						
						case 'CPN_TXT4':
							if (!$DialValue) break;
							$CustomerBarcode			= $arrayPersonalData['CUSTOMER_BARCODE'];
							$arrayPersonalData['F8'] 	= "{$CustomerBarcode}04";
							self::CreateTrackingCoupon($MailHistoryId, $arrayPersonalData['F8'], 4, $arrayFinalOrderValue);
							break;						
						case 'CPN_TXT5':
							if (!$DialValue) break;
							$CustomerBarcode			= $arrayPersonalData['CUSTOMER_BARCODE'];
							$arrayPersonalData['F9'] 	= "{$CustomerBarcode}05";
							self::CreateTrackingCoupon($MailHistoryId, $arrayPersonalData['F9'], 5, $arrayFinalOrderValue);
							break;						
						case 'CPN_TXT6':
							if (!$DialValue) break;
							$CustomerBarcode			= $arrayPersonalData['CUSTOMER_BARCODE'];
							$arrayPersonalData['F10'] 	= "{$CustomerBarcode}06";
							self::CreateTrackingCoupon($MailHistoryId, $arrayPersonalData['F10'], 6, $arrayFinalOrderValue);
							break;
							
						
						case 'YEAR':
						case 'MAKE':
						case 'MAKE2':
						case 'YEAR_MAKE_MODEL':
						case 'MODEL':
							$DialValue = trim(strtolower($DialValue));
							
							if(in_array($DialValue, $arrayBogusVehicleMake)) $DialValue = '';
							
							$DialValue = str_replace('&amp;', '&', $DialValue);
							$DialValue = ucwords($DialValue);
							$DialValue = str_ireplace($arrayBogusVehicleMake, '', $DialValue);
							$DialValue = str_replace('  ', ' ', $DialValue);
							
							if($uProduceDialName=='MODEL' && !$DialValue)
								$DialValue = 'Vehicle';

							break;	
						case 'INDICIA':
							# If we're not sending to an address, dont put in the
							# indicia, probably overrun
							if (!$DialValue || $DialValue==1)
							{
								if($ClientId==114) #JETMAIL
									$DialValue = '5733';
								else
									$DialValue = '7923';
							}
							if (!$arrayPersonalData['ADDRESS_ID'])
								$DialValue = '5744'; # No Indicia Image, Blank
							break;
						case 'RI_NumberOfCopies':
							if (! $DialValue) $DialValue=1;							
							break;
					}
					






					



					# If this dial is an image, try to load the full path to the image
					# TYPE IMAGE
					if ($Headers[$uProduceDialName] == 2)
					{
						if(intval($DialValue))
						{
							$Us2Image = Us2ImagePeer::retrieveByPk ($DialValue);
							
							if ($Us2Image)
								$DialValue = $Us2Image->getValue();
						}
					}	
						
					
					###################################################
					if ( isset($StarredDials["$uProduceDialName"]) )
					{
						if (  strlen($DialValue) > $StarredDials["$uProduceDialName"] )
						{
							$StarredDials["$uProduceDialName"] = strlen($DialValue);
						}
					}
					else
					{
						$StarredDials["$uProduceDialName"] = strlen($DialValue);
					}
					
					
											
					
											
					$DialValue = str_replace('"', '""', $DialValue);
					$DialValue = str_replace("\r\n", "\n", $DialValue);

					if ($uProduceDialName == 'RI_NumberOfCopies')
					{
						$CSV .= "$DialValue,";	
					}
					else
					{
						$CSV .= "\"$DialValue\",";	
					}
					
					$arrayCSV["$uProduceDialName"] = $DialValue;								
				}
										
			}

			/**
			* Use after 5/4/2009. Store 3.0. Generate the pdf proofs for the printable product in the store
			*********************************************************************************/
			public static function GenerateProof2 ($ProductId=0, $ProofBy='', $CustomerId=0, $Us2ProductLibraryId=0, $orderProductId=0, $Us2ProductRevisionId=0)
			{
				@ob_end_flush();
				echo '<!-- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -->';
				echo '<style type="text/css">table { font-family:verdana; font-size:10px; color:#333333; }</style>';
				echo '
					<table cellspacing="0" cellpadding="0" border="0" style="height:100%; width:100%">
					<tr>
						<td align="center" valign="middle">
							<div id="main_loading"><img src="/images/common/loading.gif"><p><br><div id="loading_message">Generating preview, please wait...</div><span id="endTime">0.0</span> seconds elapsed</div>
						</td>
					</tr>
					</table>	
						
					<script type="text/javascript">
						var startTime	= new Date();
						function currentTime()
						{
						  var a=Math.floor((new Date()-startTime)/100)/10;
						  if (a%1==0) a+=".0";
						  document.getElementById("endTime").innerHTML=a;
						}
						
						var loadTime	= setInterval("currentTime()",100);
					</script>
				';
			
				flush();
				
				/*`
				` Generate the sample proof data
				````````````````````````````````````````````````````````````````````*/
				$data = Us2ProductLastProofOptionPeer::CreateProofDataFromOptions(array('makes'=>array('Toyota'=>'Camry')), 0, $orderProductId);

				/*`
				` Create a temporary uProduce CSV file
				````````````````````````````````````````````````````````````````````*/
				$uProduceCsvFile = SF_ROOT_DIR."/temp/data/";
			
				if(! file_exists($uProduceCsvFile))	mkdir($uProduceCsvFile, 0777) or die("Error: Cannot create directory $uProduceCsvFile");
				$uProduceCsvFile .= date('Ymd_'). md5(microtime(true)).'_'.mt_rand(9,999999999).'_'.mt_rand(9,999999999). '.csv';
				
				$file = fopen($uProduceCsvFile, 'w') or die("Error: Can't open file on server for processing");
				if( fwrite($file, $data)===false ) die ("Error: Can't write data into file");
				fflush($file); fclose($file);
				


				$result = self::GetProofByCsv($ProductId, $CustomerId, $uProduceCsvFile, $Us2ProductLibraryId, $Us2ProductRevisionId, $Limit=8000, $isProduction=false, $ConvertToJpg=false, $orderProductId);

				if(!$result || $result['error'] || !$result['pdf'])
				{
					echo '<script type="text/javascript">
						element = document.getElementById ("main_loading");
						element.innerHTML = \'Failed, please try again...\';
						clearTimeout(loadTime);
						clearInterval(loadTime);
					</script>';					
				}
				else
				{
					if($orderProductId)
					{
						# Save this proof for future reference
						$Us2OrderProof = new Us2OrderProof();
						$Us2OrderProof->setUs2OrderProductId ($orderProductId);
						$Us2OrderProof->setuProduceJobId ($result['uproduce_job_id']);
						$Us2OrderProof->setProofUrl ($result['pdf']);
						$Us2OrderProof->setLastUpdatedDate (date('Y-m-d H:i:s'));
						$Us2OrderProof->save();
						
						# We're up to date on the proof
						Us2OrderProductPeer::UpdateReproofYn ($orderProductId, $ReproofYn='N');	
					}
													
					echo "<script type=\"text/javascript\">
						element = document.getElementById (\"main_loading\");
						element.innerHTML = 'Done. Your proof is now ready for download.<p><a href=\"$result[pdf]\">Click here</a> if your browser does not automatically prompt you to download the pdf proof.';
						clearTimeout(loadTime);
						clearInterval(loadTime);					
						window.location = '$result[pdf]';
					</script>";						
				}
													

				flush();
				exit;													
			}
			

			/**
			* Use after 5/4/2009. Store 3.0. Generate the pdf proofs for the printable product in the store
			*********************************************************************************/
			public static function GenerateProof2_DELETE ($ProductId=0, $ProofBy='', $CustomerId=0, $Us2ProductLibraryId=0, $orderProductId=0, $Us2ProductRevisionId=0)
			{
					@ob_end_flush();
					echo '<!-- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -->';
					echo '
						<style type="text/css">
							table { font-family:verdana; font-size:10px; color:#333333; }
						</style>
					';
						
					echo '
						<table cellspacing="0" cellpadding="0" border="0" style="height:100%; width:100%">
						<tr>
							<td align="center" valign="middle">
								<div id="main_loading"><img src="http://gateway.printhd.us/admin/images/common/loading.gif"><p><br><div id="loading_message">Generating preview, please wait...</div><span id="endTime">0.0</span> seconds elapsed</div>
							</td>
						</tr>
						</table>	
							
						<script type="text/javascript">
							var startTime	= new Date();
							function currentTime()
							{
							  var a=Math.floor((new Date()-startTime)/100)/10;
							  if (a%1==0) a+=".0";
							  document.getElementById("endTime").innerHTML=a;
							}
							
							var loadTime	= setInterval("currentTime()",100);
						</script>
					';
				
					flush();
				
				
				
					$arrayDialValue	= array();
				
					if ($ProductId)
					{
						$Us2Product 		= Us2ProductPeer::retrieveByPk ($ProductId);
						$ProductTemplateId 	= $Us2Product->getUs2ProductTemplateId();
						$uProduceDocId		= Us2ProductTemplatePeer::GetuProduceDocId ($ProductTemplateId);
					}
					else
						die("Error proofing product, no product is selected. Please try again later.");
						
					if($CustomerId)
						$ClientId = CustomerPeer::GetClientByCustomer($CustomerId);


					require_once ("/var/www/web3/lib/aggregator.class.php");
					$arrayRecipient = array(
						array(
						'first'				=> 'Michelle',
						'last'				=> 'Williams-Washington',
						'full_name'			=> 'Michelle Williams-Washington',
						'address'			=> '9427 Corporate Lake Dr',
						'city'				=> 'Tampa',
						'state'				=> 'FL',
						'zip'				=> '33634',
						'vehicle_make' 		=> 'Toyota',
						'vehicle_model' 	=> 'Camry',
						'vehicle_year' 		=> '2008',
						'vehicle_mileage' 	=> '15000',
						'vehicle_vin'		=> 'JT3GN86R7W0058429',
						'seq'				=> '10210512B2',
						'purl_code'			=> 'X1234',
						'purl_name'			=> 'MichelleWilliamsWashington',
						'matchcode'			=> '123456',
						'barcode'			=> '/335407340803/',
						),
					);
					
					#$arrayOrderProductGroupName[10] = "GROUP TO PROOF";
					$arrayProofProperty = array(
						'ProductId' 		=> $ProductId,
						'CustomerId'		=> $CustomerId,
						'ProductTemplateId'	=> $ProductTemplateId,
						'ClientId'			=> $ClientId,
						'uProduceDocId'		=> $uProduceDocId
					);
					
				

					$Aggregation = new Aggregator();
					$Aggregation->SetProductLibraryId($Us2ProductLibraryId);	
					#$Aggregation->SetDisplayWatermark(true);		
					$Aggregation->SetRecordLimit(1);
					$Aggregation->SetMailDate(date('m/d/Y'));
					$Aggregation->SetBlankRecord(0);
					$Aggregation->SetProofOrderProductId($orderProductId);
					$Aggregation->InitProofData($arrayRecipient, $orderProductId);
					$Aggregation->PreloadOrderValues($arrayOrderProductGroupName=array(), $arrayProofProperty);
					$Aggregation->CreateRecipientRecord();
					$Aggregation->GenerateFinalValue();
					$arrayDialValue = $Aggregation->CreateFinalProofArray();

#echo '<pre>';
#print_r($arrayProofProperty);
#print_r($Aggregation); exit;		
					$uProduceCsvFile 	= $Aggregation->CreateFinalPrintFile();	
					#$xPath 				= 'E:\\XMPie\\uStore\\App\\CustomerApp\\uStoreShared\\JobAggregation\\MasterAggregation\\';
					$xPath				= XMPIE_AGGREGATION_PATH;
					$pathinfo 			= pathinfo($uProduceCsvFile);
					$filename 			= $pathinfo['basename'];

					# Transfer the new uProduce CSV file to the uProduce server
					# Otherwise, uProduce wont be able to access this file.
					self::SendFile2($uProduceCsvFile);					
                                        
                                        
					/**
					* Generate proof
					***************************************************************************************/	
					#$JobId = self::Proof ($uProduceDocId, $OutputType='PDFO', $arrayDialValue);
					$JobId = self::SendToProduction($uProduceDocId, "{$xPath}$filename", $outputType='PDFX', $outputName='store_proof_'.time().'_'.mt_rand(9,999999999), $inCopyDestination='');	
                    self::cleanUpTemp($uProduceCsvFile);


					if($JobId)
					{
						$Status = 0;
						# 1 Waiting
						# 2 InProgress
						# 3 Completed
						# 4 Failed
						# 5 Aborting
						# 6 Aborted
						# 7 Deployed
						# 8 Suspended
						$LastMessage = '';	
						$Continue = true;	
							

						while ($Continue==true)
						{
							$Status = self::GetJobStatus ($JobId);
						
							switch ($Status)
							{
								case '1':
									$Message = 'Queued, please wait...';
									break;
								case '2':
									$Message = 'In progress, please wait...'; 
									break;
								case '3':
									$Continue=false;
									$Message = '';
		
									$Path = self::GetFolderPath ($JobId);
									$Files = self::GetOutputResult ($JobId);
									
									foreach ($Files as $File)
									{
										$HTML.= "<img src=\"$Path$File\"><p><br>";
									}
									

									
									$PDF 			= file_get_contents("{$Path}{$Files}");
									$fileLocation 	= '';
									if($PDF)
									{
										$fileLocation = SF_ROOT_DIR.'/web/proofs/revision/' . md5(time()).'_'.mt_rand(9,999999999).'_'.mt_rand(9,999999999). '.pdf';
										$file = fopen($fileLocation, 'w+');
										fwrite($file, $PDF);
										fclose($file);
										
										$fileLocation = str_replace('/var/www/web3/web/', 'http://gateway.printhd.us/', $fileLocation);
									}
																			
									# If proofing with product library, save pdf url
									if($Us2ProductLibraryId) {
										$Us2ProductLibrary = Us2ProductLibraryPeer::retrieveByPk($Us2ProductLibraryId);
										$Us2ProductLibrary->setPdfProofUrl("$fileLocation");
										$Us2ProductLibrary->setRegenPreviewYn('Y');
										$Us2ProductLibrary->save();
									}

									if($Us2ProductRevisionId)
									{
										$Us2ProductRevision = Us2ProductRevisionPeer::retrieveByPk($Us2ProductRevisionId);
										$Us2ProductRevision->setViewedProofUrl("$fileLocation");
										$Us2ProductRevision->save();
									}
									
									
																		
									if($orderProductId)
									{
										# Save this proof for future reference
										$Us2OrderProof = new Us2OrderProof();
										$Us2OrderProof->setUs2OrderProductId ($orderProductId);
										$Us2OrderProof->setuProduceJobId ($JobId);
										$Us2OrderProof->setProofUrl ("$fileLocation");
										$Us2OrderProof->setLastUpdatedDate (date('Y-m-d H:i:s'));
										$Us2OrderProof->save();
										
										# We're up to date on the proof
										Us2OrderProductPeer::UpdateReproofYn ($orderProductId, $ReproofYn='N');	
									}								
									
				
									echo '<script type="text/javascript">
										element = document.getElementById ("main_loading");
										element.innerHTML = \'Done\'
										clearTimeout(loadTime);
										clearInterval(loadTime);
									</script>';
									flush();	
																						
									if (true)#$this->Type == 'PDFO'
									{
										//redirect to pdf
									echo '<script type="text/javascript">
										window.location = "'.$Path.$Files.'"
									</script>';	
									}
				
									#print_r($File);
									break;
								default:
									$Continue=false;
									$Message = 'Failed, please try again...';
									break;
							}
							
							if($Continue==false)
							{
									echo '<script type="text/javascript">
										clearTimeout(loadTime);
										clearInterval(loadTime);
									</script>';	
									flush();
									
									if($Status >= 3)
									{
										echo '<script type="text/javascript">
											element = document.getElementById ("main_loading");
											element.innerHTML = \'Ooops!<p>'. $Message .'\'
										</script>';	
										flush();
									}						
							}
							
							if ($LastMessage != $Message && $Status!=3)
							{
								echo '<script type="text/javascript">
									element = document.getElementById ("loading_message");
									element.innerHTML = "'.$Message.'"
								</script>';

								flush();
							}
							
							$LastMessage = $Message;
							
							sleep(3);
						}
				
					}
					else
					{
						echo '<script type="text/javascript">
							element = document.getElementById ("loading_message");
							element.innerHTML = "Error trying to generate preview, please try again later..."
							clearTimeout(loadTime);
							clearInterval(loadTime);
						</script>';
						flush();		
					}
			}
			
			/**
			* GetPrintFileFromSampleProofCsv 
			*********************************************************************************/
			public static function GetPrintFileFromSampleProofCsv($ProductId, $CustomerId, $ProofCsvFile, $Us2ProductLibraryId=0, $Us2ProductRevisionId=0, $Limit=8000, $isProduction=false, $OrderProductId=0)
			{
					if($ProductId)
					{
						$Us2Product 		= Us2ProductPeer::retrieveByPk ($ProductId);
						$ProductTemplateId 	= $Us2Product->getUs2ProductTemplateId();
						$uProduceDocId		= Us2ProductTemplatePeer::GetuProduceDocId ($ProductTemplateId);
					}
					else
						return array('error'=>'Error proofing product, no product is selected. Please try again later.');
					
					if($CustomerId)
						$ClientId = CustomerPeer::GetClientByCustomer($CustomerId);
						
									
					$isExist = Us2SheetSpecsPeer::LoadByDocId ($uProduceDocId);
					if (! $isExist)
					{
						return array('error' => 'Sorry! We cannot proof this product yet.<p>
							<b>Here\'s why:</b><br>
							The production specs for one or more product you selected for production
							doesn\'t exist.<p>
							<b>What you need to do:</b><br>
							To fix this problem, go to Global Setting and set the specs.<p><br>'
						);
					}

					require_once("/var/www/web3/lib/aggregator.class.php");
					
					$arrayProofProperty = array(
						'ProductId' 		=> $ProductId,
						'CustomerId'		=> $CustomerId,
						'ProductTemplateId'	=> $ProductTemplateId,

						'ClientId'			=> $ClientId,
						'uProduceDocId'		=> $uProduceDocId
					);
					
					$Aggregation = new Aggregator();
					
					if($isProduction)
						$Aggregation->SetProductionMode(true);
					
					$Aggregation->SetProductLibraryId($Us2ProductLibraryId);		
					$Aggregation->SetRecordLimit($Limit);
					$Aggregation->SetMailDate(date('m/d/Y'));
					$Aggregation->SetBlankRecord(0);
					$Aggregation->SetRenderType("PROOF");
					
					if($OrderProductId)
						$Aggregation->SetProofOrderProductId($OrderProductId);
					
					$Aggregation->InitRecipientData("$ProofCsvFile");
					$Aggregation->PreloadOrderValues($arrayOrderProductGroupName=array(), $arrayProofProperty);
					$Aggregation->CreateRecipientRecord();				
					$Aggregation->GenerateFinalValue();

					$uProduceCsvFile = $Aggregation->CreateFinalPrintFile();
					
					return array('file'=>$uProduceCsvFile, 'doc_id'=>$uProduceDocId);
			}
			
			/**
			*
			*********************************************************************************/
			public static function GetPDFByJobId($JobId, $WaitForResult=true, $Us2ProductLibraryId=0, $Us2ProductRevisionId=0, $ConvertToJpg=false, $isTestOnly=false)
			{
				if($JobId)
				{
					$arrayPost = array(
						'key'				=> '10OYwla0238JKasd897123jkaDALPQAv',
						'action'			=> 'GetJobResult',
						'JobId'				=> $JobId,
						'ConvertToJpg'		=> $ConvertToJpg,
						'WaitForResult'		=> $WaitForResult,
						'isTestOnly'		=> $isTestOnly
					);
	
					$Curl = curl_init();
					curl_setopt($Curl, CURLOPT_URL, "http://img4.printhd.us/service/xmpie.php");
					curl_setopt($Curl, CURLOPT_POST, 6);
					curl_setopt($Curl, CURLOPT_POSTFIELDS, $arrayPost);
					curl_setopt($Curl, CURLOPT_BINARYTRANSFER, 1);
					curl_setopt($Curl, CURLOPT_RETURNTRANSFER, 1); 
					curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 0); 
					curl_setopt($Curl, CURLOPT_TIMEOUT, 1200); # 20 minutes 
					$Result = curl_exec($Curl);
					curl_close($Curl);
					
					try { $response = json_decode($Result, true); } catch(Exception $e){ }
					
					if(! is_array($response) || $response['success']==false || !$response['pdf']) 
					{
						return array('error' => 'Failed, please try again...');
					}
					else
					{
						return array(
							#'file_location' => $fileLocation,
							'server' 	=> $response['server'],
							'pdf' 		=> $response['pdf'],
							'jpgs'		=> $response['jpgs']
						);						
					}
																		
								# If proofing with product library, save pdf url
//								if($Us2ProductLibraryId) {
//									$Us2ProductLibrary = Us2ProductLibraryPeer::retrieveByPk($Us2ProductLibraryId);
//									$Us2ProductLibrary->setPdfProofUrl("$webLocation");
//									$Us2ProductLibrary->setRegenPreviewYn('Y');
//									$Us2ProductLibrary->save();
//								}
//
//								# If product revision, save pdf url
//								if($Us2ProductRevisionId)
//								{
//									$Us2ProductRevision = Us2ProductRevisionPeer::retrieveByPk($Us2ProductRevisionId);
//									$Us2ProductRevision->setViewedProofUrl("$webLocation");
//									$Us2ProductRevision->save();
//								}

				}
			}
			
			/**
			* Create Xmpie Job
			*********************************************************************************/
			public static function CreateJobByCsv($ProductId, $CustomerId, $ProofCsvFile, $Us2ProductLibraryId=0, $Us2ProductRevisionId=0, $Limit=8000, $isProduction=false, $OrderProductId=0, $isTestOnly=false)
			{
				$result 			= self::GetPrintFileFromSampleProofCsv($ProductId, $CustomerId, $ProofCsvFile, $Us2ProductLibraryId, $Us2ProductRevisionId, $Limit, $isProduction, $OrderProductId);
				$uProduceCsvFile	= $result['file'];
				$uProduceDocId		= $result['doc_id'];

				if(!$uProduceCsvFile || !$uProduceDocId || $result['error']) {
					return array('error' => $result['error']);
				}

				# Transfer the new uProduce CSV file to the uProduce server
				# Otherwise, uProduce wont be able to access this file.
				$success = self::SendFile2($uProduceCsvFile, $halt=false);
		
				if($success==false)
					return array('error'=>'Internal System Error: Unable to save uploaded file into remote server.');
					
				$pathinfo 	= pathinfo($uProduceCsvFile);
				$filename 	= $pathinfo['basename'];	
				$xPath 		= XMPIE_AGGREGATION_PATH;

				/**
				* Send this job to production, return job id if successful
				***************************************************************************************/					
				$JobId = self::SendToProduction($uProduceDocId, "{$xPath}$filename", $outputType='PDFX', $outputName='store_proof_'.time(), $inCopyDestination='', $isTestOnly);

				return array('job_id' => $JobId);
			}
			
			/**
			*
			*********************************************************************************/
			public static function GetProofByCsv($ProductId, $CustomerId, $ProofCsvFile, $Us2ProductLibraryId=0, $Us2ProductRevisionId=0, $Limit=8000, $isProduction=false, $ConvertToJpg=false, $OrderProductId=0, $isTestYn=false)
			{
				$result = self::CreateJobByCsv($ProductId, $CustomerId, $ProofCsvFile, $Us2ProductLibraryId, $Us2ProductRevisionId, $Limit, $isProduction, $OrderProductId, $isTestYn);

				if($result['error']) 	return $result;
				if(!$result['job_id'])	return array('error'=>'Server down. Error trying to generate preview, please try again later...');
	
				
				/**
				* Generate proof
				***************************************************************************************/
				#sleep(20); # No sense checking no, all we're doing is slamming the server. Let's wait 20 seconds before checking

				$response 	= self::GetPDFByJobId($result['job_id'], $WaitForResult=true, $Us2ProductLibraryId, $Us2ProductRevisionId, $ConvertToJpg);
				$pdf 		= $response['pdf'];
				$jpgs		= $response['jpgs'];
				#$localLink	= $pdf['file_location'];

				if($response['error'] || !$pdf) {
					return array('error' => 'Failed, please try again...');
				}
				
				return array(
					'pdf' 				=> $pdf,
					'jpgs'				=> $jpgs,
					'uproduce_job_id'	=> $result['job_id']
				);
			}
			
			/**
			* GetProofByCsvWithJpgPreview
			*********************************************************************************/
			public static function GetProofByCsvWithJpgPreview($ProductId, $CustomerId, $ProofCsvFile, $Us2ProductLibraryId=0, $Us2ProductRevisionId=0, $isProduction=false)
			{
				$result = self::GetProofByCsv($ProductId, $CustomerId, $ProofCsvFile, $Us2ProductLibraryId, $Us2ProductRevisionId, 8000, $isProduction, $ConvertToJpg=true);
				//$result = self::GetProofByCsv($ProductId, $CustomerId, $ProofCsvFile, $Us2ProductLibraryId, $Us2ProductRevisionId, 8000, true, $ConvertToJpg=true);
				if($result['error'] || !$result['pdf'])
					return array('error' => 'Failed, please try again...');

				#$jpgs = self::ConvertPDFToJpeg($result['file_location'], SF_ROOT_DIR.'/web/proofs/temp_proof_jpgs/');
				#if(!$jpgs) $jpgs = self::ConvertPDFToJpeg($result['file_location'], SF_ROOT_DIR.'/web/proofs/temp_proof_jpgs/');
				
				return array(
					'web_location' 	=> $result['pdf'],
					'file_location'	=> $result['pdf'],
					'jpgs'			=> $result['jpgs']
				);
			}
			
			/**
			* GenerateProofByCsvFile
			*********************************************************************************/
			public static function GenerateProofByCsvFile ($ProductId=0, $CustomerId=0, $ProofCsvFile, $Us2ProductLibraryId=0, $Us2ProductRevisionId=0)
			{
				@ob_end_flush();
				echo '<!-- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -->';
				echo '<style type="text/css">table { font-family:verdana; font-size:10px; color:#333333; }</style>';
				echo '
					<table cellspacing="0" cellpadding="0" border="0" style="height:100%; width:100%">
					<tr>
						<td align="center" valign="middle">
							<div id="main_loading"><img src="/images/common/loading.gif"><p><br><div id="loading_message">Generating preview, please wait...</div><span id="endTime">0.0</span> seconds elapsed</div>
						</td>
					</tr>
					</table>	
						
					<script type="text/javascript">
						var startTime	= new Date();
						function currentTime()
						{
						  var a=Math.floor((new Date()-startTime)/100)/10;
						  if (a%1==0) a+=".0";
						  document.getElementById("endTime").innerHTML=a;
						}
						
						var loadTime	= setInterval("currentTime()",100);
					</script>
				';
			
				flush();
				
				
				$result = self::GetProofByCsv($ProductId, $CustomerId, $ProofCsvFile, $Us2ProductLibraryId, $Us2ProductRevisionId, $Limit=8000, $isProduction=false, $ConvertToJpg=false);

				if(!$result || $result['error'] || !$result['pdf'])
				{
					echo '<script type="text/javascript">
						element = document.getElementById ("main_loading");
						element.innerHTML = \'Failed, please try again...\';
						clearTimeout(loadTime);
						clearInterval(loadTime);
					</script>';					
				}
				else
				{
					echo "<script type=\"text/javascript\">
						element = document.getElementById (\"main_loading\");
						element.innerHTML = 'Done. Your proof is now ready for download.';
						clearTimeout(loadTime);
						clearInterval(loadTime);					
						window.location = '$result[pdf]';
					</script>";						
				}
													

				flush();
				exit;													
			}
						
			/**
			* GenerateProofByCsvFile
			*********************************************************************************/
			public static function GenerateProofByCsvFile_DELETE ($ProductId=0, $CustomerId=0, $ProofCsvFile, $Us2ProductLibraryId=0, $Us2ProductRevisionId=0)
			{
					if ($ProductId)
					{
						$Us2Product 		= Us2ProductPeer::retrieveByPk ($ProductId);
						$ProductTemplateId 	= $Us2Product->getUs2ProductTemplateId();
						$uProduceDocId		= Us2ProductTemplatePeer::GetuProduceDocId ($ProductTemplateId);
					}
					else
						die("Error proofing product, no product is selected. Please try again later.");
						
					if($CustomerId)
						$ClientId = CustomerPeer::GetClientByCustomer($CustomerId);
						
									
					$isExist = Us2SheetSpecsPeer::LoadByDocId ($uProduceDocId);
					if (! $isExist)
					{
						die('Sorry! We cannot proof this product yet.<p>
							<b>Here\'s why:</b><br>
							The production specs for one or more product you selected for production
							doesn\'t exist.<p>
							<b>What you need to do:</b><br>
							To fix this problem, go to Global Setting and set the specs.<p><br>'
						);
					}
							
					@ob_end_flush();
					echo '<!-- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -->';
					echo '
						<style type="text/css">
							table { font-family:verdana; font-size:10px; color:#333333; }
						</style>
					';
						
					echo '
						<table cellspacing="0" cellpadding="0" border="0" style="height:100%; width:100%">
						<tr>
							<td align="center" valign="middle">
								<div id="main_loading"><img src="/images/common/loading.gif"><p><br><div id="loading_message">Generating preview, please wait...</div><span id="endTime">0.0</span> seconds elapsed</div>
							</td>
						</tr>
						</table>	
							
						<script type="text/javascript">
							var startTime	= new Date();
							function currentTime()
							{
							  var a=Math.floor((new Date()-startTime)/100)/10;
							  if (a%1==0) a+=".0";
							  document.getElementById("endTime").innerHTML=a;
							}
							
							var loadTime	= setInterval("currentTime()",100);
						</script>
					';
				
					flush();
				

				
					$arrayDialValue	= array();
					require_once ("/var/www/web3/lib/aggregator.class.php");
					$arrayRecipient = array(
						array(
						'first'				=> 'Michelle',
						'last'				=> 'Williams-Washington',
						'full_name'			=> 'Michelle Williams-Washington',
						'address'			=> '9427 Corporate Lake Dr',
						'city'				=> 'Tampa',
						'state'				=> 'FL',
						'zip'				=> '33634',
						'vehicle_make' 		=> 'Toyota',
						'vehicle_model' 	=> 'Camry',
						'vehicle_year' 		=> '2008',
						'vehicle_mileage' 	=> '15000',
						'vehicle_vin'		=> 'JT3GN86R7W0058429',
						'customer_barcode'	=> '10210512B2',
						'purl_code'			=> 'X1234',
						'purl_name'			=> 'MichelleWilliamsWashington',
						'matchcode'			=> '123456'
						),
					);
					
					#$arrayOrderProductGroupName[10] = "GROUP TO PROOF";
					$arrayProofProperty = array(
						'ProductId' 		=> $ProductId,
						'CustomerId'		=> $CustomerId,
						'ProductTemplateId'	=> $ProductTemplateId,
						'ClientId'			=> $ClientId,
						'uProduceDocId'		=> $uProduceDocId
					);
					
					

					$Aggregation = new Aggregator();
					$Aggregation->SetProductLibraryId($Us2ProductLibraryId);
					#$Aggregation->SetDisplayWatermark(true);			
					$Aggregation->SetRecordLimit(8000);
					$Aggregation->SetMailDate(date('m/d/Y'));
					$Aggregation->SetBlankRecord(1);
					$Aggregation->SetRenderType("PROOF");
					$Aggregation->InitRecipientData("$ProofCsvFile");
					$Aggregation->PreloadOrderValues($arrayOrderProductGroupName=array(), $arrayProofProperty);
					$Aggregation->CreateRecipientRecord();				
					$Aggregation->GenerateFinalValue();
				
		
					$uProduceCsvFile = $Aggregation->CreateFinalPrintFile();				
					#
					#if($ProductId==2642)
					#{
					#	echo $uProduceCsvFile;
					#	exit;
					#	echo '<pre>';
					#	print_r($Aggregation); exit;
					#}					

					#echo $uProduceCsvFile; flush(); exit;
							$pathinfo = pathinfo($uProduceCsvFile);
							$filename = $pathinfo['basename'];	
							
						# Transfer the new uProduce CSV file to the uProduce server
						# Otherwise, uProduce wont be able to access this file.
						self::SendFile2 ($uProduceCsvFile);

						#$xPath = 'E:\\XMPie\\uStore\\App\\CustomerApp\\uStoreShared\\JobAggregation\\MasterAggregation\\';
						$xPath = XMPIE_AGGREGATION_PATH;
						#$xPath = 'E:\\XMPie\\uStore\\JobAggregation\\';
				#echo $filename; exit;	
#$filename="8852a0b5184b7d7086c2140286b77d74_1242315044.csv";
						# Send this job to production
						# Return job id if successful
						$JobId = self::SendToProduction ($uProduceDocId, "{$xPath}$filename", $outputType='PDFX', $outputName='store_proof_'.time(), $inCopyDestination=''); 
						                  
						self::cleanUpTemp($uProduceCsvFile);
				#	print_r($Aggregation);
				#	die("---");	
				//	$Aggregation->InitProofData($arrayRecipient);
					
					
					
					
				#	$arrayDialValue = $Aggregation->CreateFinalProofArray();


					/**
					* Generate proof
					***************************************************************************************/	
					#require_once (SF_ROOT_DIR.'/lib/uProduce.class.php');
				#	$JobId = self::Proof ($uProduceDocId, $OutputType='PDFO', $arrayDialValue);
						
					if ($JobId)
					{
						$Status = 0;
						# 1 Waiting
						# 2 InProgress
						# 3 Completed
						# 4 Failed
						# 5 Aborting
						# 6 Aborted
						# 7 Deployed
						# 8 Suspended
						$LastMessage = '';	
						$Continue = true;	
							

						while ($Continue==true)
						{
							$Status = self::GetJobStatus ($JobId);
						
							switch ($Status)
							{
								case '1':
									$Message = 'Queued, please wait...';
									break;
								case '2':
									$Message = 'In progress, please wait...'; 
									break;
								case '3':
									$Continue=false;
									$Message = '';
		
									$Path = self::GetFolderPath ($JobId);
									$Files = self::GetOutputResult ($JobId);
									
									foreach ($Files as $File)
									{
										$HTML.= "<img src=\"$Path$File\"><p><br>";
									}
									
									$PDF 			= file_get_contents("{$Path}{$Files}");
									$fileLocation 	= '';
									if($PDF)
									{
										$fileLocation = SF_ROOT_DIR.'/web/proofs/revision/' . md5(time()).'_'.mt_rand(9,999999999).'_'.mt_rand(9,999999999). '.pdf';
										$file = fopen($fileLocation, 'w+');
										fwrite($file, $PDF);
										fclose($file);
										$fileLocation = str_replace('/var/www/web3/web/', 'http://gateway.printhd.us/', $fileLocation);										
									}
																			
									# If proofing with product library, save pdf url
									if($Us2ProductLibraryId) {
										$Us2ProductLibrary = Us2ProductLibraryPeer::retrieveByPk($Us2ProductLibraryId);
										$Us2ProductLibrary->setPdfProofUrl("$fileLocation");
										$Us2ProductLibrary->setRegenPreviewYn('Y');
										$Us2ProductLibrary->save();
									}

									if($Us2ProductRevisionId)
									{
										$Us2ProductRevision = Us2ProductRevisionPeer::retrieveByPk($Us2ProductRevisionId);
										$Us2ProductRevision->setViewedProofUrl("$fileLocation");
										$Us2ProductRevision->save();
									}
									
									
									
									echo '<script type="text/javascript">
										element = document.getElementById ("main_loading");
										element.innerHTML = \'Done\'
										clearTimeout(loadTime);
										clearInterval(loadTime);
									</script>';
									flush();	
																						
									if (true)#$this->Type == 'PDFO'
									{
										//redirect to pdf
									echo '<script type="text/javascript">
										window.location = "'.$Path.$Files.'"
									</script>';	
									}
				
									#print_r($File);
									break;
								default:
									$Continue=false;
									$Message = 'Failed, please try again...';
									break;
							}
							
							if($Continue==false)
							{
									echo '<script type="text/javascript">
										clearTimeout(loadTime);
										clearInterval(loadTime);
									</script>';	
									flush();
									
									if($Status >= 3)
									{
										echo '<script type="text/javascript">
											element = document.getElementById ("main_loading");
											element.innerHTML = \'Ooops!<p>'. $Message .'\'
										</script>';	
										flush();
									}						
							}
							
							if ($LastMessage != $Message && $Status!=3)
							{
								echo '<script type="text/javascript">
									element = document.getElementById ("loading_message");
									element.innerHTML = "'.$Message.'"
								</script>';

								flush();
							}
							
							$LastMessage = $Message;
							
							sleep(3);
						}
				
					}
					else
					{
						echo '<script type="text/javascript">
							element = document.getElementById ("loading_message");
							element.innerHTML = "Error trying to generate preview, please try again later..."
							clearTimeout(loadTime);
							clearInterval(loadTime);
						</script>';
						flush();		
					}
			}
			
			/**
			* 
			*********************************************************************************/
			public static function GetProofArrayByCsvFile ($ProductId=0, $CustomerId=0, $ProofCsvFile, $Us2ProductLibraryId=0, $Us2ProductRevisionId=0)
			{
					if ($ProductId)
					{
						$Us2Product 		= Us2ProductPeer::retrieveByPk ($ProductId);
						$ProductTemplateId 	= $Us2Product->getUs2ProductTemplateId();
						$uProduceDocId		= Us2ProductTemplatePeer::GetuProduceDocId ($ProductTemplateId);
					}
					else
						die("Error proofing product, no product is selected. Please try again later.");
						
					if($CustomerId)
						$ClientId = CustomerPeer::GetClientByCustomer($CustomerId);
						
									
					$isExist = Us2SheetSpecsPeer::LoadByDocId ($uProduceDocId);
					if (! $isExist)
					{
						die('Sorry! We cannot proof this product yet.<p>
							<b>Here\'s why:</b><br>
							The production specs for one or more product you selected for production
							doesn\'t exist.<p>
							<b>What you need to do:</b><br>
							To fix this problem, go to Global Setting and set the specs.<p><br>'
						);
					}
							
				
					$arrayDialValue	= array();
					require_once ("/var/www/web3/lib/aggregator.class.php");
					$arrayRecipient = array(
						array(
						'first'				=> 'Michelle',
						'last'				=> 'Williams-Washington',
						'full_name'			=> 'Michelle Williams-Washington',
						'address'			=> '9427 Corporate Lake Dr',
						'city'				=> 'Tampa',
						'state'				=> 'FL',
						'zip'				=> '33634',
						'vehicle_make' 		=> 'Toyota',
						'vehicle_model' 	=> 'Camry',
						'vehicle_year' 		=> '2008',
						'vehicle_mileage' 	=> '15000',
						'vehicle_vin'		=> 'JT3GN86R7W0058429',
						'customer_barcode'	=> '10210512B2',
						'purl_code'			=> 'X1234',
						'purl_name'			=> 'MichelleWilliamsWashington',
						'matchcode'			=> '123456'
						),
					);
					
					#$arrayOrderProductGroupName[10] = "GROUP TO PROOF";
					$arrayProofProperty = array(
						'ProductId' 		=> $ProductId,
						'CustomerId'		=> $CustomerId,
						'ProductTemplateId'	=> $ProductTemplateId,
						'ClientId'			=> $ClientId,
						'uProduceDocId'		=> $uProduceDocId
					);
					
							
					$Aggregation = new Aggregator();
					$Aggregation->SetProductLibraryId($Us2ProductLibraryId);
					#$Aggregation->SetDisplayWatermark(true);			
					$Aggregation->SetRecordLimit(8000);
					$Aggregation->SetMailDate(date('m/d/Y'));
					$Aggregation->SetBlankRecord(1);
					$Aggregation->SetRenderType("PROOF");
					$Aggregation->InitRecipientData("$ProofCsvFile");
					$Aggregation->PreloadOrderValues($arrayOrderProductGroupName=array(), $arrayProofProperty);
					$Aggregation->CreateRecipientRecord();				
					$Aggregation->GenerateFinalValue();
					#$uProduceCsvFile = $Aggregation->CreateFinalPrintFile();
					
					#echo '<pre>';
					#print_r($Aggregation);		
					#exit;		
					return $Aggregation;
			}
						
			
			/**
			* Generate the pdf proofs for the printable product in the store
			*********************************************************************************/
			public static function GenerateProof ($ProductId=0, $ProofBy='', $CustomerId=0)
			{
					@ob_end_flush();
					echo '<!-- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -->';
					echo '
						<style type="text/css">
							table { font-family:verdana; font-size:10px; color:#333333; }
						</style>
					';
						
					echo '
						<table cellspacing="0" cellpadding="0" border="0" style="height:100%; width:100%">
						<tr>
							<td align="center" valign="middle">
								<div id="main_loading"><img src="/images/common/loading.gif"><p><br><div id="loading_message">Generating preview, please wait...</div><span id="endTime">0.0</span> seconds elapsed</div>
							</td>
						</tr>
						</table>	
							
						<script type="text/javascript">
							var startTime	= new Date();
							function currentTime()
							{
							  var a=Math.floor((new Date()-startTime)/100)/10;
							  if (a%1==0) a+=".0";
							  document.getElementById("endTime").innerHTML=a;
							}
							
							var loadTime	= setInterval("currentTime()",100);
						</script>
					';
				
					flush();
				
				
				
					$Customization	= array();
					$IsImageDial	= array();
				
					if ($ProductId)
					{
						$Us2Product 		= Us2ProductPeer::retrieveByPk ($ProductId);
						$ProductTemplateId 	= $Us2Product->getUs2ProductTemplateId();
						$uProduceDocId		= Us2ProductTemplatePeer::GetuProduceDocId ($ProductTemplateId);
					}
					else
						die("Error proofing product, no product is selected. Please try again later.");
				
					/**
					* Get all the dials for the product template
					***********************************************************************/
					$Dials = Us2DialPeer::GetDialsByTemplate ($ProductTemplateId);
					
					while ($Dials->next())
					{
						$DialId		= $Dials->get(1);
						$Name 		= $Dials->get(2);
						$Us2Dial 	= Us2DialPeer::retrieveByPk ($DialId);
						$DialName	= $Us2Dial->getUProduceDialName();
						
						/* If image dial then dial value contains an image id
						***********************************************************/
						if ($Us2Dial->getDialTypeId() == '2')
						{
							$IsImageDial[]	= "$DialName";
							$Us2Image 		= Us2ImagePeer::retrieveByPk ($Us2Dial->getDefaultValue());
							
							if ($Us2Image)
								$Value = $Us2Image->getValue();
							else
								$Value = $Us2Dial->getDefaultValue();
						}
						else
							$Value = $Us2Dial->getDefaultValue();
				
						$Customization["$Name"] = $Value;
					}
				
				
				
				
					if ($ProofBy == 'Customer' || $ProofBy == 'Product')
					{
							/**
							* Get the default product property and merge it with the template property
							**************************************************************************************/
							$ProductCustomization = Us2ProductDialPeer::GetProductDefaultAsset ($ProductId);
							
							foreach ($ProductCustomization as $DialName => $DialValue)
							{
								if (in_array("$DialName", $IsImageDial)  )
								{
									$Us2Image = Us2ImagePeer::retrieveByPk ($DialValue);
									
									if ($Us2Image)
										$DialValue = $Us2Image->getValue();
								}
								
								$ProductCustomization["$DialName"] = $DialValue;
							}

								
							if (!$ProductCustomization) $ProductCustomization = array();
							$Customization = array_merge($Customization, $ProductCustomization);
				
				
							/**
							* Get the default customer product property and merge it with the template property
							**************************************************************************************/
							if ($CustomerId > 0)
								$CustomerCustomization = Us2ProductCustomerDialPeer::GetCustomerDefaultAsset ($CustomerId, $ProductId, $GroupName);
				
							foreach ($CustomerCustomization as $DialName => $DialValue)
							{
								if (in_array("$DialName", $IsImageDial)  )
								{
									$Us2Image = Us2ImagePeer::retrieveByPk ($DialValue);
									
									if ($Us2Image)
										$DialValue = $Us2Image->getValue();		
								}
								
								$CustomerCustomization["$DialName"] = $DialValue;
							}
								
							if (!$CustomerCustomization) $CustomerCustomization = array();
							$Customization = array_merge($Customization, $CustomerCustomization);
					}
					
				
				
				
					/**
					* Setup the weird magical symbols
					***************************************************************************************/
					foreach($Customization as $DialName => $DialValue)
					{
							switch ($DialName)
							{
								case 'EXP DATE 1':
								case 'EXP_DATE1': #COUPON EXP DATE
										# % = 90 days from expire date
										# (blank) = (blank)
										# (any) = (any)
									if (trim($DialValue)=='%')
										$Customization[$DialName] = date('n/d/y', strtotime("+3 months", time()));
									elseif (trim($DialValue)=='@')
										$Customization[$DialName] = date('n/d/y', strtotime("+2 months", time()));
									elseif (trim($DialValue)=='#')
										$Customization[$DialName] = date('n/d/y', strtotime("+1 months", time()));	
									elseif (trim($DialValue)=='&')
										$Customization[$DialName] = date('n/d/y', strtotime("+45 days", time()));						
									break;
								case 'EXP DATE 2':
								case 'EXP_DATE2': #COUPON EXP DATE
									if (trim($DialValue)=='%')
										$Customization[$DialName] = date('n/d/y', strtotime("+3 months", time()));
									elseif (trim($DialValue)=='@')
										$Customization[$DialName] = date('n/d/y', strtotime("+2 months", time()));
									elseif (trim($DialValue)=='#')
										$Customization[$DialName] = date('n/d/y', strtotime("+1 months", time()));
									elseif (trim($DialValue)=='&')
										$Customization[$DialName] = date('n/d/y', strtotime("+45 days", time()));									
									break;	
								case 'EXP_DATE3': #COUPON EXP DATE
								case 'EXP DATE 3':
									if (trim($DialValue)=='%')
										$Customization[$DialName] = date('n/d/y', strtotime("+3 months", time()));
									elseif (trim($DialValue)=='@')
										$Customization[$DialName] = date('n/d/y', strtotime("+2 months", time()));
									elseif (trim($DialValue)=='#')
										$Customization[$DialName] = date('n/d/y', strtotime("+1 months", time()));
									elseif (trim($DialValue)=='&')
										$Customization[$DialName] = date('n/d/y', strtotime("+45 days", time()));								
									break;	
								case 'EXP_DATE4': #COUPON EXP DATE
								case 'EXP DATE 4':
									if (trim($DialValue)=='%')
										$Customization[$DialName] = date('n/d/y', strtotime("+3 months", time()));
									elseif (trim($DialValue)=='@')
										$Customization[$DialName] = date('n/d/y', strtotime("+2 months", time()));
									elseif (trim($DialValue)=='#')
										$Customization[$DialName] = date('n/d/y', strtotime("+1 months", time()));	
									elseif (trim($DialValue)=='&')
										$Customization[$DialName] = date('n/d/y', strtotime("+45 days", time()));								
									break;							
								case 'EXP_DATE6': # TODAY DATE
								case 'MAIL DATE':
									if (trim($DialValue)=='%')
										$Customization[$DialName] = date('n/d/y');																							
							}
					}
				
				


					/**
					* Generate proof
					***************************************************************************************/	
					#require_once (SF_ROOT_DIR.'/lib/uProduce.class.php');
					$JobId = self::Proof ($uProduceDocId, $OutputType='PDF', $Customization);
						
					if ($JobId)
					{
						$Status = 0;
						# 1 Waiting
						# 2 InProgress
						# 3 Completed
						# 4 Failed
						# 5 Aborting
						# 6 Aborted
						# 7 Deployed
						# 8 Suspended
						$LastMessage = '';	
						$Continue = true;	
							

						while ($Continue==true)
						{
							$Status = self::GetJobStatus ($JobId);
						
							switch ($Status)
							{
								case '1':
									$Message = 'Queued, please wait...';
									break;
								case '2':
									$Message = 'In progress, please wait...'; 
									break;
								case '3':
									$Continue=false;
									$Message = '';
		
									$Path = self::GetFolderPath ($JobId);
									$Files = self::GetOutputResult ($JobId);
									
									foreach ($Files as $File)
									{
										$HTML.= "<img src=\"$Path$File\"><p><br>";
									}
									
				
									echo '<script type="text/javascript">
										element = document.getElementById ("main_loading");
										element.innerHTML = \'Done\'
										clearTimeout(loadTime);
										clearInterval(loadTime);
									</script>';
									flush();	
																						
									if (true)#$this->Type == 'PDFO'
									{
										//redirect to pdf
									echo '<script type="text/javascript">
										window.location = "'.$Path.$Files.'"
									</script>';	
									}
				
									#print_r($File);
									break;
								default:
									$Continue=false;
									$Message = 'Failed, please try again...';
									break;
							}
							
							if($Continue==false)
							{
									echo '<script type="text/javascript">
										clearTimeout(loadTime);
										clearInterval(loadTime);
									</script>';	
									flush();
									
									if($Status >= 3)
									{
										echo '<script type="text/javascript">
											element = document.getElementById ("main_loading");
											element.innerHTML = \'Ooops!<p>'. $Message .'\'
										</script>';	
										flush();
									}						
							}
							
							if ($LastMessage != $Message && $Status!=3)
							{
								echo '<script type="text/javascript">
									element = document.getElementById ("loading_message");
									element.innerHTML = "'.$Message.'"
								</script>';

								flush();
							}
							
							$LastMessage = $Message;
							
							sleep(3);
						}
				
					}
					else
					{
						echo '<script type="text/javascript">
							element = document.getElementById ("loading_message");
							element.innerHTML = "Error trying to generate preview, please try again later..."
							clearTimeout(loadTime);
							clearInterval(loadTime);
						</script>';
						flush();		
					}
			}
			
			/**
			* Generate email proof
			*********************************************************************************/
			public static function GenerateEmailProof ($ProductId=0, $ProofBy='', $CustomerId=0, $Us2ProductLibraryId=0, $orderProductId=0)
			{				
					$arrayDialValue	= array();
				
					if ($ProductId)
					{
						$Us2Product 		= Us2ProductPeer::retrieveByPk ($ProductId);
						$ProductTemplateId 	= $Us2Product->getUs2ProductTemplateId();
						$uProduceDocId		= Us2ProductTemplatePeer::GetuProduceDocId ($ProductTemplateId);
					}
					else
						die("Error proofing product, no product is selected. Please try again later.");
						
					if($CustomerId)
						$ClientId = CustomerPeer::GetClientByCustomer($CustomerId);
		

					require_once ("/var/www/web3/lib/aggregator.class.php");
					$arrayRecipient = array(
						array(
						'first'				=> 'Michelle',
						'last'				=> 'Williams-Washington',
						'full_name'			=> 'Michelle Williams-Washington',
						'address'			=> '9427 Corporate Lake Dr',
						'city'				=> 'Tampa',
						'state'				=> 'FL',
						'zip'				=> '33634',
						'vehicle_make' 		=> 'Toyota',
						'vehicle_model' 	=> 'Camry',
						'vehicle_year' 		=> '2008',
						'vehicle_mileage' 	=> '15000',
						'vehicle_vin'		=> 'JT3GN86R7W0058429',
						'seq'				=> '10210512B2',
						'purl_code'			=> 'X1234',
						'purl_name'			=> 'MichelleWilliamsWashington',
						'matchcode'			=> '123456',
						'barcode'			=> '/335407340803/'
						),
					);
					
					#$arrayOrderProductGroupName[10] = "GROUP TO PROOF";
					$arrayProofProperty = array(
						'ProductId' 		=> $ProductId,
						'CustomerId'		=> $CustomerId,
						'ProductTemplateId'	=> $ProductTemplateId,
						'ClientId'			=> $ClientId,
						'uProduceDocId'		=> $uProduceDocId
					);
					

					$Aggregation = new Aggregator();
					$Aggregation->SetProductLibraryId($Us2ProductLibraryId);	
					#$Aggregation->SetDisplayWatermark(true);		
					$Aggregation->SetRecordLimit(1);
					$Aggregation->SetMailDate(date('m/d/Y'));
					$Aggregation->SetBlankRecord(0);
					$Aggregation->SetProofOrderProductId($orderProductId);
					$Aggregation->InitProofData($arrayRecipient, $orderProductId);
					$Aggregation->PreloadOrderValues($arrayOrderProductGroupName=array(), $arrayProofProperty);
					#print_r($Aggregation); exit;
					$Aggregation->CreateRecipientRecord();
					$Aggregation->GenerateFinalValue();
					$arrayDialValue = $Aggregation->CreateFinalProofArray();
					print_r($arrayDialValue); 
					#print_r($arrayDialValue); exit;
				#	print_r($Aggregation); exit;


					$emailTemplate = '
					<table width="100%">
					<tr>
						<td style="background-color:#ff0000">
						{DEALERSHIP NAME 1}<br>
						{SLOGAN 1}
						</td>
					</tr>
					</table>


					{FIRST}
					{SLOGAN 2}<p>
					Dear {FIRST}
					{PARAGRAPH 2}
					Sincerely,
					{SERVICE MANAGER 1}
					{TITLE 1}

					{CPN TXT A - 1}
					{COUPON 1}
					{TEXT 4}
					{PURL CODE}
					{SERVICE HOURS 1}
					{DEALERSHIP CITY 1}
					{DEALERSHIP NAME 1}
					{DEALERSHIP ST 1}
					{DEALERSHIP ZIP 1}
					';

					foreach($arrayDialValue as $dialName => $dialValue)
					{
						if(strpos($dialValue, 'E:\\')===0) {
							$dialValue 		= str_replace('E:\\', '\\\\tinman\\', $dialValue);
							$dialValue 		= "<img src=\"$dialValue\">";
							$emailTemplate 	= str_replace("{{$dialName}}", $dialValue, $emailTemplate);
						}
						else
							$emailTemplate = str_replace("{{$dialName}}", $dialValue, $emailTemplate);
					}

					echo "<pre>$emailTemplate</pre>";
					exit;


			}
			
			/**
			* ConvertPDFToJpeg
			*********************************************************************************/
			private static function ConvertPDFToJpeg($infilepath, $outdir)
			{
				$pathinfo 			= pathinfo($infilepath);
				$filename 			= $pathinfo['filename'];
				exec("/usr/bin/convert -density 200 $infilepath -scale 2000x2000 $outdir/{$filename}.jpg");
				
				$arrayImage = array(
					"{$outdir}/{$filename}.jpg",
					"{$outdir}/{$filename}-0.jpg",
					"{$outdir}/{$filename}-1.jpg",
					"{$outdir}/{$filename}-2.jpg",
					"{$outdir}/{$filename}-3.jpg",
				);
				
				foreach($arrayImage as $file)
				{
					if(file_exists($file))
					{
						# Convert image from cymk to rgb
						$img = imagecreatefromjpeg($file);
						imagejpeg($img, $file, 100);

						$result[] = str_replace('/var/www/web3/web/', 'http://gateway.printhd.us/', $file);
					}
				}
				
				return $result;
			}
                        
                        
                        public function cleanUpTemp($file)  {
                            if(stripos('_temp', $file)) {
                                unlink($file);
                            }
                        }
			
				
	}
?>
