<?php

/**
 * smanagerActions actions.
 *
 * @package    smanagerActions
 * @subpackage smanagerActions
 * @author     Lom Van Nguyen
 * @version    SVN: $Id: actions.class.php 2692 2009-01-12 21:03:55Z fabien $
 */
 
 /*` Need this library for some number and URL converting functions
 ````````````````````````````````````````````````````````````````````*/
require_once SF_ROOT_DIR . '/includes/common/class.convert.php';


class smanagerActions extends sfActions
{
	/**
	* The code inserted here is executed at the beginning of each action call
	*********************************************************************************/
	public function preExecute()
	{
		$this->AccessControl = new AccessControl($this);

		$accessGroup		= array('ADMIN','STORE ADMIN');
		$isAuthenticated	= $this->AccessControl->isAuthenticated;
		$hasAccess			= $this->AccessControl->hasGroup( $accessGroup );

		if(! $isAuthenticated) $this->redirect ("/login");

		if(! $hasAccess)
			$this->forward('default', 'NoAccess');






		# Get and initialize request variables
		foreach ($_REQUEST as $name => $value)
		{
			$len = strlen($value);
			# If date then convert to database format
			if (!is_numeric($value) && strtotime($value)!==false && $len<6 && $len!=1) $value = date ('Y-m-d', strtotime($value));
			$this->$name = $value;
		}

		$this->LoadVariables();
	}

	/**
	* Index
	*********************************************************************************/
	public function executeIndex()
	{
		# Forward to the ManagerIndex page so we can secure it for admin only.
		$this->forward ("smanager", "ManagerIndex");
	}

	/**
	* Internal Function: LoadVariables() :: Load variables and session data.
	*********************************************************************************/
	private function LoadVariables ()
	{
		$token		= $this->getRequestParameter('token');
		$request	= Convert::DecodeURL($token);

		foreach($request as $name => $value)
			$this->$name = $value;

		# Only temporary for debugging purposes
		$this->TOKEN = $request;
	}

	/**
	* Manager Index
	*********************************************************************************/
	public function executeManagerIndex()
	{
		$this->setLayout("smanager");
		$this->setTemplate("Index");
		$this->getResponse()->setTitle('American Marketing | Store Manager');

		define("LOADING_HTML",		'<center><img src="http://us.i1.yimg.com/us.yimg.com/i/us/per/gr/gp/rel_interstitial_loading.gif"></center>');
		define("CONNECTION_ERROR",	'<fieldset><b>Ooops, connection failed.</b><p> Please try again later. If you continue to see this error, please notify IT department.</fieldset>');

                

		/**
		* Page
		*****************************************************************************/
		switch ($this->Page)
		{
			case 'UploadDialImage':
				$this->setLayout(false);
				return $this->UploadDialImage();
			break;
			case 'CreateNewProductLibraryGroup':
				$this->setLayout(false);
				$this->setTemplate ("CreateNewProductLibraryGroup");
				return '_Success'; exit;
				break;
			break;
			case 'ProductApprovalList':
				$this->setTemplate ("ProductApprovalList");
				return '_Success'; exit;
				break;
			break;
			case 'GeoMailDeliveryChart':
				$this->setLayout(false);
				$this->setTemplate ("GeoMailDeliveryChart");
				return '_Success'; exit;
				break;
			break;
			case 'ProductApproval':
				$this->setLayout(false);
				$this->setTemplate ("ProductApproval");
				return '_Success'; exit;
				break;
			break;
			case 'LiveProductApproval':
				$this->setLayout(false);
				$this->setTemplate ("LiveProductApproval");
				$this->ProcessLiveProductApproval();
				return '_Success'; exit;
				break;
			break;
			case 'FindText':
				$this->setLayout(false);
				$this->setTemplate ("FindText");
				return '_Success'; exit;
				break;
			break;
			case 'ViewProducts':
				$this->setTemplate ("ViewProducts"); break;
			case 'CustomizationWizard':
				$this->setTemplate("CustomizationWizard");
				if($this->Action=='AddWizard') { return '_Add'; exit; }
				if($this->Action=='AddStep') { return '_AddStep'; exit; }
				if($this->Action=='EditStep') { return '_EditStep'; exit; }
				break;
			case 'Product':
				$this->setTemplate ("Product"); break;
			case 'FieldSetup':
				$this->setLayout(false);
				$this->setTemplate ("FieldSetup");
			break;
			case 'ProductEdit':
				$this->setLayout(false);
				$this->setTemplate ("ProductEdit");
			break;
			case 'Automagic':
				$GLOBALS['skip_javascript'] = true;
				$this->getResponse()->addJavascript('/sf/prototype/js/prototype.js');
				$this->getResponse()->addJavascript('/js/jquery.1.5/jquery-1.5.1.min.js');
				$this->setTemplate("Automagic");
				return '_20120725';
			break;
			case 'SaveAutomagic':
				$this->setLayout(false);
				$this->setTemplate ("Automagic");
				return '_Save'; exit;
			break;
			case 'SaveAdvancedAutomagic':
				$this->setLayout(false);
				$this->setTemplate ("AdvancedAutomagic");
				return '_Save'; exit;
			break;
			case 'AdvancedAutomagicEditCondition':
				$this->setLayout(false);
				$this->setTemplate ("AdvancedAutomagic");
				return '_EditCondition'; exit;
			break;
			case 'SaveAdvancedAutomagicCondition':
				$this->setLayout(false);
				$this->setTemplate ("AdvancedAutomagic");
				return '_SaveCondition'; exit;
			break;
			case 'RemoveAdvancedAutomagic':
				$this->setLayout(false);
				$this->setTemplate ("AdvancedAutomagic");
				return '_Remove'; exit;
			break;
			case 'AdvancedAutomagicEdit':
				$this->setLayout(false);
				$this->setTemplate ("AdvancedAutomagic");
				return '_Edit'; exit;
			break;
			case 'BrowseEvoxImage':
				$this->setLayout(false);
				$this->setTemplate ("BrowseEvoxImage");
				return '_Success'; exit;
			break;
			case 'ChangeRequestNote';
				$this->setLayout(false);
				$this->setTemplate(false);

				if($this->ProductChangeRequestId && trim($this->note))
				{
					$Us2ProductChangeRequestHistory = new Us2ProductChangeRequestHistory;
					$Us2ProductChangeRequestHistory->setUs2ProductChangeRequestId($this->ProductChangeRequestId);
					$Us2ProductChangeRequestHistory->setHistoryType('NOTE');
					$Us2ProductChangeRequestHistory->setNotes(trim($this->note));
					$Us2ProductChangeRequestHistory->setCreatedDate(date('Y-m-d H:i:s'));
					$Us2ProductChangeRequestHistory->setCreatedByUserId($this->AccessControl->UserId);
					echo $Us2ProductChangeRequestHistory->save(); exit;
				}

				echo '0'; exit;
			break;
			case 'UpdateChangeRequest':
				$this->setLayout(false);
				$this->setTemplate(false);

				if(($this->Remove || $this->SetCompleted || $this->UpdateCaseStatus) && $this->ProductChangeRequestId)
				{
					if($this->Remove) 	$new = 'REMOVED';
					else				$new = 'COMPLETED';

					if($this->UpdateCaseStatus)
						$new = $this->Status;

					foreach($this->ProductChangeRequestId as $id)
					{
							$Us2ProductChangeRequest = Us2ProductChangeRequestPeer::retrieveByPk($id);

							if($Us2ProductChangeRequest)
							{
								$OldStatus = $Us2ProductChangeRequest->getStatus();

								$Us2ProductChangeRequest->setStatus($new);
								$Us2ProductChangeRequest->save();

								if($OldStatus != $new)
								{
									$Us2ProductChangeRequestHistory = new Us2ProductChangeRequestHistory;
									$Us2ProductChangeRequestHistory->setUs2ProductChangeRequestId($id);
									$Us2ProductChangeRequestHistory->setHistoryType('STATUS_CHANGE');
									$Us2ProductChangeRequestHistory->setOldStatus($OldStatus);
									$Us2ProductChangeRequestHistory->setNewStatus($new);
									$Us2ProductChangeRequestHistory->setNotes($this->Notes);
									$Us2ProductChangeRequestHistory->setCreatedDate(date('Y-m-d H:i:s'));
									$Us2ProductChangeRequestHistory->setCreatedByUserId($this->AccessControl->UserId);
									$Us2ProductChangeRequestHistory->save();
								}

								if($this->SetCompleted)
									Us2ProductChangeRequestPeer::SendStatusUpdateAlert($id, 'COMPLETED');
								elseif($this->Remove)
									Us2ProductChangeRequestPeer::SendStatusUpdateAlert($id, 'REMOVED');
								elseif($this->UpdateCaseStatus)
								{
									switch($this->Status)
									{
										#case 'PENDING': Us2ProductChangeRequestPeer::SendStatusUpdateAlert($id, ''); break;
										#case 'IN_PROGRESS': Us2ProductChangeRequestPeer::SendStatusUpdateAlert($id, ''); break;
										#case 'UPDATED': Us2ProductChangeRequestPeer::SendStatusUpdateAlert($id, ''); break;
										case 'INSUFFICIENT_INFO': Us2ProductChangeRequestPeer::SendStatusUpdateAlert($id, 'INSUFFICIENT_INFO'); break;
									}
								}
							}

					}
				}

				if($this->RedirectUrl)	header("Location: $this->RedirectUrl");
				else					header("Location: /smanager");
				exit;

			break;
			case 'UpdateChangeRequestStatus':
				$this->setLayout(false);
				$this->setTemplate(false);

				if($this->ProductChangeRequestId)
				{
					$Us2ProductChangeRequest = Us2ProductChangeRequestPeer::retrieveByPk($this->ProductChangeRequestId);

					if($Us2ProductChangeRequest)
					{
						$OldStatus = $Us2ProductChangeRequest->getStatus();

						if(!$this->UpdateWhenPending || ($this->UpdateWhenPending && $OldStatus=='PENDING'))
						{
							$Us2ProductChangeRequest->setStatus($this->Status);
							$Us2ProductChangeRequest->setLastHandledDate(date('Y-m-d H:i:s'));
							$Us2ProductChangeRequest->setLastHandledByUserId($this->UserId);
							$Us2ProductChangeRequest->save();

							if($OldStatus != $this->Status)
							{
								$Us2ProductChangeRequestHistory = new Us2ProductChangeRequestHistory;
								$Us2ProductChangeRequestHistory->setUs2ProductChangeRequestId($this->ProductChangeRequestId);
								$Us2ProductChangeRequestHistory->setHistoryType('STATUS_CHANGE');
								$Us2ProductChangeRequestHistory->setOldStatus($OldStatus);
								$Us2ProductChangeRequestHistory->setNewStatus($this->Status);
								$Us2ProductChangeRequestHistory->setCreatedDate(date('Y-m-d H:i:s'));
								$Us2ProductChangeRequestHistory->setCreatedByUserId($this->AccessControl->UserId);
								$Us2ProductChangeRequestHistory->save();
							}
						}

						echo '1'; exit;
					}


				}

				echo '0'; exit;

			break;
			case 'ChangeRequestInfo':
				$this->setLayout(false);
				$this->setTemplate(false);
				$this->ProductChangeRequestId = intval($_REQUEST['ProductChangeRequestId']);

				switch($this->Partial)
				{
					case 'NOTE': 	return '_ChangeRequestInfo_Note'; 		break;
					case 'HISTORY': return '_ChangeRequestInfo_History'; 	break;
					default: 		return '_ChangeRequestInfo_Detail'; 	break;
				}

				exit;
			break;
			case 'DialProperty':
				$this->setLayout(false);

				if ($this->AccessControl->hasGroup('Product Manager v10') == true) {
					$this->setTemplate("DialProperty");
					return '_20131121'; # With mass proof
				} else {
					$this->setTemplate("DialProperty");
					return '_20120829';
				}

			break;
			case 'SetActiveProductLibrary':
				$this->setLayout(false);
				$this->setTemplate ("SetActiveProductLibrary");
				return "_Success"; exit;
			break;
			case 'GetCustomers':

				$this->client = $_REQUEST['getClient'];
				if ($this->client == 0) {
					$this->arrayCustomCustomerId 	= Us2ProductCustomerDialPeer::GetArrayCustomerByProduct($_REQUEST['productId']);
					$this->arrayCustomers			= CustomerPeer::GetNameByArrayId($this->arrayCustomCustomerId);
				} else {
					$this->arrayCustomers 		= CustomerPeer::GetCustomersByClient($this->client);
					$this->arrayCustomCustomerId = Us2ProductCustomerDialPeer::GetArrayCustomerByProduct($_REQUEST['productId']);
				}


				$arrayACL 			= Us2ProductAclPeer::GetByProductType($_REQUEST['productId'], $SourceType='CUSTOMER');
				$arrayCstPermission	= Us2ProductAclPeer::GetCustomerACLByPermissionGroup($arrayACL, $this->AccessControl->UserGroupIds);

				if($arrayCstPermission)
				{
					foreach($arrayCstPermission as $__id => $__permission)
					{
						if($__permission['hidden']=='Y') unset($this->arrayCustomCustomerId[$__id]);
					}
				}

				$this->arrayCustomerName = CustomerPeer::GetNameByArrayId ($this->arrayCustomCustomerId);
				$this->arrayCustomerClientId = CustomerPeer::GetClientByArrayCustomer($this->arrayCustomCustomerId);

				$this->setLayout(false);
				$this->setTemplate ("GetCustomers");
				return "_Success"; exit;
			break;
			case 'SaveDialProperty':
				$this->setLayout(false);
				$this->setTemplate ("DialProperty");
				return "_Save"; exit;
			break;
			case 'ProductProperty':

				if ($this->AccessControl->hasGroup('Product Manager v10') == true) {
					$this->setTemplate("ProductProperty");
					return '_20131121';
				} else {
					$this->setTemplate("ProductProperty");
					return '_20120829';
				}

			break;
			case 'CouponCatalog':
				$this->setTemplate("CouponCatalog");
			break;
			case 'CouponProperty':
				$this->setLayout(false);
				$this->setTemplate("CouponProperty");

			break;
			case 'ProductProperty_AddCustomer':
				$this->setLayout(false);
				$this->setTemplate ("ProductProperty");
				return "_AddCustomer"; exit;
			break;
			case 'MagicProperty':
				$this->setLayout(false);
				$this->setTemplate ("MagicProperty");
			break;
			case 'AdvancedDialProperty':
				$this->setLayout(false);
				$this->setTemplate("AdvancedDialProperty");
				if($this->Save) { return '_Save'; exit; }
			break;
			case 'EmailProof':
				$this->setLayout(false);
				$this->setTemplate("EmailProof");
				return '_Success'; exit;
			break;
			case 'CommonText':
				$this->setLayout(false);
				$this->setTemplate ("CommonText");
			break;
			case 'AddAutomagicCustomer':
				$this->setLayout(false);
				$this->setTemplate ("AddAutomagicCustomer");
				return '_SelectCustomer'; exit;
			break;
			case 'AddAutomagicCustomer_SubmitForm':
				$this->setLayout(false);
				$this->setTemplate ("AddAutomagicCustomer");
				return '_SubmitForm'; exit;
			break;
			case 'AssetLibrary_SelectImage':
				$this->setLayout(false);
				$this->setTemplate ("AssetLibrary");

				return '_SelectImage2'; exit;
			break;
			case 'AssetLibrary_Add':
				$this->setLayout(false);
				$this->setTemplate ("AssetLibrary");
				return '_Add'; exit;
			break;
			case 'AssetLibrary_GetFolderImages':
				$this->setLayout(false);
				$this->setTemplate ("AssetLibrary");
				return '_GetFolderImages'; exit;
			break;
			case 'AssetLibrary_ManageImage':
				$this->setLayout(false);
				$this->setTemplate ("AssetLibrary");
				return '_ManageImage'; exit;
			break;
			case 'AssetLibrary_GetAssetImages':
				$this->setLayout(false);
				$this->setTemplate ("AssetLibrary");

				if($this->UploadImage)
				{ return '_UploadImages'; exit; }

				return '_GetAssetImages'; exit;
			break;
			case 'AssetLibrary':

				if($_REQUEST['Search'])
				{
					$this->SearchAssetLibrary();
				}
				elseif($this->getRequestParameter('MoveAssetImage'))
				{
					return $this->MoveAssetImage();
				}

				$this->setTemplate ("AssetLibrary");
			break;
			case 'AddProduct':
				$this->setTemplate ("AddProduct");
			break;
			case 'ProofStatus':
				$this->setLayout(false);
				$this->setTemplate('ProofStatus');
				$this->arrayProofSchedule = Us2ProofSchedulePeer::GetByProductCustomer($this->ProductId, $this->CustomerId);
				return '_Success'; exit;
			break;
			case 'ViewScheduledProofResult':
				$this->setLayout(false);
				$this->setTemplate('ViewScheduledProofResult');
				return '_Success'; exit;
			break;
			case 'ProductTemplate':
				$this->setTemplate ("ProductTemplate");
			break;
			case 'ProductTemplate_Add':
				$this->setTemplate ("ProductTemplate");
				return '_Add'; exit;
			break;
			case 'ProductionSpec':
				$this->setTemplate ("ProductionSpec");
			break;


			case 'LiveConfigApprovalPreview':
				$this->setLayout(false);
				$this->setTemplate ("LiveConfigApprovalPreview");
			break;
			case 'ChangeRequest':
			case 'LiveProduct':
				#$this->setLayout('dynamic');
				$this->setTemplate ("LiveProduct");

				$this->includeCss = array(
					'http://gateway.printhd.us/css/jqueryui/1.8/themes/base/jquery.ui.all.css',
					'http://gateway.printhd.us/files/customer_profile/css/style.css'
				);
			break;
			case 'ChangeRequestDetail':
			case 'LiveProductDetail':
				#$this->setLayout('dynamic');
				$this->setTemplate ("LiveProductDetail");

				$this->includeJs = array(
					'http://admin.printhd.us/js/jquery.1.5/jquery-1.5.1.min.js'
				);

				$this->includeCss = array(
					'http://gateway.printhd.us/css/jqueryui/1.8/themes/base/jquery.ui.all.css',
					'http://gateway.printhd.us/files/customer_profile/css/style.css'
				);
			break;
			case 'ProductionDashboard':
				$this->setTemplate("ProductionDashboard2");


				require_once(SF_ROOT_DIR . '/classes/class.customer_profile.php');
				$CustomerProfile 		= new CustomerProfile;
				$arrayCampaignProduct 	= Us2ProductGroupPeer::GetProductsInGroup(array(), 'campaign', 'LIKE');

				$this->arrayPendingProfileRevision 			= $CustomerProfile->GetPendingRevision($arrayFilteredCustomerId);
				$this->arrayPendingCampaignProfileRevision	= $CustomerProfile->GetRevisionFilterByProductAffected($this->arrayPendingProfileRevision, $arrayCampaignProduct, 'AFFECTED');
				$this->arrayPendingTriggerProfileRevision	= $CustomerProfile->GetRevisionFilterByProductAffected($this->arrayPendingProfileRevision, $arrayCampaignProduct, 'NOTAFFECTED');

				$this->TotalPendingTriggerProductConfig		= Us2ProductLiveConfigPeer::GetPending($arrayFilteredCustomerId, $limit=50000, $getCountOnly=true, '', $arrayCampaignProduct, 'NOTIN');
				$this->TotalPendingCampaignProductConfig	= Us2ProductLiveConfigPeer::GetPending($arrayFilteredCustomerId, $limit=50000, $getCountOnly=true, '', $arrayCampaignProduct, 'IN');
				$this->TotalPendingTriggerChangeRequest		= Us2ProductChangeRequestPeer::GetPending($arrayFilteredCustomerId, $limit=50000, $getCountOnly=true, $arrayCampaignProduct, 'NOTIN');
				$this->TotalPendingCampaignChangeRequest	= Us2ProductChangeRequestPeer::GetPending($arrayFilteredCustomerId, $limit=50000, $getCountOnly=true, $arrayCampaignProduct, 'IN');

			break;
			case 'ProfileRevisionDetail':
				$this->setTemplate("ProfileRevisionDetail");
			break;
			case 'ProfileRevisionProof':
				$this->setTemplate("ProfileRevisionProof");
			break;
			case 'ProductionApproval':
				$customerId		= $this->getRequestParameter('CustomerId');
				$clientId		= $this->getRequestParameter('ClientId');
				$this->setTemplate("ProductionApproval");
				$this->getResponse()->setTitle('Production Approval');

				$return = $this->HandleProductionApproval();
                if($return) return $return;

                if($this->getRequestParameter('DownloadZip')) {
                	return $this->HandleProdApprovalDownloadZip();
                }

			break;
			case 'ProductListingManager':
				return $this->executeProductListingManager();
			break;
			case 'SaveMagicParagraph':
				$this->setLayout(false);
				$this->setTemplate ("SaveMagicParagraph");
			break;
			case 'GetProofByCsvWithJpgPreview':
				$this->setLayout(false);

//				if($this->AccessControl->UserId==3 || $this->AccessControl->UserId==859)
//				{
//					ob_start();
//					require_once (SF_ROOT_DIR.'/lib/uProduce2.class.php');
//					$result = uProduce2::GetProofByCsvWithJpgPreview($this->ProductId, $this->CustomerId, $this->ProofCsvFile, $this->Us2ProductLibraryId, $this->Us2ProductRevisionId);
//					ob_end_clean();
//
//					$result = array(
//						'web_location' => 'http://gateway.printhd.us/proofs/revision/2d957c401a25cd41e0df3b6021548d68_9501255.pdf',
//						'file_location' => '/var/www/web3/web/proofs/revision/2d957c401a25cd41e0df3b6021548d68_9501255.pdf',
//						'jpgs' => array(
//							'http://gateway.printhd.us/proofs/liveproduction_jpgs/c8b82ca82a8453c263700f459f0b89e8_913500950-0.jpg',
//							'http://gateway.printhd.us/proofs/liveproduction_jpgs/c8b82ca82a8453c263700f459f0b89e8_913500950-1.jpg')
//						);
//
//					foreach($result['jpgs'] as $url)
//					{
//						$size = Us2ImagePeer::GetNewImageSizeByWidth($url, $newWidth=500);
//						$result['preview_size'][] = $size;
//					}
//				}
//				else
//				{
					# Making sure the function call doesn't echo out anything. This will screw up our json data
					ob_start();

						#if($this->AccessControl->UserId==3)
						#	$result = uProduce::GetProofByCsvWithJpgPreview($this->ProductId, $this->CustomerId, $this->ProofCsvFile, $this->Us2ProductLibraryId, $this->Us2ProductRevisionId, $isProduction=true);
						#else
                                                
                                               
                                                    $result = uProduce::GetProofByCsvWithJpgPreview($this->ProductId, $this->CustomerId, $this->ProofCsvFile, $this->Us2ProductLibraryId, $this->Us2ProductRevisionId);
                                              
							

					ob_end_clean();
                                        
					#print_r($result); exit;

					#$logText	= "Product: $this->ProductId, CustomerId: $this->CustomerId, Csv: $this->ProofCsvFile, Us2ProductLibraryId: $this->Us2ProductLibraryId, Us2ProductRevisionId: $this->Us2ProductRevisionId";
					#$file 		= fopen('/var/www/web3/log/proofs/proof.log', 'a+');
					#fwrite($file, date('Y-m-d H:i:s')." -- $logText".print_r($result,true)."\n\n\n");
					#fclose($file);
				#}

				echo json_encode($result);
				exit;

			break;
                       case 'ProductionLiveProof':
                            $this->setLayout(false);
                         
                                         
                                        require_once(SF_ROOT_DIR . '/classes/class.customer_profile.php');
                                        require_once('/var/www/web3/batch/ops/config/prod_live_product_config_proof.php');
                                        
                                        $Us2ProductLiveConfig = Us2ProductLiveConfigPeer::retrieveByPk($this->ProductId);
                                        //var_dump($Us2ProductLiveConfig);die();
                                        if(is_null($this->ProofCsvFile))
                                        {
                                            $this->ProofCsvFile =  "/var/www/web3/temp/data/20141203_afc19125e134ab854957bd3ddf87af6a_159327816_626608070.csv";
                                        }
                                        
					ob_start();
                                           $result = SubmitUs2ProductLiveConfig($Us2ProductLiveConfig, "System".microtime(), 1, $is_test_server=false, $is_production_assets=true);         
                                           // $result = uProduce::GetProofByCsvWithJpgPreview($this->ProductId, $this->CustomerId, $this->ProofCsvFile,0, 0, true);
					ob_end_clean();
                             
				echo json_encode($result);
				exit;

                        break;
			case 'Proof':
				$this->setLayout(false);

				require_once (SF_ROOT_DIR.'/lib/uProduce.class.php');


				/* Uploading a csv file to proof
				````````````````````````````````````````````````*/
				if($this->Type=='CsvProof')
				{
					$ProofCsvFile = $_FILES['ProofCsvFile'];
					uProduce::GenerateProofByCsvFile($this->ProductId, $this->CustomerId, $ProofCsvFile['tmp_name'], $this->Us2ProductLibraryId, $this->Us2ProductRevisionId);
				}
				elseif($this->Type=='ProofAutomotive')
				{
					$this->forward('smanager','ProofWithOptions'); exit;
				}
				elseif($this->Type=='GroupProof')
				{
					$this->forward('smanager','GroupProofing'); exit;
				}
				else {
					uProduce::GenerateProof2($this->ProductId, $this->ProofBy, $this->CustomerId, $this->Us2ProductLibraryId, 10, $this->Us2ProductRevisionId);
				}

				exit;
			break;
			case 'DialSearchReplace':
				$this->forward('smanager','DialSearchReplace'); exit;
			break;
			case 'ProductDataTransfer':
				$this->forward('smanager','ProductDataTransfer'); exit;
			break;
			case 'GetProductByStoreAjax':
				$this->GetProductByStoreAjax(); exit;
			break;
			case 'GroupProof':
				$this->setLayout(false);

				switch($this->Action)
				{
					case 'GetCustomers':
						$this->setTemplate('GroupProof');
						return '_CustomerList'; print_r($_REQUEST); echo $this->ProductId;
					break;
					default: break;
				}
				exit;
			break;
			case 'ProofEmail':
				$this->setLayout(false);
				require_once (SF_ROOT_DIR.'/lib/uProduce.class.php');

				uProduce::GenerateEmailProof($this->ProductId, $this->ProofBy, $this->CustomerId, $this->Us2ProductLibraryId);
				exit;
			break;
			case 'UpdateProductLibraryGroup':

				if($this->UpdateConfigGroup)
				{
					$Us2ProductLibrary = Us2ProductLibraryPeer::retrieveByPk($this->Us2ProductLibraryId);
					if($Us2ProductLibrary)
					{
						if(! trim($this->GroupName))
							$this->GroupName = 'Untitled';

						$Us2ProductLibrary->setName($this->GroupName);
						$Us2ProductLibrary->save();
					}

					$token = Convert::EncodeURL("Page=ProductProperty&ProductId={$this->ProductId}&setupCustomerId={$this->CustomerId}&autoload=1&Us2ProductLibraryId={$this->Us2ProductLibraryId}");
					header("Location: /smanager?token=$token"); exit;
				}

				if($this->DeleteConfigGroup)
				{
					$Us2ProductLibrary = Us2ProductLibraryPeer::retrieveByPk($this->Us2ProductLibraryId);
					if($Us2ProductLibrary)
					{
						# Since we don't have an active_yn flag and other unknown pages also uses
						# this table. Let's set the product id to a (-) negative number so it doesn't
						# show up anywhere.
						$CID = $this->CustomerId * -1;
						$CID = $CID ? $CID : -1;

						$Us2ProductLibrary->setProductId($this->ProductId * -1);
						$Us2ProductLibrary->setCustomerId($CID);
						$Us2ProductLibrary->save();

						/**
						* Also remove from the active product library. We can simply delete the record here because it's
						* only a reference table.
						*/
						$C = new Criteria;
						$C->addAnd(Us2ProductActiveLibraryPeer::US2_PRODUCT_LIBRARY_ID, $this->Us2ProductLibraryId);
						Us2ProductActiveLibraryPeer::doDelete($C);


						$token = Convert::EncodeURL("Page=ProductProperty&ProductId={$this->ProductId}&setupCustomerId={$this->CustomerId}&autoload=1");
						header("Location: /smanager?token=$token"); exit;
					}
				}

			break;
			default:
				$this->arrayMall = Us2MallPeer::GetMallArray();

				if($this->BrowseType=='ByStore' && $this->MallId)
				{
					if(! $this->StoreId)
						$this->arrayStore = Us2StorePeer::GetStoreArrayByMall($this->MallId);
					else
					{
						$Token = Convert::EncodeURL("Page=ViewProducts&StoreId=$this->StoreId");
						header ("Location: /smanager?token=$Token"); exit;
					}
				}
				elseif($this->BrowseType=='ByCustomer')
				{
					$Token = Convert::EncodeURL("Page=ViewProducts&CustomerId=$this->CustomerId");
					header ("Location: /smanager?token=$Token"); exit;
				}

				#if($this->AccessControl->UserId==3)
				$this->setTemplate("Index_20120622");
			break;
		}



		return "_Success"; exit;
	}

	private function MoveAssetImage()
	{
		$this->setLayout(false);

		$MoveToLibraryId 	= intval($this->getRequestParameter('MoveToLibraryId'));
		$AssetImageId 		= intval($this->getRequestParameter('AssetImageId'));

		if($AssetImageId && $MoveToLibraryId)
		{
			$Us2AssetImage = Us2AssetImagePeer::retrieveByPk($AssetImageId);
			$Us2AssetImage->setUs2AssetLibraryId($MoveToLibraryId);
			$Us2AssetImage->save();
		}

		return sfView::NONE;
	}


	private function GetProductByStoreAjax()
	{
		$StoreId 			= $this->getRequestParameter('StoreId');
		$arrayResult 		= array();

		$C = new Criteria();
		$C->addSelectColumn (Us2ProductPeer::PRODUCT_ID);
		$C->addSelectColumn (Us2ProductPeer::NAME);
		$C->addAnd (Us2ProductPeer::STORE_ID, $StoreId);
		$C->addAnd (Us2ProductPeer::PRODUCT_TYPE_ID, 1);
		$C->addAnd (Us2ProductPeer::ACTIVE_YN, 'Y');
		$C->addAnd (Us2ProductPeer::STATUS_ID, 3, Criteria::NOT_EQUAL); # not deleted
		$C->addAscendingOrderByColumn (Us2ProductPeer::NAME);
		$Rs = Us2ProductPeer::doSelectRs($C);

		while($Rs->next())
		{
			$id = $Rs->get(1);
			$arrayResult[] = array(
				'product_id' 	=> $id,
				'name'			=> $Rs->get(2)."($id)"
			);
		}

		echo json_encode($arrayResult);
		exit;
	}


	private function SearchAssetLibrary()
	{
		$this->SearchAssetLibrary 		= true;
		$this->SearchText 				= $this->getRequestParameter('SearchText');
		$this->arrayProductTemplateId 	= array();
		$this->arrayProductId 			= array();
		$this->arrayFoundProductId 		= array();
		$this->arrayCustomerId 			= array();
		$this->arrayProductCustomerId 	= array();
		$this->arrayAutomagicMatch		= array();
		$this->arrayProductLibraryMatch = array();
		$this->arrayProductName 		= array();
		$this->arrayCustomerName 		= array();



		/**
		* Search by image id
		*/
		if(ctype_digit($this->SearchText) && $this->SearchText > 0)
		{
			$this->SearchText = intval($this->SearchText);

			/**
			* Get a list of dials using the image id
			*/
			$arrayDialId = array();

			$C = new Criteria();
			$C->addSelectColumn(Us2DialPeer::DIAL_ID);
			$C->addAnd(Us2DialPeer::DIAL_TYPE_ID, 2); # 2= image
			$C->addAnd(Us2DialPeer::DEFAULT_VALUE, $this->SearchText);
			$Rs = Us2DialPeer::doSelectRs($C);

			while($Rs->next())
				$arrayDialId[] = $Rs->get(1);


			/**
			* If we have a list of matching dials, find out where they belong
			*/
			if($arrayDialId)
			{
				/**
				* Check the product template
				*/
				$C = new Criteria;
				$C->addSelectColumn(Us2ProductTemplateDialPeer::US2_PRODUCT_TEMPLATE_ID);
				$C->addAnd(Us2ProductTemplateDialPeer::US2_DIAL_ID, $arrayDialId, Criteria::IN);
				$Rs = Us2ProductTemplateDialPeer::doSelectRs($C);

				while($Rs->next())
					$this->arrayProductTemplateId[] = $Rs->get(1);

				/**
				* Check the product
				*/
				$C = new Criteria;
				$C->addSelectColumn(Us2ProductDialPeer::US2_PRODUCT_ID);
				$c1 = $C->getNewCriterion(Us2ProductDialPeer::US2_DIAL_ID, $arrayDialId, Criteria::IN);
				$c2 = $C->getNewCriterion(Us2ProductDialPeer::DEFAULT_US2_DIAL_ID, $arrayDialId, Criteria::IN);
				$c1->addOr($c2);
				$C->add($c1);
				$C->addAnd(Us2ProductDialPeer::ACTIVE_YN, 'Y');
				$Rs = Us2ProductDialPeer::doSelectRs($C);

				while($Rs->next()) {
					$this->arrayFoundProductId[] 	= $Rs->get(1);
					$this->arrayProductId[] 		= $Rs->get(1);
				}

				/**
				* Check the customer products
				*/
				$C = new Criteria;
				$C->addSelectColumn(Us2ProductCustomerDialPeer::US2_PRODUCT_ID);
				$C->addSelectColumn(Us2ProductCustomerDialPeer::CUSTOMER_ID);
				#$C->addSelectColumn(Us2ProductCustomerDialPeer::US2_PRODUCT_CUSTOMER_DIAL_ID);
				$c1 = $C->getNewCriterion(Us2ProductCustomerDialPeer::US2_DIAL_ID, $arrayDialId, Criteria::IN);
				$c2 = $C->getNewCriterion(Us2ProductCustomerDialPeer::DEFAULT_US2_DIAL_ID, $arrayDialId, Criteria::IN);
				$c1->addOr($c2);
				$C->add($c1);
				$C->addAnd(Us2ProductCustomerDialPeer::ACTIVE_YN, 'Y');
				$C->addAscendingOrderByColumn(Us2ProductCustomerDialPeer::US2_PRODUCT_ID);
				$C->addAscendingOrderByColumn(Us2ProductCustomerDialPeer::CUSTOMER_ID);
				$Rs = Us2ProductCustomerDialPeer::doSelectRs($C);

				while($Rs->next()) {
					$ProductId 	= $Rs->get(1);
					$CustomerId = $Rs->get(2);


					$this->arrayProductId[] 	= $ProductId;
					$this->arrayCustomerId[] 	= $CustomerId;
					$this->arrayProductCustomerId[$ProductId][$CustomerId] = $CustomerId;
				}
			}



			/**
			* Check the automagic settings
			*/
			$C = new Criteria;
			$C->addAnd(Us2AutomagicPeer::SERIALIZED_DATA, "%{$this->SearchText}%", Criteria::LIKE);
			$C->addAscendingOrderByColumn(Us2AutomagicPeer::PRODUCT_ID);
			$C->addAscendingOrderByColumn(Us2AutomagicPeer::CUSTOMER_ID);
			$arrayAutomagic = Us2AutomagicPeer::doSelect($C);

			foreach($arrayAutomagic as $Automagic)
			{
				$CustomerId 	= $Automagic->getCustomerId();
				$ProductId 		= $Automagic->getProductId();
				$data 			= unserialize($Automagic->getSerializedData());
				$found 			= false;
				$fields 		= array();
				$descriptions 	= array();

				/**
				* Look into the advanced condition to determine where it's calling for the image
				*/
				foreach($data['ADVANCED_CONDITION'] as $i => $condition)
				{
					$GetDescription = false;

					foreach($condition['update_fields'] as $name => $value)
					{
						if($value == $this->SearchText)
						{
							$found = true;
							$fields[] = $name;
							$GetDescription = true;
						}
					}

					if($GetDescription)
					{
						foreach($condition['condition'] as $i => $cond)
						{
							$descriptions[] = "$cond[field] $cond[criteria] $cond[value]";
						}
					}
				}

				/**
				* Look into the variable data block
				*/
				foreach($data['PARAGRAPH'] as $i => $block)
				{
					if($block['replace'] == $this->SearchText)
					{
						$found = true;
						$descriptions[] = "$block[field]";
					}
				}

				/**
				* If we match exact matches
				*/
				if($found)
				{
					$this->arrayProductId[] 	= $ProductId;
					$this->arrayCustomerId[] 	= $CustomerId;

					$this->arrayAutomagicMatch[] = array(
						'product_id'	=> $ProductId,
						'customer_id'	=> $CustomerId,
						'fields'		=> $fields,
						'descriptions'	=> $descriptions
					);
				}
			}



			/**
			* Check product library.
			* This is tricky as we have to search all the values in the us2_product_library_dial table to
			* find matches and from there determine the customer/product and whether the dial type is an image
			*/
			$C = new Criteria;
			$C->addSelectColumn(Us2ProductLibraryPeer::US2_PRODUCT_LIBRARY_ID);
			$C->addSelectColumn(Us2ProductLibraryPeer::PRODUCT_ID);
			$C->addSelectColumn(Us2ProductLibraryPeer::CUSTOMER_ID);
			$C->addSelectColumn(Us2ProductLibraryPeer::NAME);
			$C->addSelectColumn(Us2ProductLibraryDialPeer::DIAL_NAME);
			$C->addAnd(Us2ProductLibraryDialPeer::VALUE, $this->SearchText);
			$C->addJoin(Us2ProductLibraryDialPeer::US2_PRODUCT_LIBRARY_ID, Us2ProductLibraryPeer::US2_PRODUCT_LIBRARY_ID);
			$C->addAscendingOrderByColumn(Us2ProductLibraryPeer::PRODUCT_ID);
			$C->addAscendingOrderByColumn(Us2ProductLibraryPeer::CUSTOMER_ID);
			$Rs = Us2ProductLibraryDialPeer::doSelectRs($C);

			while($Rs->next())
			{
				$LibraryId 		= $Rs->get(1);
				$ProductId 		= $Rs->get(2);
				$CustomerId 	= $Rs->get(3);
				$LibraryName 	= $Rs->get(4);
				$DialName 		= $Rs->get(5);

				$isImageDial = $this->GetProductDialType($ProductId, $DialName);

				if($isImageDial)
				{
					$this->arrayProductId[] 	= $ProductId;
					$this->arrayCustomerId[] 	= $CustomerId;
					$this->arrayProductLibraryMatch[$LibraryId] = array(
						'product_id'	=> $ProductId,
						'customer_id'	=> $CustomerId,
						'library_name'	=> $LibraryName
					);
				}

			}



			#echo '<pre>';
			#print_r($this->arrayProductLibraryMatch);

			#print_r($this->arrayProductTemplateId);
			#print_r($this->arrayProductId);
			#print_r($this->arrayProductCustomerId);
			#print_r($arrayDialId);
		}
		else
		{
			/**
			* Search by image name
			*/
		}


		/**
		* Get product names
		*/
		$C = new Criteria;
		$C->addSelectColumn(Us2ProductPeer::PRODUCT_ID);
		$C->addSelectColumn(Us2ProductPeer::NAME);
		$C->addAnd(Us2ProductPeer::PRODUCT_ID, $this->arrayProductId, Criteria::IN);
		$Rs = Us2ProductPeer::doSelectRs($C);

		while($Rs->next())
			$this->arrayProductName[$Rs->get(1)] = $Rs->get(2);

		/**
		* Get customer names
		*/
		$C = new Criteria;
		$C->addSelectColumn(CustomerPeer::CUSTOMER_ID);
		$C->addSelectColumn(CustomerPeer::NAME);
		$C->addAnd(CustomerPeer::CUSTOMER_ID, $this->arrayCustomerId, Criteria::IN);
		$Rs = CustomerPeer::doSelectRs($C);

		while($Rs->next())
			$this->arrayCustomerName[$Rs->get(1)] = $Rs->get(2);






		#echo '<pre>';
		#print_r($_REQUEST);
		#exit;
	}

	private function GetProductDialType($ProductId, $DialName)
	{
		$arrayProductDial = $this->arrayCachedProductDial[$ProductId];

		if(!$arrayProductDial)
		{
			$ProductTemplateId 	= Us2ProductPeer::GetProductTemplateId($ProductId);
			$arrayProductDial 	= Us2ProductTemplateDialPeer::GetuProduceNameAndType($ProductTemplateId);

			$this->arrayCachedProductDial[$ProductId] = $arrayProductDial;
		}


		return $arrayProductDial[$DialName] == 2;
	}

	public function executeProductDataTransfer()
	{
		/**
		* They should only be able to get here with the right permissions.
		* But let's do another check to make sure
		*/
		if($this->AccessControl->hasGroup('Product Manager MassCopy') == false)
			die("Access Restricted");


		$this->setLayout(false);
		$this->FromProductId 	= $this->ProductId;
		$this->ToProductId 		= $this->getRequestParameter('ToProductId');



		$this->arrayStore 				= Us2StorePeer::GetAll();
		$this->ProductTemplateId 		= Us2ProductPeer::GetProductTemplateId($this->FromProductId);
		$this->ProductProperties 		= Us2ProductPeer::GetProperties($this->FromProductId);
		$this->arrayDial 				= Us2ProductTemplateDialPeer::GetuProduceNameAndType($this->ProductTemplateId);

		$this->ToProductTemplateId 		= Us2ProductPeer::GetProductTemplateId($this->ToProductId);
		$this->ToProductProperties 		= Us2ProductPeer::GetProperties($this->ToProductId);
		$this->ToArrayDial 				= Us2ProductTemplateDialPeer::GetuProduceNameAndType($this->ProductTemplateId);

		$this->ToDropDownTextList 		= array(''=>'--');
		$this->ToDropDownImgList 		= array(''=>'--');

		foreach($this->ToArrayDial as $DialName => $DialType)
		{
			$AltDialName = str_replace(' ', '_', $DialName);

			# Display only fields that are being used in the product
			if($this->ProductProperties['FIELDS'][$DialName] == false &&
				$this->ProductProperties['FIELDS'][$AltDialName] == false
			) continue;

			/**
			* Text
			*/
			if($DialType == 1)
			{
				$this->ToDropDownTextList[$DialName] = $DialName;
			}
			elseif($DialType == 2)
			{
				$this->ToDropDownImgList[$DialName] = $DialName;
			}
		}


		/**
		* Get customer names
		*/
		$this->arrayFromCustomerId 	= Us2ProductCustomerDialPeer::GetArrayCustomerByProduct($this->FromProductId);
		$this->arrayCustomerId 		= Us2ProductCustomerDialPeer::GetArrayCustomerByProduct($this->ToProductId);
		$this->arrayCustomerName 	= CustomerPeer::GetNameByArray($this->arrayCustomerId);
		$this->arrayCustomerClient 	= CustomerPeer::GetClientByArrayCustomer($this->arrayCustomerId);
		$this->arrayClientId 		= array_unique($this->arrayCustomerClient);
		$this->arrayClientName 		= ClientPeer::GetNameByArray($this->arrayClientId);

		asort($this->arrayCustomerName);
		asort($this->arrayClientName);
		asort($this->arrayCustomerClient);




		$this->Mode = 'LIST';

		/**
		* Doing the preview
		*/
		if($this->PreviewUpdate)
		{
			$this->Mode = 'PREVIEW';

			$arrayCustomerId 		= $_REQUEST['Customer'];
			$SelectedDial 			= $_REQUEST['SelectedDial'];
			$DialDestinationValue	= $_REQUEST['DialDestinationValue'];
			$this->arrayPreviewDialChanges = array();

			foreach($arrayCustomerId as $CustomerId)
			{
				$arrayFromDialValue 	= Us2ProductCustomerDialPeer::GetCustomerDefaultAsset ($CustomerId, $this->FromProductId);
				$arrayDial 				= Us2ProductCustomerDialPeer::GetDialsByCustomer($this->ToProductId, $CustomerId);
				$arrayDialId 			= array_keys($arrayDial);
				$arrayUproduceDialName 	= Us2DialPeer::GetDialNameIdByArray($arrayDialId);

				foreach($SelectedDial as $i => $uProduceDialName)
				{
					$DestinationDial 	= $DialDestinationValue[$uProduceDialName];
					$FromValue 			= $arrayFromDialValue[$uProduceDialName];
					$DialId 			= array_search($DestinationDial, $arrayUproduceDialName);

					$this->arrayPreviewDialChanges[$CustomerId][] = array(
						'dial_name'	=> $DestinationDial,
						'dial_id'	=> $DialId,
						'new_value'	=> $FromValue
					);
				}
			}
		}




		/**
		* Doing the final update
		*/
		if($this->FinalizeUpdate)
		{
			$this->Mode 					= 'UPDATED';
			$this->arrayAffectedCustomer 	= array();

			foreach($_REQUEST as $name => $value)
			{
				/**
				* Only grab those request where the name start with "newvalue_"
				*/
				if(strpos($name, 'newvalue_') === 0)
				{
					$name 		= explode('_', $name);
					$customer 	= intval($name[1]);
					$dial 		= intval($name[2]);

					if($customer && $dial)
					{
						$Us2Dial = Us2DialPeer::retrieveByPk($dial);
						if($Us2Dial)
						{
							/* If dial is an image
							**********************************************/
							if($Us2Dial->getDialTypeId() == 2)
							{
									// Try getting what image options the dial currently have
									$Xml 			= $Us2Dial->getValueOptionsXml();
									$arrayOption	= array();

									try { $Xml = new SimpleXMLElement($Xml); } catch (Exception $Error){}

									foreach ($Xml->Options->Option as $Option)
										if ($Option) $arrayOption[] = "$Option";

									if(! in_array($value, $arrayOption)) {
										$arrayOption[] = "$value";
									}

									/* Save image options
									**********************************************/
									$XML = "<?xml version='1.0'?><Dial/>";
									$XML = new SimpleXMLElement($XML);

									$i=1;
									foreach($arrayOption as $ImageId)
									{
										$XML->Options->Option[$i] = "$ImageId";
										$i++;
									}
									$Us2Dial->setValueOptionsXml( $XML->asXML() );
							}

							# Make sure to add to the value options xml if it's an image
							$Us2Dial->setDefaultValue($value);
							$Us2Dial->save();

							$this->arrayAffectedCustomer[$customer] = $customer;
						}
					}
				}
			}
		}




	}

	public function executeDialSearchReplace()
	{
		/**
		* They should only be able to get here with the right permissions.
		* But let's do another check to make sure
		*/
		if($this->AccessControl->hasGroup('Product Manager MassUpdate') == false || $this->CustomerId > 0 || $this->DialId == 0)
			die("Access Restricted");



		$this->setLayout(false);
		$this->Mode = 'LIST';


		/**
		* Doing a preview of the update
		*/
		if($this->PreviewUpdate)
		{
			$this->Mode 						= 'PREVIEW';
			$arrayDialId 						= array();
			$arrayLibraryDialId 				= array();
			$this->arrayDialValue 				= array();
			$this->arrayCustomerLibraryDial 	= array();

			foreach($_REQUEST as $name => $value)
			{
				/**
				* Only grab those request where the name start with "dial_"
				*/
				if(strpos($name, 'dial_') === 0)
				{
					$name 		= explode('_', $name);
					$customer 	= intval($name[1]);
					$dial 		= intval($name[2]);

					if($customer && $dial)
					{
						$arrayDialId[] = $dial;
					}
				}
				elseif(strpos($name, 'productdial_') === 0)
				{
					$name 			= explode('_', $name);
					$customer 		= intval($name[1]);
					$librarydial 	= intval($name[2]);

					if($customer && $librarydial)
					{
						$arrayLibraryDialId[] = $librarydial;
					}
				}
			}




			if($arrayDialId)
			{
				$this->arrayDialValue = Us2DialPeer::GetDefaultValueByArrayId($arrayDialId);

				/**
				* Loop through the list and determine if we're completely replacing the value
				* or just searching and replacing part of the existing value
				*/
				foreach($arrayDialId as $DialId)
				{
					$DialValue = $this->arrayDialValue[$DialId];

					if($this->NewSearchValue)
					{
						$DialValue = str_ireplace($this->NewSearchValue, $this->NewReplaceValue, $DialValue);
					}
					else
					{
						$DialValue = $this->NewDialValue;
					}

					$this->arrayDialValue[$DialId] = $DialValue;
				}
			}



			if($arrayLibraryDialId)
			{
				$C = new Criteria;
				$C->addSelectColumn(Us2ProductLibraryPeer::CUSTOMER_ID);
				$C->addSelectColumn(Us2ProductLibraryPeer::NAME);
				$C->addSelectColumn(Us2ProductLibraryDialPeer::US2_PRODUCT_LIBRARY_DIAL_ID);
				$C->addSelectColumn(Us2ProductLibraryDialPeer::VALUE);
				$C->addJoin(Us2ProductLibraryDialPeer::US2_PRODUCT_LIBRARY_ID, Us2ProductLibraryPeer::US2_PRODUCT_LIBRARY_ID);
				$C->addAnd(Us2ProductLibraryDialPeer::US2_PRODUCT_LIBRARY_DIAL_ID, $arrayLibraryDialId, Criteria::IN);
				$Rs = Us2ProductLibraryDialPeer::doSelectRs($C);

				while($Rs->next())
				{
					$customer 		= $Rs->get(1);
					$name 			= $Rs->get(2);
					$librarydial 	= $Rs->get(3);
					$value 			= $Rs->get(4);

					if($this->NewSearchValue)
					{
						$value = str_ireplace($this->NewSearchValue, $this->NewReplaceValue, $value);
					}
					else
					{
						$value = $this->NewDialValue;
					}

					$this->arrayCustomerLibraryDial[$customer][$librarydial] = array(
						'library_name' 	=> $name,
						'value'			=> $value
					);
				}
			}
		}



		/**
		* Doing the final update
		*/
		if($this->FinalizeUpdate)
		{
			$this->Mode 						= 'UPDATED';
			$this->arrayDialValue 				= array();
			$this->arrayCustomerLibraryDial 	= array();


			foreach($_REQUEST as $name => $value)
			{
				/**
				* Only grab those request where the name start with "newvalue_"
				*/
				if(strpos($name, 'newvalue_') === 0)
				{
					$name 		= explode('_', $name);
					$customer 	= intval($name[1]);
					$dial 		= intval($name[2]);

					if($customer && $dial)
					{
						$Us2Dial = Us2DialPeer::retrieveByPk($dial);
						if($Us2Dial)
						{
							$Us2Dial->setDefaultValue($value);
							$Us2Dial->save();

							$this->arrayDialValue[$dial] = $value;
						}
					}
				}

				/**
				* See if we also need to replace product library dial values
				*/
				if(strpos($name, 'newlibdialvalue_') === 0)
				{
					$name 			= explode('_', $name);
					$customer 		= intval($name[1]);
					$librarydial 	= intval($name[2]);

					if($customer && $librarydial)
					{
						$Us2ProductLibraryDial = Us2ProductLibraryDialPeer::retrieveByPk($librarydial);
						if($Us2ProductLibraryDial)
						{
							$Us2ProductLibraryDial->setValue($value);
							$Us2ProductLibraryDial->save();

							$this->arrayCustomerLibraryDial[$customer][$librarydial] = array(
								'library_name' 	=> Us2ProductLibraryPeer::GetNameById( $Us2ProductLibraryDial->getUs2ProductLibraryId() ),
								'value'			=> $value
							);
						}
					}
				}
			}
		}



		$arrayCustomerId 				= array();
		$this->arrayCustomerDialValue 	= array();
		$this->Us2Dial 					= Us2DialPeer::retrieveByPk($this->DialId);


		/**
		* Look up all customer dial values for dial with the same uproduce name
		*/
		$C = new Criteria;
		$C->addAnd(Us2ProductCustomerDialPeer::US2_PRODUCT_ID, $this->ProductId);
		$C->addAnd(Us2ProductCustomerDialPeer::DEFAULT_US2_DIAL_ID, $this->DialId);
		$C->addAnd(Us2ProductCustomerDialPeer::ACTIVE_YN, 'Y');
		$C->addJoin(Us2ProductCustomerDialPeer::US2_DIAL_ID, Us2DialPeer::DIAL_ID);
		$C->addJoin(Us2ProductCustomerDialPeer::CUSTOMER_ID, CustomerPeer::CUSTOMER_ID);
		$C->addJoin(CustomerPeer::CLIENT_ID, ClientPeer::CLIENT_ID);
		$C->addSelectColumn(Us2ProductCustomerDialPeer::CUSTOMER_ID);
		$C->addSelectColumn(Us2ProductCustomerDialPeer::US2_DIAL_ID);
		$C->addSelectColumn(Us2DialPeer::DEFAULT_VALUE);
		$C->addSelectColumn(CustomerPeer::NAME);
		$C->addSelectColumn(ClientPeer::NAME);
		$C->addAscendingOrderByColumn(ClientPeer::NAME);
		$C->addAscendingOrderByColumn(CustomerPeer::NAME);
		$Rs = Us2ProductCustomerDialPeer::doSelectRs($C);

		while($Rs->next())
		{
			$this->arrayCustomerDialValue[] = array(
				'customer_id'	=> $Rs->get(1),
				'dial_id'		=> $Rs->get(2),
				'value'			=> $Rs->get(3),
				'name'			=> $Rs->get(4),
				'client_name'	=> $Rs->get(5)
			);

			$arrayCustomerId[$Rs->get(1)] = $Rs->get(1);
		}


		/**
		* Look up all available product library / product groups
		*/
		$this->arrayUniqueGroupName 		= array();
		$this->arrayCustomerProductLibrary	= array();


		$C = new Criteria;
		$C->addSelectColumn(Us2ProductLibraryPeer::US2_PRODUCT_LIBRARY_ID);
		$C->addSelectColumn(Us2ProductLibraryPeer::NAME);
		$C->addSelectColumn(Us2ProductLibraryPeer::CUSTOMER_ID);
		$C->addSelectColumn(Us2ProductLibraryDialPeer::US2_PRODUCT_LIBRARY_DIAL_ID);
		$C->addSelectColumn(Us2ProductLibraryDialPeer::VALUE);

		$C->addAnd(Us2ProductLibraryPeer::PRODUCT_ID, $this->ProductId);
		$C->addAnd(Us2ProductLibraryPeer::CUSTOMER_ID, $arrayCustomerId, Criteria::IN);
		#$C->addAnd(Us2ProductLibraryDialPeer::US2_PRODUCT_LIBRARY_ID, array_keys($arrayProductLibrary), Criteria::IN);
		$C->addAnd(Us2ProductLibraryDialPeer::DIAL_NAME, $this->Us2Dial->getuProduceDialName());

		$C->addJoin(Us2ProductLibraryDialPeer::US2_PRODUCT_LIBRARY_ID, Us2ProductLibraryPeer::US2_PRODUCT_LIBRARY_ID);
		$Rs = Us2ProductLibraryDialPeer::doSelectRs($C);

		while($Rs->next())
		{
			$ProductLibraryId 		= $Rs->get(1);
			$LibraryName 			= trim(strtoupper($Rs->get(2)));
			$CustomerId 			= $Rs->get(3);
			$ProductLibraryDialId 	= $Rs->get(4);
			$Value 					= $Rs->get(5);

			$this->arrayUniqueGroupName[$LibraryName] 	= $LibraryName;

			$this->arrayCustomerProductLibrary[$CustomerId][$ProductLibraryId] = array(
				'library_name' 		=> $LibraryName,
				'library_dial_id'	=> $ProductLibraryDialId,
				'value'				=> $Value
			);
		}




		return "_Success"; exit;
	}

	public function executeGroupProofing()
	{
		$this->setLayout(false);


		$arrayConfiguredCustomer 	= Us2ProductCustomerDialPeer::GetArrayCustomerByProduct($this->ProductId);
		$arrayCustomerClient		= CustomerPeer::GetClientByArrayCustomer($arrayConfiguredCustomer);
		$arrayClientId				= array_unique($arrayCustomerClient);
		$this->arrayClient 			= array(-1=>'Select a client') + ClientPeer::GetNameByArray($arrayClientId);

#		CustomerPeer::GetNameByArray();



		#``````````````````````````````````````````````````````````````
		# Sample list of makes/model
		$this->arrayMake = array(
					"Acura" 		=> "TSX", 			#ok
					"Alfa Romeo" 	=> "Milano",
					"Aston-Martin" 	=> "V8", 			#ok
					"Audi" 			=> "A4", 			#ok
					"Bentley" 		=> "Continental", 	#ok
					"BMW" 			=> "X6", 			#ok
					"Buick" 		=> "Regal", 		#ok
					"Cadillac" 		=> "XTS", 			#ok
					"Chevrolet" 	=> "Corvette", 		#ok
					"Chrysler" 		=> "300C", 			#ok
					"Daewoo"	 	=> "Lanos",
					"Daihatsu"	 	=> "Charade",
					"Dodge" 		=> "Charger", 		#ok
					"Ferrari" 		=> "California", 	#ok
					"Ford" 			=> "Focus", 		#ok
					"GMC" 			=> "Acadia", 		#ok
					"Gmc" 			=> "Acadia", 		#ok
					"Honda" 		=> "Pilot", 		#ok
					"Hummer" 		=> "H3",
					"Hyundai" 		=> "Sonata", 		#ok
					"Infiniti" 		=> "QX56", 			#ok
					"Isuzu" 		=> "NPR", 			#ok
					"Jaguar" 		=> "XKR", 			#ok
					"Jeep" 			=> "Patriot", 		#ok
					"Kia" 			=> "Sportage", 		#ok
					"Lamborghini" 	=> "Aventador", 	#ok
					"Land Rover" 	=> "LR4", 			#ok
					"Lexus" 		=> "LX", 			#ok
					"Lincoln" 		=> "Navigator", 	#ok
					"Lotus" 		=> "Esprit",
					"Maserati" 		=> "Quattroporte", 	#ok
					"Maybach" 		=> "Landaulet",
					"Mazda" 		=> "6", 			#ok
					"Mercedes-Benz" => "SLK", 			#ok
					"Mercury" 		=> "Grand Marquis", #ok 2010
					"Mini" 			=> "Cooper", 		#ok
					"Mitsubishi" 	=> "Lancer", 		#ok
					"Nissan" 		=> "Altima", 		#ok
					"Oldsmobile" 	=> "Alero", 		#ok 2004
					"Panoz" 		=> "Roadster",
					"Peugeot" 		=> "504",
					"Plymouth" 		=> "Caravelle",
					"Pontiac" 		=> "Solstice", 		#ok 2012
					"Porsche" 		=> "911", 			#ok
                    "Ram"           => "1500", 			#ok
					"Rolls Royce" 	=> "Park Ward",
					"Saab" 			=> "9-4X", 			#ok
					"Saturn" 		=> "Sky", 			#ok 2010
					"Scion" 		=> "tC",
					"Smart"			=> "Fortwo",
					"Subaru" 		=> "Forester", 		#ok
					"Suzuki" 		=> "Equator", 		#ok
					"Toyota" 		=> "Camry", 		#ok
					"Volkswagen" 	=> "Passat", 		#ok
					"Volvo" 		=> "XC60" 			#ok
		);


		$this->HandleGroupProof();
		$this->HandleSendToDashboard();
		return '_Success';
	}

	public function executeProofWithOptions()
	{
		#``````````````````````````````````````````````````````````````
		# Sample list of makes/model
		$this->arrayMake = array(
					"Acura" 		=> "TSX", 			#ok
					"Alfa Romeo" 	=> "Milano",
					"Aston-Martin" 	=> "V8", 			#ok
					"Audi" 			=> "A4", 			#ok
					"Bentley" 		=> "Continental", 	#ok
					"BMW" 			=> "X6", 			#ok
					"Buick" 		=> "Regal", 		#ok
					"Cadillac" 		=> "XTS", 			#ok
					"Chevrolet" 	=> "Corvette", 		#ok
					"Chrysler" 		=> "300C", 			#ok
					"Daewoo"	 	=> "Lanos",
					"Daihatsu"	 	=> "Charade",
					"Dodge" 		=> "Charger", 		#ok
					"Ferrari" 		=> "California", 	#ok
					"Ford" 			=> "Focus", 		#ok
					"GMC" 			=> "Acadia", 		#ok
					"Gmc" 			=> "Acadia", 		#ok
					"Honda" 		=> "Pilot", 		#ok
					"Hummer" 		=> "H3",
					"Hyundai" 		=> "Sonata", 		#ok
					"Infiniti" 		=> "QX56", 			#ok
					"Isuzu" 		=> "NPR", 			#ok
					"Jaguar" 		=> "XKR", 			#ok
					"Jeep" 			=> "Patriot", 		#ok
					"Kia" 			=> "Sportage", 		#ok
					"Lamborghini" 	=> "Aventador", 	#ok
					"Land Rover" 	=> "LR4", 			#ok
					"Lexus" 		=> "LX", 			#ok
					"Lincoln" 		=> "Navigator", 	#ok
					"Lotus" 		=> "Esprit",
					"Maserati" 		=> "Quattroporte", 	#ok
					"Maybach" 		=> "Landaulet",
					"Mazda" 		=> "6", 			#ok
					"Mercedes-Benz" => "SLK", 			#ok
					"Mercury" 		=> "Grand Marquis", #ok 2010
					"Mini" 			=> "Cooper", 		#ok
					"Mitsubishi" 	=> "Lancer", 		#ok
					"Nissan" 		=> "Altima", 		#ok
					"Oldsmobile" 	=> "Alero", 		#ok 2004
					"Panoz" 		=> "Roadster",
					"Peugeot" 		=> "504",
					"Plymouth" 		=> "Caravelle",
					"Pontiac" 		=> "Solstice", 		#ok 2012
					"Porsche" 		=> "911", 			#ok
                    "Ram"           => "1500", 			#ok
					"Rolls Royce" 	=> "Park Ward",
					"Saab" 			=> "9-4X", 			#ok
					"Saturn" 		=> "Sky", 			#ok 2010
					"Scion" 		=> "tC",
					"Smart"			=> "Fortwo",
					"Subaru" 		=> "Forester", 		#ok
					"Suzuki" 		=> "Equator", 		#ok
					"Toyota" 		=> "Camry", 		#ok
					"Volkswagen" 	=> "Passat", 		#ok
					"Volvo" 		=> "XC60" 			#ok
		);

		#``````````````````````````````````````````````````````````````
		# Get all makes from the Chrome database
		$this->arrayChromeMakeModel = array();
		$this->arrayChromeMake		= array();
		$this->arrayDivisionId		= array();

		$C = new Criteria();
		$C->addSelectColumn(ChromeMakePeer::DIVISION_ID);
		$C->addSelectColumn(ChromeMakePeer::MAKE);
		$C->addGroupByColumn(ChromeMakePeer::MAKE);
		$C->addAscendingOrderByColumn(ChromeMakePeer::MAKE);
		$Rs = ChromeMakePeer::doSelectRs($C);
		while($Rs->next()) {
			$this->arrayChromeMake[$Rs->get(1)] = $Rs->get(2);
			$this->arrayDivisionId[]			= $Rs->get(1);
		}

		#``````````````````````````````````````````````````````````````
		# Get all models for each make
		$C = new Criteria();
		$C->addSelectColumn(ChromeYearMakeModelStylePeer::DIVISION_ID);
		$C->addSelectColumn(ChromeYearMakeModelStylePeer::MODEL_NAME);
		$C->addGroupByColumn(ChromeYearMakeModelStylePeer::DIVISION_ID);
		$C->addGroupByColumn(ChromeYearMakeModelStylePeer::MODEL_NAME);
		$Rs = ChromeModelPeer::doSelectRs($C);
		while($Rs->next()) {
			$DivisionId = $Rs->get(1);
			$Model		= $Rs->get(2);
			$Make		= $this->arrayChromeMake[$DivisionId];
			$this->arrayChromeMakeModel[$Make][$Model] = $Model;
		}

		$C = new Criteria();
		$C->addSelectColumn(ChromeModelPeer::DIVISION_ID);
		$C->addSelectColumn(ChromeModelPeer::MODEL);
		$C->addGroupByColumn(ChromeModelPeer::DIVISION_ID);
		$C->addGroupByColumn(ChromeModelPeer::MODEL);
		$Rs = ChromeModelPeer::doSelectRs($C);
		while($Rs->next()) {
			$DivisionId = $Rs->get(1);
			$Model		= $Rs->get(2);
			$Make		= $this->arrayChromeMake[$DivisionId];
			$this->arrayChromeMakeModel[$Make][$Model] = $Model;
		}



		ksort($this->arrayChromeMakeModel);

		#``````````````````````````````````````````````````````````````
		# For whatever reason, chroma database isn't have all toyota models, we will have to hardcode these toyota models
		# in for now. Update or remove this array as necessary.
	#	$this->arrayChromeMakeModel['Toyota'] = array(
	#		'AVALON','TACOMA','TUNDRA','VENZA','YARIS','4RUNNER','CAMRY','CELICA','COROLLA','FJ CRUISER',
	#		'ECHO','HIGHLANDER','LAND CRUISER','MR2','MATRIX','PRIUS','RAV4','RAV4 EV','SIENNA','SEQUOIA','CAMRY SOLARA',
	#		'4RUNNER 4WD','4RUNNER SR5','CAMRY HYBRID','HIGHLANDER HYBRID','MR2 SPYDER','TUNDRA 2WD TRUCK',
	#		'TUNDRA 4WD TRUCK'
	#	);
		$this->arrayChromeMakeModel['Scion'][] = 'FR-S';
		$this->arrayChromeMakeModel['Scion'][] = 'iQ';
		#$this->arrayChromeMakeModel['Toyota'][] = 'RAV4 EV';

	#	sort($this->arrayChromeMakeModel['Toyota']);
	#	foreach($this->arrayChromeMakeModel['Toyota'] as &$___model)
	#	{
	#		if($___model != 'RAV4 EV')
	#			$___model = ucwords(strtolower($___model));
	#	}

		#``````````````````````````````````````````````````````````````
		# Get a list of previous live order products to proof against
		# These order products can contain real data necessary to drive the piece
		$this->arraySampleOrderProduct = array(0=>'----');

		$C = new Criteria;
		$C->addSelectColumn(Us2OrderProductPeer::ORDER_PRODUCT_ID);
		$C->addSelectColumn(Us2OrderProductPeer::PRODUCT_ID);
		$C->addSelectColumn(Us2OrderProductPeer::CUSTOMER_ID);
		$C->addSelectColumn(Us2OrderProductPeer::ADDED_DATE);
		$C->addAnd(Us2OrderProductPeer::PRODUCT_ID, $this->ProductId);
		$C->addAnd(Us2OrderProductPeer::FLAT_CSV_FILE_PATH, NULL, Criteria::ISNOTNULL);
		if($this->CustomerId) $C->addAnd(Us2OrderProductPeer::CUSTOMER_ID, $this->CustomerId);
		$C->addDescendingOrderByColumn(Us2OrderProductPeer::ADDED_DATE);
		$C->setLimit(10);
		$Rs = Us2OrderProductPeer::doSelectRs($C);
		while($Rs->next()) {
			$date = date('m/d/Y', strtotime($Rs->get(4)));
			if($date=='12/31/1969') $date = '--';

			$this->arraySampleOrderProduct[$Rs->get(1)] = $date.' - #'.$Rs->get(1).' - '.CustomerPeer::GetNameById($Rs->get(3));
		}


		#``````````````````````````````````````````````````````````````
		# Load product custom data to see if we have additional proof options available
		# 
		$Us2Product 				= Us2ProductPeer::retrieveByPk($this->ProductId);
		$CustomData 				= unserialize($Us2Product->getCustomData());
		$this->ExtraProofLayers 	= $CustomData['EXTRA_PROOF_LAYERS'];
       

		$this->LastProofOptions = Us2ProductLastProofOptionPeer::GetLastOptionByCustomerProduct($this->CustomerId, $this->ProductId);
		$this->HandleProof();
		return '_Success';
	}

	private function HandleProof()
	{
		/**
		* If they clicked on the proof button then build the csv and generate the proof
		************************************************************************************/
		if($this->Proof || $this->ProofPdfOnly || $this->ProofEmail)
		{
			$options = array();
			if($this->proofCustomerId) $this->CustomerId = $this->proofCustomerId;



			if($this->OrderProductId)					$options['order_product'] 							= $this->OrderProductId;
			if($this->SamplesJ2) 						$options['sample_sj2'] 								= true;
			if($this->Hijack)							$options['hijack']									= true;
			if($this->ConquestProof)					$options['conquest_proof']							= true;
			if($this->VIPLoyaltyMember)					$options['vip_loyalty_member']						= true;
			if($this->Us2ProductLibraryId)				$options['product_library_id']						= $this->Us2ProductLibraryId;
			if($this->ProofWithEquitySample)			$options['sample_equity']							= true;
			if($this->ProofWithTCSSBMileage)			$options['sample_tcssb_mileage']					= true;
			if($this->ProofWithSmartCoupon)				$options['sample_smart_coupon']						= true;
			#if($this->ExtraLayer)						$options['sample_extra_layers']						= $this->ExtraLayer;


			# Other Options
			if($this->TriggerDeclinedSvcBrakeAlert)		$options['trigger_declined_svc_brake_alert'] 		= true;
			if($this->TriggerDeclinedSvcBrakeWarning)	$options['trigger_declined_svc_brake_warning'] 		= true;
			if($this->TriggerDeclinedSvcTiresAlert)		$options['trigger_declined_svc_tires_alert'] 		= true;
			if($this->TriggerDeclinedSvcTiresWarning)	$options['trigger_declined_svc_tires_warning'] 		= true;
			if($this->TriggerDeclinedSvcBatteryAlert)	$options['trigger_declined_svc_battery_alert'] 		= true;
			if($this->TriggerDeclinedSvcBatteryWarning)	$options['trigger_declined_svc_battery_warning'] 	= true;
			if($this->TriggerDeclinedSvcGeneralAlert)	$options['trigger_declined_svc_general_alert'] 		= true;
			if($this->TriggerDeclinedSvcGeneralWarning)	$options['trigger_declined_svc_general_warning'] 	= true;
			if($this->EngineCode)						$options['sample_engine_code'] 						= $this->EngineCode;


			# Additional proof by product library (configuration group)
			if($this->ExtraProofProductLibraryName)
			{
				foreach($this->ExtraProofProductLibraryName as $Name)
				{
					$ProductLibraryId = $this->GetProductLibraryByName($this->CustomerId, $this->ProductId, $Name);

					if($ProductLibraryId)
					{
						$options['sample_product_library_id'][] = $ProductLibraryId;
					}
				}
			}





			if(!$this->Makes && !$this->MakeModel) $this->Makes[] = 'MAKE';

			foreach($this->Makes as $Make)
			{
				$sampleModel = $this->arrayMake["$Make"];
				if(!$sampleModel) $sampleModel = $this->arrayMake[strtoupper($Make)];

				$options['makes']["$Make"] = $sampleModel;
			}

			foreach($this->MakeModel as $_makeModel)
			{
				$_makeModel = explode('___', $_makeModel);
				$make 		= $_makeModel[0];
				$model		= $_makeModel[1];
				$make		= str_replace('_',' ',$make);
				$model		= str_replace('_',' ',$model);

				# Enable special vin for Rav4 EV model
				if(strtoupper($model) == 'RAV4 EV')
					$options['rav4_ev_vin'] = true;

				$options['models'][] = array('make'=>$make, 'model'=>$model);
			}




			/*`
			` Save proof options to history
			````````````````````````````````````````````````````````````````````*/
			if($this->Proof || $this->ProofPdfOnly)
			{
				$Us2ProductLastProofOption = new Us2ProductLastProofOption;
				$Us2ProductLastProofOption->setProductId($this->ProductId);
				$Us2ProductLastProofOption->setCustomerId($this->CustomerId);
				$Us2ProductLastProofOption->setData(serialize($options));
				$Us2ProductLastProofOption->setCreatedByUserId($this->AccessControl->UserId);
				$Us2ProductLastProofOption->setCreatedDate(date('Y-m-d H:i:s'));
				$Us2ProductLastProofOption->save();


				#if($this->AccessControl->UserId==3)
				#{
					#return $this->ScheduleProof($this->ProductId, $this->CustomerId, $options);
					#exit;
				#}
			}

			/*`
			` Get sample list data id from an order product
			````````````````````````````````````````````````````````````````````*/
			if($this->OrderProductId) $ListDataId = Us2OrderProductPeer::GetSampleListDataFromCsv($this->OrderProductId);


			/*`
			` Generate the sample proof data
			````````````````````````````````````````````````````````````````````*/
			$data = Us2ProductLastProofOptionPeer::CreateProofDataFromOptions($options, $ListDataId);

			/*`
			` Create a temporary uProduce CSV file
			````````````````````````````````````````````````````````````````````*/
			$this->uProduceCsvFile = SF_ROOT_DIR."/temp/data/";

			if(! file_exists($this->uProduceCsvFile))	mkdir($this->uProduceCsvFile, 0777) or die("Error: Cannot create directory $this->uProduceCsvFile");
			$this->uProduceCsvFile .= date('Ymd_'). md5(microtime(true)).'_'.mt_rand(9,999999999).'_'.mt_rand(9,999999999). '.csv';

			$file = fopen($this->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);





			/*` Proof the document
			````````````````````````````````````````````````````````````*/
			if($this->ProofPdfOnly) {
				uProduce::GenerateProofByCsvFile($this->ProductId, $this->CustomerId, $this->uProduceCsvFile, $this->Us2ProductLibraryId, $this->Us2ProductRevisionId);
				exit;
			}
			elseif($this->Proof) {
				# Note: Have to execute in view because to include_partial
			}
			elseif($this->ProofEmail)
			{
				$Aggregator 			= uProduce::GetProofArrayByCsvFile($this->ProductId, $this->CustomerId, $this->uProduceCsvFile, $this->Us2ProductLibraryId, $this->Us2ProductRevisionId);
				$arrayRecipientRecord	= $Aggregator->arrayRecipientRecord;

				$html 	= '<table><tr><td valign="top"><fieldset>{LIST}</fieldset></td><td><iframe src="" width="1000" height="700" name="frameEmailPreview" /></td></tr></table>';
				$list	= '';

				foreach($arrayRecipientRecord as $i => $data)
				{
					$RecipientCsvData 	= $data['RecipientCsvData'];
					$base64Data 		= base64_encode(serialize($RecipientCsvData));

					$list .= "
						<form action=\"/Email/Preview\" method=\"post\" target=\"frameEmailPreview\">
						<input type=\"hidden\" name=\"clientId\" value=\"$this->clientId\">
						<input type=\"hidden\" name=\"customerId\" value=\"$this->CustomerId\">
						<input type=\"hidden\" name=\"emailTemplateId\" value=\"$this->emailTemplateId\">
						<input type=\"hidden\" name=\"triggerNameId\" value=\"$this->triggerNameId\">
						<input type=\"hidden\" name=\"emailLayoutId\" value=\"$this->emailLayoutId\">
						<input type=\"hidden\" name=\"base64Data\" value=\"$base64Data\">
						<input type=\"hidden\" name=\"hideDataFile\" value=\"1\">
						<input type=\"submit\" name=\"viewEmail\" value=\"View $RecipientCsvData[MAKE]\">
						</form>
						<p>";
				}

				echo str_replace('{LIST}', $list, $html); exit;
			}
		}
	}

	private function HandleGroupProof()
	{
		/**
		* If they clicked on the proof button then build the csv and generate the proof
		************************************************************************************/
		if($this->ProofZip || $this->ProofPDF)
		{
			set_time_limit(600);

			# JobId generated for all proofs
			$arrayJobId 		= array();#1768562,1768563
			$arrayJobCustomer	= array();#1768562=>4227, 1768563=>9360
			$arrayCustomerPDF	= array();
			$arrayError 		= array();



			foreach($this->GetRequestParameter('CustomerId') as $CustomerId)
			{
				$options = array();

				#if($this->OrderProductId)			$options['order_product'] 			= $this->OrderProductId;
				#if($this->Us2ProductLibraryId)		$options['product_library_id']		= $this->Us2ProductLibraryId;
				if($this->SamplesJ2) 				$options['sample_sj2'] 				= true;
				if($this->Hijack)					$options['hijack']					= true;
				if($this->ConquestProof)			$options['conquest_proof']			= true;
				if($this->VIPLoyaltyMember)			$options['vip_loyalty_member']		= true;
				if($this->ProofWithEquitySample)	$options['sample_equity']			= true;
				if($this->ProofWithTCSSBMileage)	$options['sample_tcssb_mileage']	= true;
				if($this->ProofWithSmartCoupon)		$options['sample_smart_coupon']		= true;

				/*` Other Options
				```````````````````````````````````````````````````*/
				if($this->TriggerDeclinedSvcBrakeAlert)		$options['trigger_declined_svc_brake_alert'] 		= true;
				if($this->TriggerDeclinedSvcBrakeWarning)	$options['trigger_declined_svc_brake_warning'] 		= true;
				if($this->TriggerDeclinedSvcTiresAlert)		$options['trigger_declined_svc_tires_alert'] 		= true;
				if($this->TriggerDeclinedSvcTiresWarning)	$options['trigger_declined_svc_tires_warning'] 		= true;
				if($this->TriggerDeclinedSvcBatteryAlert)	$options['trigger_declined_svc_battery_alert'] 		= true;
				if($this->TriggerDeclinedSvcBatteryWarning)	$options['trigger_declined_svc_battery_warning'] 	= true;
				if($this->TriggerDeclinedSvcGeneralAlert)	$options['trigger_declined_svc_general_alert'] 		= true;
				if($this->TriggerDeclinedSvcGeneralWarning)	$options['trigger_declined_svc_general_warning'] 	= true;
				if($this->EngineCode)						$options['sample_engine_code'] 						= $this->EngineCode;


				/*` Get the makes and sample models
				```````````````````````````````````````````````````*/# 
				$makes = $this->GetRequestParameter("customer_{$CustomerId}_makes");

				if(!$makes) $makes[] = 'MAKE';

				foreach($makes as $make)
				{
					$sampleModel = $this->arrayMake["$make"];
					if(!$sampleModel) $sampleModel = $this->arrayMake[strtoupper($make)];
					if(!$sampleModel) $sampleModel = 'MODEL';

					$options['makes']["$make"] = $sampleModel;
				}

				/*`
				` Generate the sample proof data
				````````````````````````````````````````````````````````````````````*/
				$data = Us2ProductLastProofOptionPeer::CreateProofDataFromOptions($options);

				/*`
				` Save proof options to history
				````````````````````````````````````````````````````````````````````*/
				/*
				if($this->Proof || $this->ProofPdfOnly)
				{
					$Us2ProductLastProofOption = new Us2ProductLastProofOption;
					$Us2ProductLastProofOption->setProductId($this->ProductId);
					$Us2ProductLastProofOption->setCustomerId($this->CustomerId);
					$Us2ProductLastProofOption->setData(serialize($options));
					$Us2ProductLastProofOption->setCreatedByUserId($this->AccessControl->UserId);
					$Us2ProductLastProofOption->setCreatedDate(date('Y-m-d H:i:s'));
					$Us2ProductLastProofOption->save();
				}
				*/

				/*`
				` Create a temporary uProduce CSV file
				````````````````````````````````````````````````````````````````````*/
				$csv = SF_ROOT_DIR."/temp/data/";

				if(! file_exists($csv))	mkdir($csv, 0777) or die("Error: Cannot create directory $csv");
				$csv .= date('Ymd_'). md5(microtime(true)).'_'.mt_rand(9,999999999).'_'.mt_rand(9,999999999). '.csv';

				$file = fopen($csv, '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);



				/*`
				` Request all the proofs and save the job id generated.
				` After it's all done, we will try to request the PDFs for all
				` proof requests.
				````````````````````````````````````````````````````````````*/
				$result = uProduce::CreateJobByCsv($this->ProductId, $CustomerId, $csv);

				if($result['error']) {
					$arrayError[$CustomerId] = $result['error'];
				}

				if(!$result['job_id'])	{
					$arrayError[$CustomerId] = "Unable to generate proof for Customer #$CustomerId - ". CustomerPeer::GetNameById($CustomerId);
				} else {
					$id = $result['job_id'];
					$arrayJobId[] 			= $id;
					$arrayJobCustomer[$id]	= $CustomerId;
				}
			}

			/*`
			` Start getting the PDF for all the proofs
			````````````````````````````````````````````````````````````*/
			foreach($arrayJobId as $JobId)
			{
				$response 		= uProduce::GetPDFByJobId($JobId, true); # True, wait for results
				$CustomerId 	= $arrayJobCustomer[$JobId];
				$CustomerName 	= CustomerPeer::GetNameById($CustomerId);
				$pdf 			= $response['pdf'];
				$jpgs			= $response['jpgs'];

				if($response['error'] || !$pdf)
				{
					$CustomerName = CustomerPeer::GetNameById($CustomerId);
					$arrayError[$CustomerId] = "Proof for customer #$CustomerId ($CustomerName) failed to generate, please try again.";
				} else {
					$arrayCustomerPDF["$CustomerId - $CustomerName"] = $pdf;
				}
			}

			/*`
			` If we didn't get any error, go ahead and start assembling the pdfs
			````````````````````````````````````````````````````````````*/
			if(!$arrayError && $arrayCustomerPDF)
			{
				$output = $this->ProofZip ? 'zip' : 'pdf';
				$file 	= $this->CombineMultiPDF($arrayCustomerPDF, $output);

				if($file['url']) {
					header("Location: $file[url]"); exit;
				} else {
					$result['error'] = $file['error'];
				}
			}

			#echo '<pre>';
			#echo 'job';
			#print_r($arrayJobId);
			#echo 'error';
			#print_r($arrayError);
			#print_r($result);
			#print_r($arrayCustomerPDF);
			return $result;

		}
	}

	/**
	 * HandleSendToDashboard
	 */
	public function HandleSendToDashboard()
	{
		if($this->getRequestParameter('SendToDashboard'))
		{
			require_once(SF_ROOT_DIR.'/classes/class.product_configuration.php');
			$ProductConfiguration 	= new ProductConfiguration;
			$ProductId				= $this->getRequestParameter('ProductId');
			$CustomerId				= $this->getRequestParameter('CustomerId');

			if($CustomerId)
			{
				foreach($CustomerId as $id)
				{
					# Create a new change request case and link it to the approval for tracking purposes
					$this->Us2ProductChangeRequest = new Us2ProductChangeRequest;
					$this->Us2ProductChangeRequest->setProductId($ProductId);
					$this->Us2ProductChangeRequest->setCustomerId($id);
					$this->Us2ProductChangeRequest->setDescription('New Approval Requested');
					$this->Us2ProductChangeRequest->setStatus('UPDATED');
					$this->Us2ProductChangeRequest->setRequestedByUserId($this->AccessControl->UserId);
					$this->Us2ProductChangeRequest->setRequestedDate(date('Y-m-d H:i:s'));
					$this->Us2ProductChangeRequest->setLastHandledDate(date('Y-m-d H:i:s'));
					$this->Us2ProductChangeRequest->setLastHandledByUserId($this->AccessControl->UserId);
					$this->Us2ProductChangeRequest->save();
					$this->ProductChangeRequestId = $this->Us2ProductChangeRequest->getUs2ProductChangeRequestId();

					$this->Us2ProductChangeRequestHistory = new Us2ProductChangeRequestHistory;
					$this->Us2ProductChangeRequestHistory->setUs2ProductChangeRequestId($this->ProductChangeRequestId);
					$this->Us2ProductChangeRequestHistory->setHistoryType('STATUS_CHANGE');
					$this->Us2ProductChangeRequestHistory->setOldStatus('NA');
					$this->Us2ProductChangeRequestHistory->setNewStatus('UPDATED');
					$this->Us2ProductChangeRequestHistory->setCreatedDate(date('Y-m-d H:i:s'));
					$this->Us2ProductChangeRequestHistory->setCreatedByUserId($this->AccessControl->UserId);
					$this->Us2ProductChangeRequestHistory->save();

					$ProductConfiguration->AddConfigurationToLiveConfigQueue($ProductId, $id, $this->AccessControl->UserId, $this->ProductChangeRequestId);
				}

				$this->Message = "Product configurations for ". count($CustomerId) ." customers have been sent to the Production Dashboard.";
			} else
				$this->Message = 'Please select one or more customers';
		}
	}

	/**
	 * Combine all pdfs into one zip or pdf output file
	 * @param array $arrayPdfUrl array of pdf urls
	 * @param string $outputType zip or pdf
	 */
	private function CombineMultiPDF($arrayPdfUrl, $outputType='zip')
	{
		$arrayFiles = array();
		$result 	= array();

		foreach($arrayPdfUrl as $name => $url)
		{
			$name 			= str_replace(array('!','@','#','$','%','^','&','*','+','=','~','`','<','>','{','}','\\','/','"',"'",'?'), '', $name);
			$filename 		= "{$name}_".uniqid().".pdf";
			$data 			= file_get_contents($url);
			$file 			= fopen(SF_ROOT_DIR."/temp/data/multi_pdf/$filename", 'w');
			$arrayFiles[] 	= SF_ROOT_DIR."/temp/data/multi_pdf/$filename";

			fwrite($file, $data);
			fclose($file);
		}

		switch($outputType)
		{
			case 'zip':
				require_once(SF_ROOT_DIR.'/classes/class.zip_compress.php');
				$filename		= uniqid().'.zip';
				$destination 	= SF_ROOT_DIR."/web/temp/data/{$filename}";
				$ZipCompress	= new ZipCompress;
				$success		= $ZipCompress->create_zip($arrayFiles, $destination, $overwrite=true, $ignorefolders=true);

				if($success) 	$result['url'] 		= "http://gateway.printhd.us/temp/data/{$filename}";
				else 			$result['error'] 	= 'Unable to generate downloadable files, please try again later.';
			break;
			case 'pdf':
				$filename		= uniqid().'.pdf';
				$destination 	= SF_ROOT_DIR."/web/temp/data/{$filename}";

				/*`
				` Call the PDF Toolkit app to merge the pdf files
				```````````````````````````````````````````````````````````````````````````````````````````````````*/
				foreach($arrayFiles as $file) {
					$filelist[] = "'$file'";
				}

				exec("pdftk ". join(' ', $filelist) ." cat output $destination");

				if(file_exists($destination)) 
					$result['url'] = "http://gateway.printhd.us/temp/data/{$filename}";
				else 
					$result['error'] = 'Unable to generate downloadable files, please try again later.';
			break;
		}


		/*`
		` Clean up, remove all the temp files
		````````````````````````````````````````````````````````````*/
		foreach($arrayFiles as $path) {
			unlink($path);
		}


		return $result;
	}


	private function ScheduleProof($ProductId, $CustomerId, $options)
	{
		require_once(SF_ROOT_DIR.'/classes/class.product_configuration.php');
		$ProductConfiguration	= new ProductConfiguration;
		$StagingConfig			= $ProductConfiguration->GetCurrentConfiguration($ProductId, $CustomerId);
		$ProductLibraryId 		= $options['product_library_id'];

		/*`
		` Schedule a new proof request
		`````````````````````````````````````````````````````````````````````*/
		$Us2ProofSchedule = new Us2ProofSchedule;
		$Us2ProofSchedule->setProductId($ProductId);
		$Us2ProofSchedule->setCustomerId($CustomerId);
		$Us2ProofSchedule->setOptionData(serialize($options));
		$Us2ProofSchedule->setCreatedDate(date('Y-m-d H:i:s'));
		$Us2ProofSchedule->setCreatedByUserId($this->AccessControl->UserId);
		$Us2ProofSchedule->save();
		$Us2ProofScheduleId = $Us2ProofSchedule->getPrimaryKey();

		/*`
		` Create the detail list of changes
		`````````````````````````````````````````````````````````````````````*/
		foreach($StagingConfig as $source => $arrayChanges)
		{
			foreach($arrayChanges as $id => $value)
			{
				$Us2ProofScheduleData = new Us2ProofScheduleData;
				$Us2ProofScheduleData->setUs2ProofScheduleId($Us2ProofScheduleId);
				$Us2ProofScheduleData->setSource($source);
				$Us2ProofScheduleData->setSourceId($id);
				$Us2ProofScheduleData->setValue($value);
				$Us2ProofScheduleData->save();
			}
		}

		/*`
		` If we have a product library, get all of the preset dial/values from the library
		` and save the current configuration to the schedule
		`````````````````````````````````````````````````````````````````````*/
		if($ProductLibraryId)
		{
			$arrayDialValue = Us2ProductLibraryDialPeer::GetNameValuePairByLibrary($ProductLibraryId);
			foreach($arrayDialValue as $DialName => $value)
			{
				$Us2ProofScheduleData = new Us2ProofScheduleData;
				$Us2ProofScheduleData->setUs2ProofScheduleId($Us2ProofScheduleId);
				$Us2ProofScheduleData->setSource('PRODUCT_LIBRARY');
				$Us2ProofScheduleData->setSourceId($DialName);
				$Us2ProofScheduleData->setValue($value);
				$Us2ProofScheduleData->save();
			}
		}

		die("** Your proof request have been scheduled. Your request number is <big><b>$Us2ProofScheduleId</b></big>**<p>You can check the status of your proof request in the Proof Status and Proof Manager page.");
	}

	private function HandleProdApprovalDownloadZip()
	{
		$arrayLiveConfigId 	= $this->getRequestParameter('LiveConfigId');
		$arrayFiles 		= array();


		$Curl = curl_init();
		curl_setopt($Curl, CURLOPT_URL, "http://img4.printhd.us/getzippedproofs.php");
		curl_setopt($Curl, CURLOPT_POST, 8);
		curl_setopt($Curl, CURLOPT_POSTFIELDS, 'key=10OYwla0238JKasd897123jkaDALPQAv&LiveConfigId[]='. join('&LiveConfigId[]=', $arrayLiveConfigId));
		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['url']) 
		{
			$this->ErrorMessage = 'Unable to generate downloadable files, please try again later.';

			if($response['errors'])
				$this->ErrorMessage = $response['errors'][0];
		}
		else
		{
			header("Location: $response[url]"); exit;
		}


		return '_Success';
	}

	private function HandleProductionApproval()
	{
		$this->ErrorMessage =	'';
		$customerId			= $this->getRequestParameter('CustomerId');
		$clientId			= $this->getRequestParameter('ClientId');
                                
        if($clientId)
		{
			if($clientId != 'NONE') {
				$arrayCustomers = CustomerPeer::GetCustomersByClient($clientId);
				$this->arrayFilteredCustomerId = array_keys($arrayCustomers);
			}
		}
		if($customerId)
		{
			if($customerId != 'NONE')   {
				$this->arrayFilteredCustomerId = array($customerId);
			}
		}

		if($this->filter)
		{
			switch($this->filter)
			{
				case 'campaign':
					$this->arrayFilterProduct 		= Us2ProductGroupPeer::GetProductsInGroup(array(), 'campaign', 'LIKE');
					$this->ProductCriteria			= 'IN';
				break;
				case 'trigger':
					$this->arrayFilterProduct 		= Us2ProductGroupPeer::GetProductsInGroup(array(), 'campaign', 'LIKE');
					$this->ProductCriteria			= 'NOTIN';
				break;
			}
		}



			/* Approve for production. Flag live config for approval so
			` script can pick it up and sync data to production db
			````````````````````````````````````````````````*/
			if($_REQUEST['Approve'] || $_REQUEST['ApproveFinal'])
			{
				foreach($_REQUEST['LiveConfigId'] as $LiveConfigId)
				{
					$Us2ProductLiveConfig = Us2ProductLiveConfigPeer::retrieveByPk($LiveConfigId);
					if($Us2ProductLiveConfig)
					{
						$CustomerId = $Us2ProductLiveConfig->getCustomerId();
						$ProductId	= $Us2ProductLiveConfig->getProductId();
						$ClientId	= CustomerPeer::GetClientByCustomer($CustomerId);
						$date 		= date('Y-m-d H:i:s', strtotime($Us2ProductLiveConfig->getCreatedDate()));
						$continue	= true;

						if(in_array($ClientId, array(20,369,260,403,570)))	$status = 'CSR_APPROVED';
						else				$status = 'APPROVED';

						if($_REQUEST['ApproveFinal']) $status = 'APPROVED';

						/*`
						` Check queue for pending approval. If there are older revision still pending
						` for the same customer/product, alert the user and do not let them proceed.
						` Older revision needs to be rejected/approved first.
						``````````````````````````````````````````````````````*/
						$checkApprovalStatus = ($status=='APPROVED') ? array('APPROVED', 'REJECTED') : array('CSR_APPROVED', 'CSR_REJECTED', 'APPROVED', 'REJECTED');

						$C = new Criteria;
						$C->addAnd(Us2ProductLiveConfigPeer::CUSTOMER_ID, $CustomerId);
						$C->addAnd(Us2ProductLiveConfigPeer::PRODUCT_ID, $ProductId);
						$C->addAnd(Us2ProductLiveConfigPeer::CREATED_DATE, $date, Criteria::LESS_THAN);
						$C->addAnd(Us2ProductLiveConfigPeer::APPROVAL_STATUS, $checkApprovalStatus, Criteria::NOT_IN);
						$count = Us2ProductLiveConfigPeer::doCount($C);

						if($count) {
							$ProductName	= Us2ProductPeer::GetNameById($ProductId);
							$CustomerName	= CustomerPeer::GetNameById($CustomerId);
							$this->ErrorMessage .= "&bull; There are older proofs for ($CustomerName - $ProductName) that needs to be addressed first before you can approve #$LiveConfigId.<br>";
							$continue = false;
						}





						if($continue==false) continue;


						$Us2ProductLiveConfig->setApprovalStatus($status);
						$Us2ProductLiveConfig->setApprovedByUserId($this->AccessControl->UserId);
						$Us2ProductLiveConfig->setApprovedDate(date('Y-m-d H:i:s'));
						$Us2ProductLiveConfig->save();

						if($id = $Us2ProductLiveConfig->getUs2ProductChangeRequestId())
						{
							$Us2ProductChangeRequest = Us2ProductChangeRequestPeer::retrieveByPk($id);
							$oldStatus = $Us2ProductChangeRequest->getStatus();
							$Us2ProductChangeRequest->setStatus('APPROVED');
							$Us2ProductChangeRequest->save();

							$Us2ProductChangeRequestHistory = new Us2ProductChangeRequestHistory;
							$Us2ProductChangeRequestHistory->setUs2ProductChangeRequestId($id);
							$Us2ProductChangeRequestHistory->setHistoryType('STATUS_CHANGE');
							$Us2ProductChangeRequestHistory->setNotes('');
							$Us2ProductChangeRequestHistory->setOldStatus($oldStatus);
							$Us2ProductChangeRequestHistory->setNewStatus('APPROVED');
							$Us2ProductChangeRequestHistory->setCreatedDate(date('Y-m-d H:i:s'));
							$Us2ProductChangeRequestHistory->setCreatedByUserId($this->AccessControl->UserId);
							$Us2ProductChangeRequestHistory->save();

							/*`
							` Send alert to client
							``````````````````````````````````````````````````````*/
							if($status != 'APPROVED')
							{
								Us2ProductChangeRequestPeer::SendStatusUpdateAlert($id, $status);
							}
						}

						/*`
						` Send alert to client
						``````````````````````````````````````````````````````*/
///						if($status=='CSR_APPROVED')
//						{
//							$Alert		= Us2ProductChangeRequestAlertPeer::GetAlertByClient($ClientId);
//							$Options	= unserialize($Alert->getOptions());
//							$email 		= Us2ProductLiveConfigPeer::CreateProofReadyAlertEmail($LiveConfigId, $Options);
//
//							if($email && $Options['send_copy_to_dealer_profile_email'])
//							{
//								require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'class.alert_email.php');
//								require_once(SF_ROOT_DIR.'/classes/class.customer_profile.php');
//
//								$AlertEmail			= new AlertEmail();
//								$CustomerProfile	= new CustomerProfile(false, $Us2ProductLiveConfig->getCustomerId());
//								$DefaultProfileId	= $CustomerProfile->GetDefaultProfile();
//								$ProfileData		= $CustomerProfile->GetProfileData($DefaultProfileId);
//								$arrayAddress		= array();
//
//								foreach($Options['send_copy_to_dealer_profile_email'] as $fieldName)
//								{
//									$address = trim($ProfileData["$fieldName"]);
//									if($address) $arrayAddress["$address"] = $address;
//								}
//
//								foreach($arrayAddress as $address)
//								{
//									$AlertEmail->SendStatusEmail(array("$address" => "$address"), $email['subject'], $email['body'], "admin@ammsusa.com","Proof Ready");
//								}
//							}
//						}



					}
				}
			}
			elseif($_REQUEST['Reject'])
			{
					if($_REQUEST['LiveConfigId'])
					{
						$this->setTemplate("ProductionApproval");
						return '_ConfirmReject';
					}
			}
			elseif($_REQUEST['ConfirmReject'])
			{
					foreach($this->getRequestParameter('LiveConfigId') as $LiveConfigId)
					{
						$Us2ProductLiveConfig = Us2ProductLiveConfigPeer::retrieveByPk($LiveConfigId);
						if($Us2ProductLiveConfig)
						{
							$Us2ProductLiveConfig->setApprovalStatus('REJECTED');
							$Us2ProductLiveConfig->setApprovedByUserId($this->AccessControl->UserId);
							$Us2ProductLiveConfig->setApprovedDate(date('Y-m-d H:i:s'));
							$Us2ProductLiveConfig->save();

							if($id = $Us2ProductLiveConfig->getUs2ProductChangeRequestId())
							{
								$Us2ProductChangeRequest = Us2ProductChangeRequestPeer::retrieveByPk($id);
								$oldStatus = $Us2ProductChangeRequest->getStatus();
								$Us2ProductChangeRequest->setStatus('REJECTED');
								$Us2ProductChangeRequest->save();

								$Us2ProductChangeRequestHistory = new Us2ProductChangeRequestHistory;
								$Us2ProductChangeRequestHistory->setUs2ProductChangeRequestId($id);
								$Us2ProductChangeRequestHistory->setHistoryType('STATUS_CHANGE');
								$Us2ProductChangeRequestHistory->setNotes(trim($this->getRequestParameter("reject_note_{$LiveConfigId}")));
								$Us2ProductChangeRequestHistory->setOldStatus($oldStatus);
								$Us2ProductChangeRequestHistory->setNewStatus('REJECTED');
								$Us2ProductChangeRequestHistory->setCreatedDate(date('Y-m-d H:i:s'));
								$Us2ProductChangeRequestHistory->setCreatedByUserId($this->AccessControl->UserId);
								$Us2ProductChangeRequestHistory->save();

								Us2ProductChangeRequestPeer::SendStatusUpdateAlert($id, 'REJECTED');
							}
						}
					}

					$this->redirect("/smanager?token=".Convert::EncodeUrl('Page=ProductionApproval')."=&ClientId={$this->ClientId}&CustomerId={$this->CustomerId}"); exit;
			}
			elseif($_REQUEST['ApproveRevision'])
			{
				$dmsConnection = Propel::GetConnection('dms_main');
				foreach($_REQUEST['ProfileRevisionId'] as $ProfileRevisionId)
				{
					$query = "UPDATE customer_profile_revision SET approval_status='APPROVED', approved_by_user_id='".$this->AccessControl->UserId."', approved_date='".date('Y-m-d H:i:s')."' WHERE customer_profile_revision_id='$ProfileRevisionId' ";
					$dmsConnection->executeQuery($query);
				}
			}
			elseif($_REQUEST['RejectRevision'])
			{
				require_once(SF_ROOT_DIR . '/classes/class.customer_profile.php');
				$CustomerProfile = new CustomerProfile;

				$dmsConnection = Propel::GetConnection('dms_main');
				foreach($_REQUEST['ProfileRevisionId'] as $ProfileRevisionId)
				{
					$RevisionInfo 		= $CustomerProfile->GetRevisionInfo($ProfileRevisionId);
					$CustomerId			= $RevisionInfo['customer_id'];
					$ClientId			= CustomerPeer::GetClientByCustomer($CustomerId);
					$ProfileConfigId 	= CustomerProfileConfigPeer::GetConfigIdByClientDomain($ClientId, 'DEFAULT');
					$CustomerProfile 	= new CustomerProfile($ProfileConfigId);

					$query = "UPDATE customer_profile_revision SET approval_status='REJECTED', approved_by_user_id='".$this->AccessControl->UserId."', approved_date='".date('Y-m-d H:i:s')."' WHERE customer_profile_revision_id='$ProfileRevisionId'  ";
					$dmsConnection->executeQuery($query);

					$CustomerProfile->RevertChanges($ProfileRevisionId, true);
				}
			}





	}

	private function ProcessLiveProductApproval()
	{
			require_once(SF_ROOT_DIR.'/classes/class.product_configuration.php');

			/*`
			` Get the current live product configuration
			````````````````````````````````````````````````````````*/
			$this->ProductChangeRequestId	= intval($this->ProductChangeRequestId);
			$ProductConfiguration 			= new ProductConfiguration;
			$this->LiveConfigId 			= $ProductConfiguration->GetCurrentLiveConfiguration($this->ProductId, $this->CustomerId);
			#$this->arrayChanges 			= $ProductConfiguration->GetConfigurationChanges($this->ProductId, $this->CustomerId);
			$this->arrayChanges				= array(1);

			if($this->LiveConfigId)
				$this->Us2ProductLiveConfig = Us2ProductLiveConfigPeer::retrieveByPk($this->LiveConfigId);


		 
			/*`
			` Request live product config approval
			````````````````````````````````````````````````````````*/
			if($this->ActivateConfig)
			{
				if($this->ProductChangeRequestId)
				{
					$this->Us2ProductChangeRequest = Us2ProductChangeRequestPeer::retrieveByPk($this->ProductChangeRequestId);
					$OldStatus = $this->Us2ProductChangeRequest->getStatus();
					$this->Us2ProductChangeRequest->setStatus('UPDATED');
					$this->Us2ProductChangeRequest->save();

					$this->Us2ProductChangeRequestHistory = new Us2ProductChangeRequestHistory;
					$this->Us2ProductChangeRequestHistory->setUs2ProductChangeRequestId($this->ProductChangeRequestId);
					$this->Us2ProductChangeRequestHistory->setHistoryType('STATUS_CHANGE');
					$this->Us2ProductChangeRequestHistory->setOldStatus($OldStatus);
					$this->Us2ProductChangeRequestHistory->setNewStatus('UPDATED');
					$this->Us2ProductChangeRequestHistory->setCreatedDate(date('Y-m-d H:i:s'));
					$this->Us2ProductChangeRequestHistory->setCreatedByUserId($this->AccessControl->UserId);
					$this->Us2ProductChangeRequestHistory->save();

					#Us2ProductChangeRequestPeer::SendStatusUpdateAlert($this->ProductChangeRequestId);
				}
				else
				{
					# Create a new change request case and link it to the approval for tracking purposes
					$this->Us2ProductChangeRequest = new Us2ProductChangeRequest;
					$this->Us2ProductChangeRequest->setProductId($this->ProductId);
					$this->Us2ProductChangeRequest->setCustomerId($this->CustomerId);
					$this->Us2ProductChangeRequest->setDescription('New Approval Requested');
					$this->Us2ProductChangeRequest->setStatus('UPDATED');
					$this->Us2ProductChangeRequest->setRequestedByUserId($this->AccessControl->UserId);
					$this->Us2ProductChangeRequest->setRequestedDate(date('Y-m-d H:i:s'));
					$this->Us2ProductChangeRequest->setLastHandledDate(date('Y-m-d H:i:s'));
					$this->Us2ProductChangeRequest->setLastHandledByUserId($this->AccessControl->UserId);
					$this->Us2ProductChangeRequest->save();
					$this->ProductChangeRequestId = $this->Us2ProductChangeRequest->getUs2ProductChangeRequestId();

					$this->Us2ProductChangeRequestHistory = new Us2ProductChangeRequestHistory;
					$this->Us2ProductChangeRequestHistory->setUs2ProductChangeRequestId($this->ProductChangeRequestId);
					$this->Us2ProductChangeRequestHistory->setHistoryType('STATUS_CHANGE');
					$this->Us2ProductChangeRequestHistory->setOldStatus('NA');
					$this->Us2ProductChangeRequestHistory->setNewStatus('UPDATED');
					$this->Us2ProductChangeRequestHistory->setCreatedDate(date('Y-m-d H:i:s'));
					$this->Us2ProductChangeRequestHistory->setCreatedByUserId($this->AccessControl->UserId);
					$this->Us2ProductChangeRequestHistory->save();

					#Us2ProductChangeRequestPeer::SendStatusUpdateAlert($this->ProductChangeRequestId);
				}

				$this->newLiveConfigId = $ProductConfiguration->AddConfigurationToLiveConfigQueue($this->ProductId, $this->CustomerId, $this->AccessControl->UserId, $this->ProductChangeRequestId);



				#$email 				= Us2ProductLiveConfigPeer::CreateNewApprovalRequestAlertEmail($newLiveConfigId);
				#
				#require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'class.alert_email.php');
				#$AlertEmail	= new AlertEmail();
				#$AlertEmail->SendStatusEmail(array('changerequest@ammsusa.com'=>'changerequest@ammsusa.com'), $email['subject'], $email['body'], "admin@ammsusa.com","Approval Required");
			}

			/*`
			` Get pending configuration approvals
			````````````````````````````````````````````````````````*/
			$this->arrayPendingLiveConfigId = $ProductConfiguration->GetPendingConfiguration($this->ProductId, $this->CustomerId);

			/*`
			` If there are no changes between current staging and live production config then disable the button
			````````````````````````````````````````````````````````*/
			if(!$this->arrayChanges)
				$this->disabled = 'disabled="disabled"';
			#else
			#	echo '<pre>'. print_r($arrayChanges, true). '</pre>';

			#<fieldset style=" border:1px solid #dddddd; border-top:2px solid #aaaaaa; background-color:#E7F2F2; padding:12px; background-image:url('http://admin.printhd.us/images/top_bgk.gif'); background-repeat:repeat-x">


	}

	private function UpdateProductACL()
	{
		$arrayCurrentACL	= array();
		$arrayNewACL		= array();

		foreach($_REQUEST as $name => $value)
		{
			if(strpos($name, 'current_customer_product_')===0)
			{
				$parts 		= explode('_', $name, 5);
				$CustomerId	= intval($parts[3]);
				$ProductId	= intval($parts[4]);

				$arrayCurrentACL[$ProductId][$CustomerId] = $value;
			}
			elseif(strpos($name, 'checkbox_customer_product')===0)
			{
				$parts 		= explode('_', $name, 5);
				$CustomerId	= intval($parts[3]);
				$ProductId	= intval($parts[4]);

				$arrayNewACL[$ProductId][$CustomerId] = $value;
			}
		}

		/*`
		` Update existing ACL if new settings doesn't match existing
		`````````````````````````````````````````````````````````````````*/
		foreach($arrayCurrentACL as $ProductId => $arrayCustomerValue)
		{
			foreach($arrayCustomerValue as $CustomerId => $value)
			{
				if($arrayNewACL[$ProductId][$CustomerId] != $value)
				{
					# -1 = everyone, 147 product manager superadmin
					Us2ProductAclPeer::AddUpdatePermission($ProductId, -1, 'CUSTOMER', $CustomerId, array('hide'=>$arrayNewACL[$ProductId][$CustomerId]));
					Us2ProductAclPeer::AddUpdatePermission($ProductId, 147, 'CUSTOMER', $CustomerId, array('hide'=>'N'));
				}
			}
		}

		/*`
		` Update new ACL settings
		`````````````````````````````````````````````````````````````````*/
		foreach($arrayNewACL as $ProductId => $arrayCustomerValue)
		{
			foreach($arrayCustomerValue as $CustomerId => $value)
			{
				# -1 = everyone, 147 product manager superadmin
				Us2ProductAclPeer::AddUpdatePermission($ProductId, -1, 'CUSTOMER', $CustomerId, array('hide'=>$value));
				Us2ProductAclPeer::AddUpdatePermission($ProductId, 147, 'CUSTOMER', $CustomerId, array('hide'=>'N'));
			}
		}

	}

	private function executeProductListingManager()
	{
		if($this->UpdateACL) $this->UpdateProductACL();


		$this->setTemplate("ProductListingManager");
		$GLOBALS['skip_javascript'] = true;
		#$this->getResponse()->addJavascript('/sf/prototype/js/prototype.js');
		$this->getResponse()->addJavascript('/js/jquery.1.5/jquery-1.5.1.min.js');


		$this->arrayStore	= array(0 => '-- select store --');
		$this->arrayProduct = array(0 => '-- select product --');
		$this->arrayResult	= array();

		$C = new Criteria;
		$C->addSelectColumn(Us2StorePeer::STORE_ID);
		$C->addSelectColumn(Us2StorePeer::NAME);
		$C->addAscendingOrderByColumn(Us2StorePeer::NAME);
		$C->addAnd(Us2StorePeer::ACTIVE_YN, 'Y');
		$Rs = Us2StorePeer::doSelectRs($C);
		while($Rs->next()) {
			$this->arrayStore[$Rs->get(1)] = $Rs->get(1) .' - '. $Rs->get(2);
		}



		if($this->BrowseType=='ByProduct')
		{
			$arrayCustomCustomerId 		= Us2ProductCustomerDialPeer::GetArrayCustomerByProduct($this->ProductId);
			$arrayCustomerClientId		= CustomerPeer::GetClientByArrayCustomer($arrayCustomCustomerId);
			$this->arrayCustomerName	= CustomerPeer::GetNameByArrayId($arrayCustomCustomerId);
			$this->arrayProductName		= array($this->ProductId => Us2ProductPeer::GetNameById($this->ProductId));
			$this->arrayACL 			= array($this->ProductId => Us2ProductAclPeer::GetByProductType($this->ProductId, $SourceType='CUSTOMER'));

			if(!$this->arrayCustomerName) $this->arrayCustomerName = array();
			asort($this->arrayCustomerName);

			foreach($this->arrayCustomerName as $customerId => $customerName)
			{
				$clientId = $arrayCustomerClientId[$customerId];
				$this->arrayResult[$clientId][$customerId][] = $this->ProductId;
			}
		}
		elseif($this->BrowseType=='ByCustomer')
		{
			$arrayProductId 			= Us2ProductCustomerDialPeer::GetArrayProductByCustomer($this->CustomerId);
			$this->arrayCustomerName 	= array($this->CustomerId => CustomerPeer::GetNameById($this->CustomerId));
			$this->arrayProductName		= Us2ProductPeer::GetNameByArray($arrayProductId);
			$this->arrayACL 			= array();

			foreach($arrayProductId as $productId)
			{
				$this->arrayACL[$productId] = Us2ProductAclPeer::GetByProductType($productId, $SourceType='CUSTOMER', $SourceValue=$this->CustomerId);
				$this->arrayResult[CustomerPeer::GetClientByCustomer($this->CustomerId)][$this->CustomerId][] = $productId;
			}
		}



		return '_Success';
	}


	private function UploadDialImage()
	{
		$TriggeredFrom  = $_REQUEST['TriggeredFrom'];
		$DialId 		= intval($_REQUEST['DialId']);
		$imageFile		= $_FILES['imageFile']; 
		$PathInfo		= pathinfo($imageFile['name']);
		$imageName 		= $PathInfo['basename'];
		$imageName 		= str_replace("'", '', $imageName);
		$imageName 		= str_replace('"', '', $imageName);
		$Ext			= strtoupper($PathInfo['extension']);

		# Double check where we're posting from
		if($TriggeredFrom=='ProductManager' && $DialId)
		{
			ini_set("memory_limit", "1024M");
			ini_set("upload_max_filesize", "100M");

			require_once(SF_ROOT_DIR . "/apps/admin/modules/smanager/lib/general.class.php");
			$General = new General();


			/**
			* Try uploading the image
			*************************************************************************/
			if($imageName)
			{
			 	$Success 		= $General->UploadAssetImage(0, $imageFile, $imageName);
				$ErrorMessage	= $General->ErrorMessage;
				$ImageId 		= $General->ImageId;
			}
			else
				$ErrorMessage = 'Unable to upload image';
		}


		if(!$ErrorMessage && $ImageId)
		{
			$Us2Image = Us2ImagePeer::retrieveByPk($ImageId);

			echo "
			<script>
				if(typeof parent.AssignUploadedImageToDial == \"function\")
					parent.AssignUploadedImageToDial('$ImageId', '$DialId', '". $Us2Image->getPreviewUrl() ."', '". htmlentities($Us2Image->getName()) ."');
			</script>
			";
		}
		else 
		{
			if(!$ErrorMessage)
				$ErrorMessage = 'Unable to upload image';

			#echo "Error: $ErrorMessage $DialId";
		}


		echo '
			<script>
				if(typeof parent.ResetImageUploadSpin == "function")
					parent.ResetImageUploadSpin("'. $ErrorMessage .'");
			</script>
		';



		return sfView::NONE;
	}


	/**
	* Get product configuration group (us2_product_library) if by name
	*********************************************************************************/
	public function GetProductLibraryByName($CustomerId, $ProductId, $Name)
	{
		# Get the product library id
		$ProductLibraryId = 0;

		$C = new Criteria;
		$C->addSelectColumn(Us2ProductLibraryPeer::US2_PRODUCT_LIBRARY_ID);
		$C->addAnd(Us2ProductLibraryPeer::CUSTOMER_ID, $CustomerId);
		$C->addAnd(Us2ProductLibraryPeer::PRODUCT_ID, $ProductId);
		$C->addAnd(Us2ProductLibraryPeer::NAME, $Name);
		$C->setLimit(1);
		$Rs = Us2ProductLibraryPeer::doSelectRs($C);

		while($Rs->next())
			$ProductLibraryId = $Rs->get(1);

		return $ProductLibraryId;
	}

}
