<?php

require_once(SF_ROOT_DIR . '/classes/class.cyber_hackney.php');
require_once(SF_ROOT_DIR . '/apps/' . SF_APP . '/lib/CallCenterRequest.class.php');
require_once(SF_ROOT_DIR . '/apps/' . SF_APP . '/lib/CyberHackneyRequest.class.php');

/**
 * defaultActions actions.
 *
 * @package		defaultActions
 * @subpackage	defaultActions
 * @author		Lom Van Nguyen
 * @version		SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */

define ('DEBUG', 		false);
define ('HOME',			1);
define ('PRODUCTS', 	2);
define ('WORKSPACE',	3);
define ('CART', 		4);
define ('CHECKOUT', 	5);
define ('CUSTOMIZE', 	6);
define ('ORDER', 		7);
define ('REVIEW', 		8);
define ('RECIPIENT', 	9);
define ('SUMMARY', 		10);
define ('ORDER_REVIEW', 11);
define ('HELP', 		12);
define ('VIEW', 		13);
define ('ARTICLE', 		14);
define ('WB2PRINT', 	15);
define ('PROOF', 		16);
define ('CUSTOMER_REPORT',	17);


class defaultActions extends sfActions
{
	private $CAmmsPricing = null;

	/**
	* The code inserted here is executed at the beginning of each action call
	*********************************************************************************/
	public function preExecute()
	{
		// If this is the HDAutoInfo store
		if (in_array(STORE_ID, array(AUTOLOOP_STORE_ID, HDAUTOINFO_STORE_ID))) {
			$headers = getallheaders();
			if (array_key_exists('Origin', $headers)) {
				$Origin = $headers['Origin'];
			} else {
				$Origin = $this->getRequestParameter("Origin", '');
			}
			// Allow access to the WordPress site, with or without https
			if (preg_match("|^http[s]?://hdautoinfo.com$|", $Origin)) {
				header( "Access-Control-Allow-Origin: " . $Origin);
			}
		}
		$this->AccessControl = new AccessControl($this);

		$accessGroup		= array('ADMIN','STORE ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST');
		$this->customListAccess	= array('ADMIN','STORE ADMIN','STORE_LIST_MANAGER');
		$isAuthenticated	= $this->AccessControl->isAuthenticated;
		$hasAccess			= $this->AccessControl->hasGroup( $accessGroup );

		if ($isAuthenticated) {
			$AmmsAuthUser = $this->AccessControl->TouchAmmsAuthUser();
			if ($AmmsAuthUser !== false) {
				$this->AccessControl->AmmsAuthUserId = $AmmsAuthUser["ammsauth_user_id"];
			}
		}

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

			$this->$name = $value;
		}

		require_once SF_ROOT_DIR . '/includes/common/class.convert.php';
		require_once SF_ROOT_DIR . '/includes/common/class.validator.php';

		$this->includeMenu = true;

		$token		= $this->getRequestParameter('token');
		$request	= Convert::DecodeURL($token);

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

		// If this is a single signon
		$sso_token	= $this->getRequestParameter('sso_token');
		if (!empty($sso_token)) {
			return $this->executeSso($sso_token);
		}

		// Load proxy and current IDs
		$ProxyCustomerId = $this->getUser()->getAttribute('ProxyCustomerId');
		$this->CurrentCustomerId = (!empty($ProxyCustomerId)) ? $ProxyCustomerId : $this->AccessControl->CustomerId;
		$ProxyClientId = $this->getUser()->getAttribute('ProxyClientId');
		$this->CurrentClientId = (!empty($ProxyClientId)) ? $ProxyClientId : CustomerPeer::GetClientByCustomer($this->CurrentCustomerId);
		$ProxyUserId = $this->getUser()->getAttribute('ProxyUserId');
		$this->CurrentUserId = (!empty($ProxyUserId)) ? $ProxyUserId : $this->AccessControl->UserId;
		$CurrentAmmsAuthUser = $this->AccessControl->TouchAmmsAuthUser($this->CurrentUserId);
		if ($CurrentAmmsAuthUser !== false) {
			$this->CurrentAmmsAuthUserId = $CurrentAmmsAuthUser["ammsauth_user_id"];
		}

		$this->DisplayCEClientSelector = false;
	}


	/**
	* The code inserted here is executed at the end of each action call
	*********************************************************************************/
	public function postExecute()
	{
	}


	public function executeSso($sso_token)
	{
		$ACCESS_KEY		= 'v5826jkhnAUIGjhgv89612BiohJKuigb1578jJKgma89671283AQILHKJGmnah231a';
		// Do a Context call
		$url			= "http://sso.ammscore.com/Signon/Context?key={$ACCESS_KEY}&access_key={$sso_token}";

		$response		= $this->curlGet($url);
		$context		= json_decode($response, true);

		if (($context['status'] == 'success') && !empty($context['data']['sf_user_id'])) {

			// If not already authenticated
			if (!$this->AccessControl->isAuthenticated) {

				$Data			= $context['data'];
				$username		= $Data['sf_user_name'];
				$user_id		= $Data['sf_user_id'];
				$ExtraData		= $Data['extra_data'];
				$uri			= $ExtraData['uri'];
				$client_id		= $ExtraData['customer_id'];
				$customer_id	= $ExtraData['mailer_id'];

				if ( $user_id > 0 ) {
					header("P3P: policyref=\"/w3c/p3p.xml\", CP=\"NON CURa ADMa DEVa TAIa CONa OUR DELa BUS IND UNI PUR COM NAV DEM STA\"");
					include_once 'plugins/sfGuardPlugin/lib/model/om/BasesfGuardUserPeer.php';

					$asfGuardUser = sfGuardUserPeer::retrieveByPK($user_id);
					$this->getContext()->getUser()->signIn($asfGuardUser);

					// Mark key used
					$url			= "http://sso.ammscore.com/Signon/MarkKeyUsed?key={$ACCESS_KEY}&access_key={$sso_token}";

					$response		= $this->curlGet($url);

					$this->redirect($uri); exit;
				} else {
					if ($this->getContext()->getUser()->isAuthenticated()) {
						$this->getContext()->getUser()->setAuthenticated(false);
					}

					exit;
				}

			} else {
				$Data			= $context['data'];
				$ExtraData		= $Data['extra_data'];
				$uri			= $ExtraData['uri'];

				$this->redirect($uri); exit;
			}

		} else {
			exit;
		}
	}

	/**
	* Error 404 - Page Not Found
	*********************************************************************************/
	public function executeError404()
	{
		$this->getResponse()->setTitle(WEBSITE_TITLE . " - Page Not Found");
		return "_Success";
	}


	/**
	* No Access
	***********************************************************************************/
	public function executeNoAccess()
	{
		$this->getResponse()->setTitle( WEBSITE_TITLE .' | Access Restricted' );
		return "_Success"; exit;
	}

	/**
	* Index
	*********************************************************************************/
	public function executeIndex()
	{
		switch($this->Page) {
			case 'PostContact':					return $this->executePostContact();
			case 'Customers':					return $this->executeCustomers();
			case 'PaymentProfile':				return $this->executePaymentProfile();
			case 'Products':					return $this->executeProducts();
			case 'ProductGroup':				return $this->executeProductGroup();
			case 'SearchResults':				return $this->executeSearchResults();
			case 'ViewProduct':					return $this->executeViewProduct();
			case 'ViewCampaign':				return $this->executeViewCampaign();
			case 'NameCampaign':				return $this->executeNameCampaign();
			case 'StartCampaign':				return $this->executeStartCampaign();
			case 'CustomizeOrder':				return $this->executeCustomizeOrder();
			case 'MyCart':						return $this->executeMyCart();
			case 'MyWorkspace':					return $this->executeMyWorkspace();
			case 'MyProfile':					return $this->executeMyProfile();
			case 'ChangePassword':				return $this->executeChangePassword();
			case 'PasswordChanged':				return $this->executePasswordChanged();
			case 'OrderHistory':				return $this->executeOrderHistory();
			case 'OrderSummary':				return $this->executeOrderSummary();
			case 'Reorder':						return $this->executeReorder();
			case 'Cancel':						return $this->executeCancel();
			case 'Gallery':						return $this->executeGallery();
			case 'Checkout':					return $this->executeCheckout();
			case 'CheckoutRight':				return $this->executeCheckoutRight();
			// case 'ProcessList':					return $this->executeProcessList();
			case 'OrderReview':					return $this->executeOrderReview();
			case 'Compliance':					return $this->executeCompliance();
			case 'SelectMailingList':			return $this->executeSelectMailingList();
			case 'ReloadOrderProductList':		return $this->executeReloadOrderProductList();
			case 'UploadCsvList':				return $this->executeUploadCsvList();
			case 'UploadFile':					return $this->executeUploadFile();
			case 'RemoveOrderProductList':		return $this->executeRemoveOrderProductList();
			case 'CasOrderSelection':			return $this->executeCasOrderSelection();
			case 'SaveCasListOrder':			return $this->executeSaveCasListOrder();
			case 'Register':					return $this->executeRegister();
			case 'RecipientListMap':			return $this->executeRecipientListMap();
			case 'SaveOrderProductOrderInfo':	return $this->executeSaveOrderProductOrderInfo();
			case 'SampleCSV':					return $this->executeSampleCSV();
			case 'ProductImage':				return $this->executeProductImage();
			case 'MarketEval':					return $this->executeMarketEval();
			case 'ContactUs':					return $this->executeContactUs();
			case 'Reports':						return $this->executeReports();
			case 'ExtraParamsXml':				return $this->executeExtraParamsXml();
			case 'GetUploadStatus':				return $this->executeGetUploadStatus();
			case 'CreatePull':					return $this->executeCreatePull();
			case 'GetPullInfo':					return $this->executeGetPullInfo();

			/*``
			` Start of customer and product manager
			````````````````````````````````````````````````````````````````````````````````*/
			case 'ProgramManager':				return $this->executeProgramManager();
			case 'CategoryManager':				return $this->executeCategoryManager();
			case 'CategoryInfo':				return $this->executeCategoryInfo();
			case 'UpdateCategoryInfo':			return $this->executeUpdateCategoryInfo();
			case 'CouponManager':				return $this->executeCouponManager();
			case 'CouponDetail':				return $this->executeCouponDetail();
			case 'AddCoupon':					return $this->executeAddCoupon();
			case 'EditCoupon':					return $this->executeEditCoupon();
			case 'DeleteCoupon':				return $this->executeDeleteCoupon();
			case 'ProductManager':				return $this->executeProductManager();
			case 'ProgramDetail':				return $this->executeProgramDetail();
			case 'ProductDetail':				return $this->executeProductDetail();
			case 'ProductCategory':				return $this->executeProductCategory();
			case 'SaveAdditionalOrderInfo':		return $this->executeSaveAdditionalOrderInfo();
			case 'SaveOrderNotification':		return $this->executeSaveOrderNotification();
			case 'SaveProductCategory':			return $this->executeSaveProductCategory();
			case 'SaveOtherSetting':			return $this->executeSaveOtherSetting();
			case 'SaveProductInfo':				return $this->executeSaveProductInfo();
			case 'SaveProductAddonCallScript':	return $this->executeSaveProductAddonCallScript();
			case 'SaveProductAddonEmail':		return $this->executeSaveProductAddonEmail();
			case 'SaveGroupPermission':			return $this->executeSaveGroupPermission();
			case 'SaveProductMailingOption':	return $this->executeSaveProductMailingOption();
			case 'AddCustomer':					return $this->executeAddCustomer();
			case 'AddProgram':					return $this->executeAddProgram();
			case 'EditProgram':					return $this->executeEditProgram();
			case 'AddProduct':					return $this->executeAddProduct();
			case 'AddCategory':					return $this->executeAddCategory();
			case 'AddNewGroup':					return $this->executeAddNewGroup();
			case 'SalesReport':					return $this->executeSalesReport();
			case 'GroupManager':				return $this->executeGroupManager();
			case 'EditUserGroup':				return $this->executeEditUserGroup();
			case 'EditGroup':					return $this->executeEditGroup();
			case 'DeleteProduct':				return $this->executeDeleteProduct();
			case 'AddPricing':					return $this->executeAddPricing();
			case 'RemoveRateCard':				return $this->executeRemoveRateCard();
			case 'PricingDetail':				return $this->executePricingDetail();
			case 'DeleteCategory':				return $this->executeDeleteCategory();
			case 'UploadManager':				return $this->executeUploadManager();
			case 'ViewCompleteOrderDetail':		return $this->executeViewCompleteOrderDetail();
			case 'DownloadRecipientList':		return $this->executeDownloadRecipientList();
			case 'EmailManager':				return $this->executeEmailManager();
			case 'OrderManager':				return $this->executeOrderManager();
			case 'GetOrderProductNotes':		return $this->executeGetOrderProductNotes();
			case 'GetAutoCampaignAgreement':	return $this->executeGetAutoCampaignAgreement();
			case 'AddOrderProductNote':			return $this->executeAddOrderProductNote();
			case 'UploadComplianceFile':		return $this->executeUploadComplianceFile();
			case 'DownloadComplianceFile':		return $this->executeDownloadComplianceFile();
			case 'ListComplianceFiles':			return $this->executeListComplianceFiles();
			case 'DeleteComplianceFile':		return $this->executeDeleteComplianceFile();
			case 'AutoCampaignAgreement':		return $this->executeAutoCampaignAgreement();
			case 'OrderReviewNonMailable':		return $this->executeOrderReviewNonMailable();
			case 'UploadConsumers':				return $this->executeUploadConsumers();
			case 'CustomerMapping':				return $this->executeCustomerMapping();
			case 'MapFields':					return $this->executeMapFields();
			case 'ConsumerUploads':				return $this->executeConsumerUploads();
			case 'DownloadCustomerUploadFile':	return $this->executeDownloadCustomerUploadFile();
			case 'FancyProductDesigner':		return $this->executeFancyProductDesigner();
			/*``
			` Start of text content pages
			````````````````````````````````````````````````````````````````````````````````*/
			case 'AboutUs':						return $this->executeTextContent();
			case 'News':						return $this->executeTextContent();
			case 'Partners':					return $this->executeTextContent();
			case 'Testimonials':				return $this->executeTextContent();
			case 'Affiliate':					return $this->executeTextContent();
			case 'ContactUs':					return $this->executeTextContent();
			case 'Licensing':					return $this->executeTextContent();
			case 'ReturnPolicy':				return $this->executeTextContent();
			case 'PrivacyPolicy':				return $this->executeTextContent();
			case 'TermsOfUse':					return $this->executeTextContent();

			/*``
			` Ajax requests
			````````````````````````````````````````````````````````````````````````````````*/
			case 'Ajax':						return $this->executeAjax();
			case 'SetCategoryStatus':			return $this->executeSetCategoryStatus();

			/*``
			` PDF Proofs
			````````````````````````````````````````````````````````````````````````````````*/
			case 'Proof':						return $this->executeProof();
			case 'ViewProof':					return $this->executeViewProof();
			case 'PDFViewer':					return $this->executePDFViewer();
			case 'PDF':							return $this->executePDF();

			// List Manager
			case "GetCustomers":				return $this->executeGetCustomers();

			case 'Test':						return $this->executeTest();

		}

		$this->ActiveMenu = "Home";
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Home" );
		return '_Success';
	}


	/**
	* Private Function: CheckAuthentication
	*********************************************************************************/
	private function CheckAuthentication( $requiredGroup=array() )
	{
		$isAuthenticated	= $this->AccessControl->isAuthenticated;
		if (!$isAuthenticated) {
			// Save this page link in a session variable
			$url = $this->getRequest()->getUri();
			$_SESSION['referer'] = $url;

			$this->redirect ("/login"); exit;
		}

		/*`
		` If group is required, make sure the user has access to this group
		`````````````````````````````````````````````````````````````````````*/
		if ($requiredGroup) {
			if (!is_array($requiredGroup)) {
				$requiredGroup = array($requiredGroup);
			}
			if ( !array_intersect($requiredGroup, $this->AccessControl->UserGroup) &&
				!in_array('ADMIN', $this->AccessControl->UserGroup) &&
				!in_array(SF_GUARD_GROUP_PREFIX.'ADMIN', $this->AccessControl->UserGroup))
			{ $this->forward('default', 'NoAccess'); exit; }
		}
	}

	/**
	* Private Function: Text Content
	*********************************************************************************/
	private function executeTextContent()
	{
		$this->setTemplate($this->Page);
		return ('_Success'); exit;
	}

	/**
	* Private Function: Proof
	*********************************************************************************/
	private function executeProof()
	{
		$this->setLayout(false);
		$this->setTemplate('Proof');
		return ('_Success'); exit;
	}

	private function executePDF() {
		header("Content-Type: application/pdf");
		return $this->renderText(file_get_contents(Us2OrderProofPeer::GetLastProof($this->OrderProductId)));
	}

	private function executePDFViewer() {
		$this->setLayout(false);
		$this->setTemplate("PDFViewer");
		return "_Success";
	}

	/**
	* Private Function: ViewProof
	*********************************************************************************/
	private function executeViewProof()
	{
		$this->setLayout(false);
		$this->setTemplate('ViewProof');
		$ItemIndex = $this->getRequestParameter('ItemIndex');
		if (!empty($ItemIndex)) {
			$this->ItemIndex = "__{$ItemIndex}";
		} else {
			$this->ItemIndex = '';
		}
		return '_Success'; exit;
	}

	/**
	* Private Function: Ajax
	*********************************************************************************/
	private function executeAjax()
	{
		require_once(SF_ROOT_DIR .'/apps/' . SF_APP . '/lib/store.class.php');

		switch ($this->Action) {

			case 'SaveDialCustomization':
				if ($this->Type=='AllDials') {
					foreach ($_REQUEST as $name => $value) {
						if (strpos($name, 'DIAL__')===0) {
							$name = str_replace('DIAL__', '', $name);
							$arrayDialValues[$name] = $value;
						}
					}

					foreach ($_FILES as $name => $dataValue) {
						if (strpos($name, 'ImageFile_DIAL__')===0) {
							if ($dataValue['size'] > 0) {
								$name = str_replace('ImageFile_DIAL__', '', $name);
								$arrayUploadedFile[$name] = $dataValue;
							}
						}
					}

					$this->arraySaveResult = Store::SaveALLDialCustomization($this->CurrentCustomerId, $this->OrderProductId, $arrayDialValues, $arrayUploadedFile);
					$this->ProductId = Us2OrderProductPeer::GetProductId($this->OrderProductId);
					return $this->executeCustomizeOrder($alertReload=false);
				} else {
					$requestValue = $_REQUEST["DIAL__". $this->DialId];
					return $this->renderText(Store::SaveDialCustomization($this->CurrentCustomerId, $this->OrderProductId, $this->DialId, $requestValue, $ResultFormat='JSON'));
				}
				break;

			case 'SaveItemNote':
				$OrderProductId				= intval($this->getRequestParameter('OrderProductId'));
				$OrderNotes					= $this->getRequestParameter('ItemNote');
				$Us2OrderProduct 			= Us2OrderProductPeer::retrieveByPk($OrderProductId);
				$Us2OrderProduct->setOrderNotes($OrderNotes);
				$result 					= $Us2OrderProduct->save();
				return $this->renderText(json_encode(array("success" => $result)));
				break;

			case 'SearchTemplate':
				$array 			= array();
				if (!empty($this->Search)) {
					$SearchTerm		= mysql_real_escape_string($this->Search);
					$Connection 	= Propel::getConnection();
					$Query 			= "SELECT product_id FROM us2_product WHERE store_id = ".STORE_ID." AND status_id = 2 AND active_yn = 'Y' AND ((name LIKE '%{$SearchTerm}%') OR (description LIKE '%{$SearchTerm}%'))";
					$Rs 			= $Connection->executeQuery($Query);

					while ($Rs->next()) {
						$array[] 		= $Rs->get('product_id');
					}
				}

				return $this->renderText(json_encode(array('ids' => implode(',', $array), 'count' => count($array))));
				break;

			case "SignUpOffers":
				$email = strtoupper($this->Email);
				$response = array();
				if (preg_match("/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/", $email)) {
					// TODO: Store this in the database. Question: Where?

					$response['email'] = $email;
				} else {
					$response['error'] = "Please enter a valid email address.";
				}

				return $this->renderText(json_encode($response));
				break;

			case "CheckUsername":
				$username = $this->getRequestParameter("Username");
				$SfGuardUser = new sfGuardUserPeer();
				if ($SfGuardUser->isUsernameAvailable($username)) {
					$response['success']	= "true";
				} else {
					$response['success']	= "false";
					$response['error']		= "This email is already in use. Please enter a different email address, or click Cancel and log in with your existing username and password.";
				}

				return $this->renderText(json_encode($response));
				break;

			case "CheckCoupon":
				$CouponCode = $this->getRequestParameter("CouponCode");
				$today = date('Y-m-d');
				$C = new Criteria();
				$C->add(Us2CouponPeer::COUPON_CODE, strtoupper($CouponCode));
				$C->add(Us2CouponPeer::CLIENT_ID, CLIENT_ID);
				$C->add(Us2CouponPeer::START_DATE, $today, Criteria::LESS_EQUAL);
				$C->add(Us2CouponPeer::END_DATE, $today, Criteria::GREATER_EQUAL);
				$C->addDescendingOrderByColumn(Us2CouponPeer::US2_COUPON_ID);
				$Us2Coupon = Us2CouponPeer::doSelectOne($C);
				if (empty($Us2Coupon)) {
					$response['success']	= "true";
				} else {
					$response['success']	= "false";
					$response['error']		= "This coupon code already exists. Click <a href=\"/?token=".Convert::EncodeURL("Page=EditCoupon&CouponId=".$Us2Coupon->getUs2CouponId())."\">here</a> to edit it or enter a different code.";
				}

				return $this->renderText(json_encode($response));
				break;

			case "GetProductsInGroup":
				$arrayProductGroupId = $this->getRequestParameter("ProductGroupId");
				// If no product groups are selected
				if (empty($arrayProductGroupId)) {
					// Collect all products
					$pids = array();
					$productRS = Us2ProductPeer::GetProductByStore(STORE_ID, 2);
					while ($productRS->next()) {
						$pids[] = $productRS->get(1);
					}

					$this->products = Us2ProductPeer::retrieveByPKs($pids);
				} else {
					// Retrieve all products belonging to these product groups
					$arrayProductId = Us2ProductGroupMembershipPeer::GetProducts($arrayProductGroupId);

					$this->products = Us2ProductPeer::retrieveByPKs($arrayProductId);
					$results = array();
					foreach ($this->products as $product) {
						if ($product->getStatusId() == 2) {
							$results[] = $product;
						}
					}
					$this->products = $results;
				}
				$this->setLayout(false);
				$this->setTemplate("GetProductsInGroup");
				return "_Success";
				break;

			case "SetOrderNotes":
				// We are creating a new order product with the selected name
				// Get the current open order
				$OrderId = Us2OrderPeer::GetLastIncompleteOrder ($this->CurrentCustomerId, STORE_ID, $this->CurrentUserId);

				// Load the product
				$Us2Product = Us2ProductPeer::retrieveByPk($this->ProductId);
				$OrderNotes = $this->getRequestParameter('OrderNotes');

				$Us2OrderProduct = new Us2OrderProduct();
				$Us2OrderProduct->setOrderId ($OrderId);
				$Us2OrderProduct->setProductId ($this->ProductId);
				$Us2OrderProduct->setCreatedByUserId($this->CurrentUserId);
				$Us2OrderProduct->setCreatedDate(date('Y-m-d H:i:s'));
				$Us2OrderProduct->setCustomerId ($this->CurrentCustomerId);
				$Us2OrderProduct->setOrderNotes($OrderNotes);
				$result = $Us2OrderProduct->save();

				$response = array();
				if ($result) {
					$response['success']			= "true";
					$response['order_notes']		= $Us2OrderProduct->getOrderNotes();
					$response['order_product_id']	= $Us2OrderProduct->getOrderProductId();
				} else {
					$response['success']		= "false";
					$response['error']			= "Failed to name campaign.";
				}

				return $this->renderText(json_encode($response));
				break;

			case "GetSampleData":
				// See if there is a specific Automagic setting for this customer
				$result = Us2AutomagicPeer::LoadByCustomerProduct ($this->CurrentCustomerId, $this->ProductId);
				// If we did not find a customer specific one
				if (!is_object($result)) {
					// Try the default
					$result = Us2AutomagicPeer::LoadByCustomerProduct (0, $this->ProductId);
				}

				if (is_object($result)) {
					$data = unserialize($result->getSerializedData());
				} else {
					$data = array();
				}

				$csv = array();
				$csv[] = array('FIELD','KEYWORD','VALUE');
				foreach ($data["PARAGRAPH"] as $datum) {
					$field 			= $datum['field'];
					$keyword 		= $datum['search_keyword'];
					$default 		= '';
					$csv[]			= array($field, $keyword, $default);
				}
				header("Content-type: text/x-csv");
				header("Content-Disposition: attachment; filename=\"{$this->ProductId}_data.csv\"");
				header("Pragma: no-cache");
				header("Expires: 0");
				foreach ($csv as $line) {
					echo "\"" . implode('","', $line) . "\"\n";
				}
				exit;
				break;

			case 'UploadFile':
				$File = $_FILES['File'];
				$pathinfo = pathinfo($File['name']);
				$extension = $pathinfo['extension'];

				$targetPath = SF_ROOT_DIR . '/web/files/';
				$targetPath .= time() . '_' . md5($File['name']) . ".$extension";

				if (move_uploaded_file($File['tmp_name'], $targetPath)) {

					$Us2Upload = new Us2Upload();
					$Us2Upload->setCustomerId(UPLOAD_CUSTOMER_ID);
					$Us2Upload->setFullpath($targetPath);
					$Us2Upload->setFilename($File['name']);
					$Us2Upload->setFiletype($File['type']);
					$Us2Upload->setFilesize($File['size']);
					$Us2Upload->setCreatedDate(date('Y-m-d H:i:s'));
					$Us2Upload->setCreatedByUserId($this->CurrentUserId);
					$Us2Upload->setActiveYn('Y');
					$Us2Upload->save();

					header("Location: " . $_SERVER['HTTP_REFERER']);
					exit;

				} else {
					$ErrorMessage = "There was an error uploading the file, please try again.";
				}
				break;

			case 'SelectMailingList2':
				$this->OrderProductId 	= $this->getRequestParameter('OrderProductId');

				$this->setLayout(false);
				$this->setTemplate('SelectMailingList2');
				return '_Success';
				break;

			case 'SwitchCampaignStatus':
				$CampaignId = $this->getRequestParameter('CampaignId');
				$StatusId = $this->getRequestParameter('StatusId');
				$Us2Campaign = Us2CampaignPeer::retrieveByPk($CampaignId);
				$Us2Campaign->setStatusId($StatusId);
				$Us2Campaign->setUpdatedByUserid($this->CurrentUserId);
				$Us2Campaign->setUpdatedDate(date('Y-m-d H:i:s'));
				$result = $Us2Campaign->save();
				if ($result) {
					return $this->renderText(json_encode("1"));
				} else {
					return $this->renderText(json_encode("0"));
				}
				break;

			case 'DeleteCampaign':
				$Us2Campaign = Us2CampaignPeer::retrieveByPk($this->CampaignId);
				$Us2Campaign->setActiveYn('N');
				$Us2Campaign->setUpdatedByUserid($this->CurrentUserId);
				$Us2Campaign->setUpdatedDate(date('Y-m-d H:i:s'));
				$result = $Us2Campaign->save();
				if ($result) {
					return $this->renderText(json_encode("1"));
				} else {
					return $this->renderText(json_encode("0"));
				}
				break;

			case 'SetProxyClientId':
				$ProxyClientId = $this->getRequestParameter('ProxyClientId');
				$this->getUser()->setAttribute('ProxyClientId', $ProxyClientId);
				unset($ProxyClientId);

				$ProxyClientId = $this->getUser()->getAttribute('ProxyClientId');
				$this->CurrentClientId = (!empty($ProxyClientId)) ? $ProxyClientId : CLIENT_ID;
				$result = array('CurrentClientId' => $this->CurrentClientId);
				return $this->renderText(json_encode($result));
				break;

			case 'SetProxyCustomerId':
				$ProxyCustomerId = $this->getRequestParameter('ProxyCustomerId');
				$this->getUser()->setAttribute('ProxyCustomerId', $ProxyCustomerId);
				unset($ProxyCustomerId);

				$ProxyCustomerId = $this->getUser()->getAttribute('ProxyCustomerId');
				$this->CurrentCustomerId = (!empty($ProxyCustomerId)) ? $ProxyCustomerId : $this->AccessControl->CustomerId;

				// Get all users for this customer
				$arrayUser = SfGuardUserProfilePeer::GetUsersByCustomer($this->CurrentCustomerId);

				// Always force them to change the proxy user id
				$this->getUser()->setAttribute('ProxyUserId', 0);
				$this->CurrentUserId = 0;

				$users = array();

				foreach ($arrayUser as $user) {
					$id = $user->getUserId();
					$name = trim($user->getFirstName() . ' ' . $user->getLastName());
					if (empty($name)) {
						$name = $user->getEmailAddress();
					}
					$users[] = array('id' => $id, 'name' => $name);
				}

				$result = array('users' => $users, 'id' => $this->CurrentUserId);
				return $this->renderText(json_encode($result));
				break;

			case 'SetProxyUserId':
				$ProxyUserId = $this->getRequestParameter('ProxyUserId');
				$OrderProductId = $this->getRequestParameter('OrderProductId', 0);

				$this->getUser()->setAttribute('ProxyUserId', $ProxyUserId);
				unset($ProxyUserId);

				$ProxyUserId = $this->getUser()->getAttribute('ProxyUserId');
				$this->CurrentUserId = (!empty($ProxyUserId)) ? $ProxyUserId : $this->AccessControl->UserId;

				// If we received an order product id
				if (!empty($OrderProductId)) {
					// Change it to the current customer and user id
					$OrderProduct	= Us2OrderProductPeer::retrieveByPk($OrderProductId);
					// Get the latest incomplete order for the new customer and user id
					$OrderId		= Us2OrderPeer::GetLastIncompleteOrder ($this->CurrentCustomerId, STORE_ID, $this->CurrentUserId);

					$OrderProduct->setCustomerId($this->CurrentCustomerId);
					$OrderProduct->setCreatedByUserId($this->CurrentUserId);
					$OrderProduct->setOrderId($OrderId);

					$OrderProduct->save();

					// Get any child order products (mailing list orders) for this order product as well
					$C1 = new Criteria();
					$C1->addAnd(Us2OrderProductPeer::PARENT_US2_ORDER_PRODUCT_ID, $OrderProductId);
					$C1->addAnd(Us2OrderProductPeer::ORDER_HANDLING_STATUS_ID, 9, Criteria::LESS_THAN);
					$arrayListOrderProduct = Us2OrderProductPeer::doSelect($C1);

					foreach ($arrayListOrderProduct as $ListOrderProduct) {
						// Change the customer, user, and order ids for this item.
						$ListOrderProduct->setCustomerId($this->CurrentCustomerId);
						$ListOrderProduct->setCreatedByUserId($this->CurrentUserId);
						$ListOrderProduct->setOrderId($OrderId);

						$ListOrderProduct->save();
					}

				}

				$result = array('ProxyUserId' => $this->CurrentUserId);
				return $this->renderText(json_encode($result));
				break;
			case 'SetOrderCustomerUser':
				$OrderProductId		= $this->getRequestParameter('OrderProductId', 0);
				$NewCustomerId		= $this->getRequestParameter('NewCustomerId', 0);
				$NewUserId			= $this->getRequestParameter('NewUserId', 0);

				// If we received an order product id
				if (!empty($OrderProductId)) {
					// Change it to the current customer and user id
					$OrderProduct	= Us2OrderProductPeer::retrieveByPk($OrderProductId);
					// If no userid provided
					if (empty($NewUserId)) {
						// Use the existing user id
						$NewUserId		= $OrderProduct->getCreatedByUserId();
					}
					// Get the latest incomplete order for the new customer and user id
					$OrderId		= Us2OrderPeer::GetLastIncompleteOrder ($NewCustomerId, STORE_ID, $NewUserId);

					$OrderProduct->setCustomerId($NewCustomerId);
					$OrderProduct->setCreatedByUserId($NewUserId);
					$OrderProduct->setOrderId($OrderId);

					$OrderProduct->save();

					// Get any child order products (mailing list orders) for this order product as well
					$C1 = new Criteria();
					$C1->addAnd(Us2OrderProductPeer::PARENT_US2_ORDER_PRODUCT_ID, $OrderProductId);
					$C1->addAnd(Us2OrderProductPeer::ORDER_HANDLING_STATUS_ID, 9, Criteria::LESS_THAN);
					$arrayListOrderProduct = Us2OrderProductPeer::doSelect($C1);

					foreach ($arrayListOrderProduct as $ListOrderProduct) {
						// Change the customer, user, and order ids for this item.
						$ListOrderProduct->setCustomerId($NewCustomerId);
						$ListOrderProduct->setCreatedByUserId($NewUserId);
						$ListOrderProduct->setOrderId($OrderId);

						$ListOrderProduct->save();
					}

				}

				$result = array('OrderProductId' => $OrderProductId, 'NewCustomerId' => $NewCustomerId, 'NewUserId' => $NewUserId);
				return $this->renderText(json_encode($result));
				break;
			case 'ExecuteEvalOrder':

				$customerId			= $this->getRequestParameter('customerId');
				$orderSelection		= $this->getRequestParameter('orderSelection');
				$evalRequestId		= $this->getRequestParameter('evalRequestId');
				$exportList			= $this->getRequestParameter('exportList');
				$exportListName		= $this->getRequestParameter('exportListName');
				$exportType			= $this->getRequestParameter('exportType');
				$exportAsCsv		= $this->getRequestParameter('exportAsCsv');
				$exportFIData		= $this->getRequestParameter('exportFIData');
				$exportInDmsFormat	= $this->getRequestParameter('exportInDmsFormat');
				$userId				= $this->CurrentUserId;

				$exportVehicleLastDate		= $_REQUEST['exportVehicleLastDate'];
				$updateOrderProduct			= $_REQUEST['updateOpId'];
				$arrayDmsOrderNames			= array();
				$arrayConquestNames			= array();
				$arrayOptions 				= array();

				if(!$customerId) 	die("No customer was selected, please try again.");
				if(!$evalRequestId) die("Invalid request.");



				require_once(SF_ROOT_DIR."/classes/class.market_eval_exporter.php");

				$marketEvalExporter = new MarketEvalExporter($customerId, $userId, $evalRequestId);
				$marketEvalExporter->orderSelection = $orderSelection;

				if($exportList==false) {
					$html = $marketEvalExporter->getExportCount();
					return $this->renderText($html);
				}
				else {

					if($exportFIData || $exportInDmsFormat) {
						$arrayOptions['export_fi_data'] 			= true;
						$arrayOptions['export_prev_3yrs_srv_total'] = true;
						$arrayOptions['export_ext_warranty_data'] 	= true;
					}

					if($exportInDmsFormat) {
						$arrayOptions['export_in_dms_format'] 		= true;
					}

					if($exportVehicleLastDate) {
						$arrayOptions['export_last_ro_sales_date'] 	= true;
					}

					if ($exportAsCsv)
					{
						/*``
						`` Export as downloadable CSV
						``````````````````````````````````````````````````````````````````````````````*/
						$data = $marketEvalExporter->processExport($evalExportId, $exportAsCsv=true, $arrayOptions);
						header("Content-type: application/csv");
						header("Content-Disposition: attachment; filename=eval_export_".date('Y_m_d_').mt_rand(9,999999999).".csv");
						header("Pragma: no-cache");
						header("Expires: 0");
						return $this->renderText($data);
					}
					else
					{
						/*``
						`` Export as rapid mail upload
						``````````````````````````````````````````````````````````````````````````````*/
						$marketEvalExporter->updateOrderProductId 	= $updateOrderProduct;
						$marketEvalExporter->exportListName 		= $exportListName;
						$isSuccess = $marketEvalExporter->createEvalExport($exportType, $arrayOptions);
						return $this->renderText("OK");

					}

				}
				break;
			case "EvalGetCount":
				$this->setTemplate("EvalGetCount");
				return "_Success";
				break;

			case "ActivateCustomer":
				$UserId					= $this->getRequestParameter('UserId');
				$StatusId				= $this->getRequest('StatusId');
				$success				= false;
				if ($UserId) {
					if ($User = SfGuardUserPeer::retrieveByPk($UserId)) {
						$User->setIsActive($StatusId);
						$User->save();
						$success = true;
					}
				}
				$result = array("success" => $success);
				return $this->renderText(json_encode($result));
				break;

			case "GetCampaignData":
				$isAuthenticated	= $this->AccessControl->isAuthenticated;
				$hasAccess			= $this->AccessControl->hasGroup( array('ADMIN', 'STORE ADMIN', SF_GUARD_GROUP_PREFIX.'ADMIN', SF_GUARD_GROUP_PREFIX.'CORP', SF_GUARD_GROUP_PREFIX.'DIST' ));
				if (!$isAuthenticated || !$hasAccess) {
					return $this->renderText("");
				}

				$this->GetDataTableParameters();

				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {
					$Connection = Propel::getConnection();


					$Query		= "SELECT us2_campaign.campaign_id, us2_campaign.name, "
								. "CONCAT(user_profile1.first_name, ' ', user_profile1.last_name) AS created_by, "
								. "DATE_FORMAT(us2_campaign.created_date, '%m/%d/%Y') AS created_date, "
								. "CONCAT(user_profile2.first_name, ' ', user_profile2.last_name) AS updated_by, "
								. "DATE_FORMAT(us2_campaign.updated_date, '%m/%d/%Y') AS updated_date, "
								. "status_id, '' AS `edit`, '' AS `delete` "
								. "FROM us2_campaign "
								. "LEFT JOIN sf_guard_user_profile AS user_profile1 ON us2_campaign.created_by_user_id = user_profile1.user_id "
								. "LEFT JOIN sf_guard_user_profile AS user_profile2 ON us2_campaign.updated_by_user_id = user_profile2.user_id "
								. "WHERE store_id = '" . STORE_ID . "' "
								. "AND client_id = '" . CLIENT_ID . "' "
								. "AND active_yn = 'Y'";

					// Don't use the searchClause from GetDataTableParameters,
					// create our own to maintain consistency with the original page
					$search						= $this->getRequestParameter('search[value]');
					$this->searchClause			= '';
					if ($search) {
						$arraySearch			= array();
						$arrayFilter			= explode(' ', $search);

						foreach ($arrayFilter as $filter) {
							$arraySearch[]			= "name LIKE '%{$filter}%'";
						}

						if (!empty($arraySearch)) {
							$this->searchClause		= ' AND ( (' . implode(') OR (', $arraySearch) . ') )';
						}
					}

					// Get RecordsTotal
					$QueryTotal = "SELECT COUNT(*) AS count FROM ( {$Query} ) A";

					$debug[]	= $QueryTotal;
					$Rs = $Connection->executeQuery($QueryTotal);

					while ($Rs->next()) {
						$RecordsTotal = $Rs->get('count');
					}

					// Get RecordsFiltered
					if (!empty($this->searchClause)) {
						$QueryFiltered = "SELECT COUNT(*) AS count FROM (SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause} ) AS b";

						$debug[]	= $QueryFiltered;
						$Rs = $Connection->executeQuery($QueryFiltered);

						while ($Rs->next()) {
							$RecordsFiltered = $Rs->get('count');
						}
					} else {
						$RecordsFiltered = $RecordsTotal;
					}

					// Get Data
					$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";

					$debug[]	= $QueryData;
					$result		= $Connection->executeQuery($QueryData);

					$arrayProgram = array();
					while ( $result->next() ) {
						$row				= $result->getRow();

						if ($row['status_id'] == 1) {
							$statusText = "<div><i>Offline</i> (<a class=\"changeStatus\" href=\"#\" data-campaign-id=\"{$row['campaign_id']}\" data-status-id=\"2\" data-url=\"/?token=" . Convert::EncodeURL("Page=Ajax&Action=SwitchCampaignStatus") . "\">Place online</a>)</div>";
						} else {
							$statusText = "<div><b>Online</b> (<a class=\"changeStatus\" href=\"#\" data-campaign-id=\"{$row['campaign_id']}\" data-status-id=\"1\" data-url=\"/?token=" . Convert::EncodeURL("Page=Ajax&Action=SwitchCampaignStatus") . "\">Take offline</a>)</div>";
						}

						$editCampaignUrl		= Convert::EncodeURL("Page=EditProgram&CampaignId={$row['campaign_id']}");
						$deleteCampaignUrl		= Convert::EncodeURL("Page=Ajax&Action=DeleteCampaign&CampaignId={$row['campaign_id']}");
						$row['status_id']		= $statusText;
						$row['edit']			= "<a class=\"active-button\" href=\"/?token={$editCampaignUrl}\">edit</a>";
						$row['delete']			= "<a class=\"active-button\" href=\"#\" class=\"deleteCampaign\" data-url=\"/?token={$deleteCampaignUrl}\" data-name=\"".addslashes($row['name'])."\">delete</a>";

						$data[]				= array_values($row);
					}

					// print_r($data);exit;

				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetCustomerData":
				$isAuthenticated	= $this->AccessControl->isAuthenticated;
				$hasAccess			= $this->AccessControl->hasGroup( array('ADMIN', 'STORE ADMIN', SF_GUARD_GROUP_PREFIX.'ADMIN', SF_GUARD_GROUP_PREFIX.'CORP', SF_GUARD_GROUP_PREFIX.'DIST' ));
				if (!$isAuthenticated || !$hasAccess) {
					return $this->renderText("");
				}

				$this->GetDataTableParameters();

				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {
					$Connection = Propel::getConnection();

					/*`
					` Get list of customers for this client
					``````````````````````````````````````````````````````````*/
					// $arrayCustomer = CustomerPeer::getCustomers(CLIENT_ID, $this->searchClause);

					$Query	= "SELECT customer_id, name, city, state, external_id "
							. "FROM customer "
							. "WHERE client_id = " . CLIENT_ID . " "
							. "AND active_yn = 'Y'";

					// Don't use the searchClause from GetDataTableParameters,
					// create our own to maintain consistency with the original page
					$search						= $this->getRequestParameter('search[value]');
					$this->searchClause			= '';
					if ($search) {
						$arraySearch			= array();
						$arrayFilter			= explode(' ', $search);

						foreach ($arrayFilter as $filter) {
							$arraySearch[]			= "name LIKE '%{$filter}%'";
						}

						if (!empty($arraySearch)) {
							$this->searchClause		= ' AND ( (' . implode(') OR (', $arraySearch) . ') )';
						}
					}

					// Get RecordsTotal
					$QueryTotal = "SELECT COUNT(*) AS count FROM ( {$Query} ) A";

					$debug[]	= $QueryTotal;
					$Rs = $Connection->executeQuery($QueryTotal);

					while ($Rs->next()) {
						$RecordsTotal = $Rs->get('count');
					}

					// Get RecordsFiltered
					if (!empty($this->searchClause)) {
						$QueryFiltered = "SELECT COUNT(*) AS count FROM (SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause} ) AS b";

						$debug[]	= $QueryFiltered;
						$Rs = $Connection->executeQuery($QueryFiltered);

						while ($Rs->next()) {
							$RecordsFiltered = $Rs->get('count');
						}
					} else {
						$RecordsFiltered = $RecordsTotal;
					}

					// Get Data
					$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";

					$debug[]	= $QueryData;
					$result		= $Connection->executeQuery($QueryData);

					$arrayCustomer = array();
					while ( $result->next() ) {
						$customer_id		= $result->get('customer_id');
						$dealerName			= ucwords(strtolower($result->get('name')));
						$city				= $result->get('city');
						$state				= $result->get('state');
						$externalId			= $result->get('external_id');

						if ($externalId) {
							$externalId = "{$externalId} - ";
						}

						$arrayCustomer[$customer_id] = "{$dealerName} - ({$externalId}{$city}, {$state})";
					}

					foreach ($arrayCustomer as $CustomerId => $CustomerName) {
						$LastTransactionDate = Us2OrderPeer::GetLastTransactionDateByCustomers($CustomerId);
						if ($LastTransactionDate) {
							$LastTransactionDate = date("m/d/Y", strtotime($LastTransactionDate));
						}

						$UserId			= 0;
						$LastLogin		= '';
						$Password		= '';
						$Username		= '';
						$IsActive		= 0;

						$C = new Criteria();
						$C->addSelectColumn(SfGuardUserProfilePeer::USER_ID);
						$C->add(SfGuardUserProfilePeer::CUSTOMER_ID, $CustomerId);
						$Rs = SfGuardUserProfilePeer::doSelectRs($C);

						while ($Rs->next()) {
							$UserId = $Rs->get(1);
						}

						$User = sfGuardUserPeer::retrieveByPk($UserId);

						if ($User) {
							$LastLogin = $User->getLastLogin();
							$IsActive = $User->getIsActive();
							$UserGroups = $User->getGroupNames();
							$Usersss = $User->getGroups();

							if ($FilterGroup) {
								if (!$User->hasGroup($FilterGroup)) {
									continue;
								}
							}

							if ($LastLogin) {
								$LastLogin = date('m/d/Y', strtotime($LastLogin));
							}

							// Get user password
							$Connection = Propel::getConnection();
							$Query = "SELECT username, real_password FROM sf_guard_user WHERE id='$UserId' ";

							$Statement = $Connection->prepareStatement($Query);
							$Resultset = $Statement->executeQuery();

							while ($Resultset->next()) {
								$Username = $Resultset->get('username');
								$Password = $Resultset->get('real_password');
							}

							// if user has any admin group then don't show their password
							foreach ($UserGroups as $groupName) {
								$groupName = strtoupper($groupName);
								if (strpos($groupName, 'ADMIN') !== false) {
									$Password = '**********';
								}
							}
						}

						if ($IsActive) {
							$ActiveImage = "<img class=\"imageActivateCustomer\" data-user-id=\"$UserId\" data-status=\"1\" data-title=\"$CustomerName\" rel=\"$UserId\" style=\"cursor:pointer\" src=\"{$protocol}{$domainName}images/common/activeicon.gif\">";
						} else {
							$ActiveImage = "<img class=\"imageActivateCustomer\" data-user-id=\"$UserId\" data-status=\"0\" data-title=\"$CustomerName\" rel=\"$UserId\" style=\"cursor:pointer\" src=\"{$protocol}{$domainName}images/common/inactiveicon.gif\">";
						}

						$PaymentProfileUrl	= "/?token=" . Convert::EncodeURL('Page=PaymentProfile&CustomerId='.$CustomerId);
						$UploadUrl			= "/?token=" . Convert::EncodeURL('Page=UploadConsumers')."&ci={$CustomerId}";

						$row = array(
							'active'			=> "{$ActiveImage}<div id=\"popupActivateUser{$UserId}\"></div>",
							'customer_id'		=> $CustomerId,
							'name'				=> $CustomerName,
							'last_order_date'	=> $LastTransactionDate,
							'last_login'		=> $LastLogin,
							'groups'			=> "<a class=\"active-button\" href=\"#\" onclick=\"return displayEditUserGroup({$UserId})\">Edit</a>",
							'pmt_profile'		=> "<a class=\"active-button\" href=\"{$PaymentProfileUrl}\">Edit</a>",
							'username'			=> $Username,
							'password'			=> $Password,
							'upload'			=> "<a class=\"active-button\" href=\"{$UploadUrl}\">Upload Consumers</a>"
						);
						$data[] = array_values($row);
					}


				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetDraftData":
				$this->GetDataTableParameters();

				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {
					$Connection = Propel::getConnection();

					$Query	= "SET SESSION group_concat_max_len = 10000000";
					$Connection->executeQuery($Query);

					$Query	= "SELECT GROUP_CONCAT(customer_id SEPARATOR ',') AS customer_id_list FROM customer WHERE client_id = {$this->CurrentClientId}";

					$Rs = $Connection->executeQuery($Query);

					while ($Rs->next()) {
						$CustomerIdList = $Rs->get('customer_id_list');
					}

					$Query	= "SELECT "
							. "us2_order_product.order_product_id, "

							. "us2_image.preview_url AS image, "

							. "CONCAT( "
							. "us2_product.name,'|', "
							. "us2_order_product.order_notes, '|', "
							. "customer.name, '|', "
							. "CONCAT(sf_guard_user_profile.first_name, ' ', sf_guard_user_profile.last_name), '|', "
							. "us2_order_product.product_id, '|', "
							. "0 "
							. ") AS description, "
							. "'' AS cancel, "
							. "'' AS complete "
							. "FROM us2_order_product "
							. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
							. "LEFT JOIN us2_product ON us2_order_product.product_id = us2_product.product_id "
							. "LEFT JOIN us2_image ON us2_product.small_image_id = us2_image.us2_image_id "
							. "LEFT JOIN customer ON us2_order_product.customer_id = customer.customer_id "
							. "LEFT JOIN sf_guard_user_profile ON us2_order_product.created_by_user_id = sf_guard_user_profile.user_id "
							. "WHERE us2_order_product.customer_id IN ({$CustomerIdList}) "
							. "AND us2_order_product.parent_us2_order_product_id = 0 "
							. "AND us2_order_product.order_handling_status_id < 9 "
							. "AND us2_order_product_compliance.order_product_compliance_id IS NULL";

					// Get RecordsTotal
					$QueryTotal = "SELECT COUNT(*) AS count FROM ( {$Query} ) A";

					$debug[]	= $QueryTotal;
					$Rs = $Connection->executeQuery($QueryTotal);

					while ($Rs->next()) {
						$RecordsTotal = $Rs->get('count');
					}

					// Get RecordsFiltered
					if (!empty($this->searchClause)) {
						$QueryFiltered = "SELECT COUNT(*) AS count FROM (SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause} ) AS b";

						$debug[]	= $QueryFiltered;
						$Rs = $Connection->executeQuery($QueryFiltered);

						while ($Rs->next()) {
							$RecordsFiltered = $Rs->get('count');
						}
					} else {
						$RecordsFiltered = $RecordsTotal;
					}

					// Get Data
					$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";

					$debug[]	= $QueryData;
					$Rs = $Connection->executeQuery($QueryData);

					while ($Rs->next()) {
						$row				= $Rs->getRow();

						$order_product_id	= $row['order_product_id'];
						$product_id			= $row['product_id'];

						if (!empty($row['image'])) {
							$PreviewImage = "/?token=" . Convert::EncodeURL(urldecode(http_build_query(array(
								"Page" => "ProductImage",
								"URL" => $row['image']
							), "", "&")));
							if ($PreviewImage) {
								$preview_image = '<img src="' . $PreviewImage . '" class="draft-thumbnail" alt="">';
							}
						} else {
							$preview_image = '';
						}

						$desc			= explode('|', $row['description']);

						$total_quan = number_format($desc[5], 0);

						$description	= "<ul style=\"list-style: none inside; line-height: 1.5\">"
										. "<li>Product: {$desc[0]}</li>"
										. "<li>Order Note: {$desc[1]}</li>"
										. "<li>Dealer: {$desc[2]}</li>"
										. "<li>User: {$desc[3]}</li>"
										. "<li>Ref #: {$desc[4]}</li>"
										. "<li>Quantity: {$total_quan}</li>"
										. "</ul>";

						$complete_token		= Convert::EncodeURL("Page=CustomizeOrder&OrderProductId={$order_product_id}&ProductId={$product_id}");
						$complete			= "<a href=\"/?token={$complete_token}\" class=\"btn-complete active-button\">complete</a>";

						$cancel				= "<a href=\"#\" class=\"btn-draft-cancel dangerous-button\" data-order-product-id=\"{$order_product_id}\">cancel</a>";

						$data[]				= array(
							$order_product_id,
							$preview_image,
							$description,
							$complete,
							$cancel
						);
					}
				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetComplianceData":
				$this->GetDataTableParameters();

				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {
					$Connection = Propel::getConnection();

					$Query	= "SET SESSION group_concat_max_len = 10000000";
					$Connection->executeQuery($Query);

					$Query	= "SELECT GROUP_CONCAT(customer_id SEPARATOR ',') AS customer_id_list FROM customer WHERE client_id = {$this->CurrentClientId}";

					$Rs = $Connection->executeQuery($Query);

					while ($Rs->next()) {
						$CustomerIdList = $Rs->get('customer_id_list');
					}

					$Query	= "SELECT "
							. "us2_order_product.order_product_id AS order_product_id, "
							. "us2_order_product.product_id AS product_id, "
							. "DATE_FORMAT(us2_order_product_compliance.submitted_date, '%Y-%m-%d') AS requested, "
							. "DATE_FORMAT(us2_order_product_compliance.submitted_date, '%m/%d/%Y') AS requested_formatted, "
							. "customer.name AS dealer_name, "
							. "us2_product.name AS mailer_name, "
							. "us2_product.product_type_id AS product_type_id, "
							. "'' AS details, "
							. "'' AS agreement, "
							. "'' AS proof, "
							. "'' AS modify, "
							. "'' AS approve, "
							. "'' AS cancel "
							. "FROM us2_order_product "
							. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
							. "LEFT JOIN us2_product ON us2_order_product.product_id = us2_product.product_id "
							. "LEFT JOIN customer ON us2_order_product.customer_id = customer.customer_id "
							. "WHERE us2_order_product.customer_id IN ({$CustomerIdList}) "
							. "AND us2_order_product.parent_us2_order_product_id = 0 "
							. "AND us2_order_product.order_handling_status_id < 9 "
							. "AND us2_order_product_compliance.stage = 'Compliance'";

					// Get RecordsTotal
					$QueryTotal = "SELECT COUNT(*) AS count FROM ( {$Query} ) A";

					$debug[]	= $QueryTotal;
					$Rs = $Connection->executeQuery($QueryTotal);

					while ($Rs->next()) {
						$RecordsTotal = $Rs->get('count');
					}

					// Get RecordsFiltered
					if (!empty($this->searchClause)) {
						$QueryFiltered = "SELECT COUNT(*) AS count FROM (SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause} ) AS b";

						$debug[]	= $QueryFiltered;
						$Rs = $Connection->executeQuery($QueryFiltered);

						while ($Rs->next()) {
							$RecordsFiltered = $Rs->get('count');
						}
					} else {
						$RecordsFiltered = $RecordsTotal;
					}

					// Get Data
					$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";

					$debug[]	= $QueryData;
					$Rs = $Connection->executeQuery($QueryData);

					while ($Rs->next()) {
						$row				= $Rs->getRow();

						$order_product_id	= $row['order_product_id'];
						$product_id			= $row['product_id'];
						$modify_token		= Convert::EncodeURL("Page=CustomizeOrder&OrderProductId={$order_product_id}&ProductId={$product_id}");
						$row['requested']	= $row['requested_formatted'];
						unset($row['requested_formatted']);
						$row['details']		= "<a href=\"#\" class=\"btn-compliance-details\" data-id=\"{$order_product_id}\"><img src=\"/images/amms_store/info.svg\" class=\"dticon\" alt=\"details\" /></a>";
						$row['agreement']	= "<a href=\"#\" class=\"btn-compliance-agreement\" data-id=\"{$order_product_id}\"><img src=\"/images/amms_store/shopping-cart.svg\" class=\"dticon\" alt=\"agreement\" /></a>";
						if ($row['product_type_id'] == 1) {
							$row['proof']		= "<a href=\"#\" class=\"btn-compliance-pdf\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/pdf-file.svg\" class=\"dticon\" alt=\"pdf\" /></a>";
						} else {
							$row['proof']		= "<a href=\"#\" class=\"btn-compliance-pdf\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/pdf-file.svg\" class=\"dticon\" alt=\"pdf\" /></a>";
						}
						$row['modify']		= "<a href=\"/?token={$modify_token}\" class=\"btn-compliance-modify active-button\">modify</a>";
						$row['approve']		= "<a href=\"#\" class=\"btn-compliance-approve options-button\" data-order-product-id=\"{$order_product_id}\">approve</a>";
						$row['cancel']		= "<a href=\"#\" class=\"btn-compliance-cancel dangerous-button\" data-order-product-id=\"{$order_product_id}\">cancel</a>";
						unset($row['product_id']);
						unset($row['product_type_id']);
						if (STORE_ID == CE_STORE_ID) {
							unset($row['agreement']);
							unset($row['proof']);
						}

						$data[] = array_values($row);
					}
				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetPendingData":
				$this->GetDataTableParameters();

				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {

					$Connection = Propel::getConnection();

					$Query	= "SET SESSION group_concat_max_len = 10000000";
					$Connection->executeQuery($Query);

					$Query	= "SELECT GROUP_CONCAT(customer_id SEPARATOR ',') AS customer_id_list FROM customer WHERE client_id = {$this->CurrentClientId}";

					$Rs = $Connection->executeQuery($Query);

					while ($Rs->next()) {
						$CustomerIdList = $Rs->get('customer_id_list');
					}

					$Query	= "SELECT "
							. "us2_order_product.order_product_id AS order_product_id, "
							. "us2_order_product.product_id AS product_id, "
							. "us2_order_product.customer_id AS customer_id, "
							. "DATE_FORMAT(us2_order_product_compliance.submitted_date, '%Y-%m-%d') AS requested, "
							. "DATE_FORMAT(us2_order_product_compliance.submitted_date, '%m/%d/%Y') AS requested_formatted, "
							. "customer.name AS dealer_name, "
							. "us2_product.name AS mailer_name, "
							. "us2_product.product_type_id AS product_type_id, "
							. "COALESCE(us2_order_product.total_quan, 0) AS quantity, "
							. "us2_order_product.total_price AS price, "
							. "us2_order_product_mailing_list.dms_count_net AS dms_count_net, "
							. "us2_order_product_mailing_list.conquest_count_net AS conquest_count_net, "
							. "'' AS details, "
							. "'' AS agreement, "
							. "'' AS proof, "
							. "us2_order_product.recipient_list_id AS maillist, "
							. "'' AS complete, "
							. "'' AS cancel "
							. "FROM us2_order_product "
							. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
							. "LEFT JOIN us2_order_product_mailing_list ON us2_order_product.order_product_id = us2_order_product_mailing_list.order_product_id AND us2_order_product.recipient_list_id = us2_order_product_mailing_list.pull_master_id "
							. "LEFT JOIN us2_product ON us2_order_product.product_id = us2_product.product_id "
							. "LEFT JOIN customer ON us2_order_product.customer_id = customer.customer_id "
							. "WHERE us2_order_product.customer_id IN ({$CustomerIdList}) "
							. "AND us2_order_product.parent_us2_order_product_id = 0 "
							. "AND us2_order_product.order_handling_status_id < 9 "
							. "AND us2_order_product_compliance.stage = 'Payment'";

					// Get RecordsTotal
					$QueryTotal = "SELECT COUNT(*) AS count FROM ( {$Query} ) A";

					$debug[]	= $QueryTotal;
					$Rs = $Connection->executeQuery($QueryTotal);

					while ($Rs->next()) {
						$RecordsTotal = $Rs->get('count');
					}

					// Get RecordsFiltered
					if (!empty($this->searchClause)) {
						$QueryFiltered = "SELECT COUNT(*) AS count FROM (SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause} ) AS b";

						$debug[]	= $QueryFiltered;
						$Rs = $Connection->executeQuery($QueryFiltered);

						while ($Rs->next()) {
							$RecordsFiltered = $Rs->get('count');
						}
					} else {
						$RecordsFiltered = $RecordsTotal;
					}

					// Get Data
					$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";

					$debug[]	= $QueryData;
					$Rs = $Connection->executeQuery($QueryData);

					while ($Rs->next()) {
						$row				= $Rs->getRow();

						$order_product_id	= $row['order_product_id'];
						$product_id			= $row['product_id'];
						$customer_id		= $row['customer_id'];
						$quantity			= $row['quantity'];
						$dms_count_net		= $row['dms_count_net'];
						$conquest_count_net	= $row['conquest_count_net'];

						if (STORE_ID != CE_STORE_ID) {
							// Get the associated list order product
							$ListOrderProduct	= $this->GetConquestListOrderProduct($order_product_id);

							// Wholesale is true because we are presenting this to the admin/client/wholesale customer
							// Get the price of the mail piece
							$MailPrice			= $this->GetPrice($customer_id, $product_id, $quantity, true);
							// Get the price for the mailing list
							if ($ListOrderProduct !== false) {
								$ListPrice			= $this->GetPrice($customer_id, $ListOrderProduct->getProductId(), $conquest_count_net, true);
							} else {
								$ListPrice			= 0;
							}

							// Get the combined price for the product plus conquest pricing
							$row['price']			= $MailPrice + $ListPrice;
						}

						$modify_token		= Convert::EncodeURL("Page=CustomizeOrder&OrderProductId={$order_product_id}&ProductId={$product_id}");
						$row['requested']	= $row['requested_formatted'];
						unset($row['requested_formatted']);
						$row['quantity']	= "<span id=\"payment-quantity-{$order_product_id}\">".number_format($row['quantity'], 0)."</span>";
						$row['price']		= "<span id=\"payment-price-{$order_product_id}\">$".number_format($row['price'], 2)."</span>";
						$row['details']		= "<a href=\"#\" class=\"btn-payment-details\" data-id=\"{$order_product_id}\"><img src=\"/images/amms_store/info.svg\" class=\"dticon\" alt=\"details\" /></a>";
						$row['agreement']	= "<a href=\"#\" class=\"btn-payment-agreement\" data-id=\"{$order_product_id}\"><img src=\"/images/amms_store/shopping-cart.svg\" class=\"dticon\" alt=\"agreement\" /></a>";
						if ($row['product_type_id'] == 1) {
							$row['proof']		= "<a href=\"#\" class=\"btn-payment-pdf\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/pdf-file.svg\" class=\"dticon\" alt=\"pdf\" /></a>";
							if (!empty($row['maillist'])) {
								$row['maillist']	= "<span id=\"payment-maillist-{$order_product_id}\"><a href=\"#\" class=\"btn-payment-maillist\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/download.svg\" class=\"dticon\" alt=\"maillist\" /></a></span>";
							} else {
								$row['maillist']	= "<span id=\"payment-maillist-{$order_product_id}\" class=\"icon-payment-pending\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/ajax_indicator00.gif\" class=\"dticon\" alt=\"maillist\" /></span>";
							}
						} else {
							$row['proof']		= "<a href=\"#\" class=\"btn-payment-pdf\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/pdf-file.svg\" class=\"dticon\" alt=\"pdf\" /></a>";
							$row['maillist']	= "<span id=\"payment-maillist-{$order_product_id}\"><img src=\"/images/amms_store/forbidden.svg\" class=\"dticon\" alt=\"maillist\" /></span>";
						}
						$row['complete']	= "<a href=\"#\" class=\"btn-payment-complete options-button\" data-order-product-id=\"{$order_product_id}\">complete</a>";
						$row['cancel']		= "<a href=\"#\" class=\"btn-payment-cancel dangerous-button\" data-order-product-id=\"{$order_product_id}\">cancel</a>";
						unset($row['product_id']);
						unset($row['product_type_id']);
						unset($row['customer_id']);
						unset($row['dms_count_net']);
						unset($row['conquest_count_net']);
						if (STORE_ID == CE_STORE_ID) {
							unset($row['agreement']);
							unset($row['proof']);
						}

						$data[] = array_values($row);
					}
				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetCompletedData":
				$this->GetDataTableParameters();

				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {
					$Connection = Propel::getConnection();

					$Query	= "SET SESSION group_concat_max_len = 10000000";
					$Connection->executeQuery($Query);

					$Query	= "SELECT GROUP_CONCAT(customer_id SEPARATOR ',') AS customer_id_list FROM customer WHERE client_id = {$this->CurrentClientId}";

					$Rs = $Connection->executeQuery($Query);

					while ($Rs->next()) {
						$CustomerIdList = $Rs->get('customer_id_list');
					}

					$Query	= "SELECT "
							. "us2_order_product.order_product_id AS order_product_id, "
							. "DATE_FORMAT(us2_order_product_compliance.submitted_date, '%Y-%m-%d') AS requested, "
							. "DATE_FORMAT(us2_order_product_compliance.submitted_date, '%m/%d/%Y') AS requested_formatted, "
							. "customer.name AS dealer_name, "
							. "us2_product.name AS mailer_name, "
							. "us2_product.product_type_id AS product_type_id, "
							. "'' AS details, "
							. "'' AS agreement, "
							. "'' AS proof, "
							. "us2_order_product.recipient_list_id AS maillist, "
							. "'' AS cancel, "
							. "us2_order_product.product_id AS product_id "
							. "FROM us2_order_product "
							. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
							. "LEFT JOIN us2_product ON us2_order_product.product_id = us2_product.product_id "
							. "LEFT JOIN customer ON us2_order_product.customer_id = customer.customer_id "
							. "WHERE us2_order_product.customer_id IN ({$CustomerIdList}) "
							. "AND us2_order_product.parent_us2_order_product_id = 0 "
							. "AND us2_order_product.order_handling_status_id < 9 "
							. "AND us2_order_product_compliance.stage IN ('Complete', 'Processing')";

					// Get RecordsTotal
					$QueryTotal = "SELECT COUNT(*) AS count FROM ( {$Query} ) A";

					$debug[]	= $QueryTotal;
					$Rs = $Connection->executeQuery($QueryTotal);

					while ($Rs->next()) {
						$RecordsTotal = $Rs->get('count');
					}

					// Get RecordsFiltered
					if (!empty($this->searchClause)) {
						$QueryFiltered = "SELECT COUNT(*) AS count FROM (SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause} ) AS b";

						$debug[]	= $QueryFiltered;
						$Rs = $Connection->executeQuery($QueryFiltered);

						while ($Rs->next()) {
							$RecordsFiltered = $Rs->get('count');
						}
					} else {
						$RecordsFiltered = $RecordsTotal;
					}

					// Get Data
					$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";

					$debug[]	= $QueryData;
					$Rs = $Connection->executeQuery($QueryData);

					while ($Rs->next()) {
						$row				= $Rs->getRow();

						$order_product_id	= $row['order_product_id'];
						$product_id			= $row['product_id'];
						$modify_token		= Convert::EncodeURL("Page=CustomizeOrder&OrderProductId={$order_product_id}&ProductId={$product_id}");
						$row['requested']	= $row['requested_formatted'];
						unset($row['requested_formatted']);
						$row['details']		= "<a href=\"#\" class=\"btn-completed-details\" data-id=\"{$order_product_id}\"><img src=\"/images/amms_store/info.svg\" class=\"dticon\" alt=\"details\" /></a>";
						$row['agreement']	= "<a href=\"#\" class=\"btn-completed-agreement\" data-id=\"{$order_product_id}\"><img src=\"/images/amms_store/shopping-cart.svg\" class=\"dticon\" alt=\"agreement\" /></a>";
						if ($row['product_type_id'] == 1) {
							$row['proof']		= "<a href=\"#\" class=\"btn-completed-pdf\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/pdf-file.svg\" class=\"dticon\" alt=\"pdf\" /></a>";
							if (!empty($row['maillist'])) {
								$row['maillist']	= "<span id=\"completed-maillist-{$order_product_id}\"><a href=\"#\" class=\"btn-completed-maillist\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/download.svg\" class=\"dticon\" alt=\"maillist\" /></a></span>";
							} else {
								$row['maillist']	= "<span id=\"completed-maillist-{$order_product_id}\" class=\"icon-completed-pending\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/ajax_indicator00.gif\" class=\"dticon\" alt=\"maillist\" /></span>";
							}
						} else {
							$row['proof']		= "<a href=\"#\" class=\"btn-completed-pdf\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/pdf-file.svg\" class=\"dticon\" alt=\"pdf\" /></a>";
							$row['maillist']	= "<span id=\"completed-maillist-{$order_product_id}\"><img src=\"/images/amms_store/forbidden.svg\" class=\"dticon\" alt=\"maillist\" /></span>";
						}
						$row['cancel']		= "<a href=\"#\" class=\"btn-completed-cancel dangerous-button\" data-order-product-id=\"{$order_product_id}\">cancel</a>";
						unset($row['product_id']);
						unset($row['product_type_id']);
						if (STORE_ID == CE_STORE_ID) {
							unset($row['agreement']);
							unset($row['proof']);
						}

						$data[] = array_values($row);
					}
				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetSalesReportData":
				$this->GetDataTableParameters();
				// Dates will be submitted in m/d/Y format but must be converted to Y-m-d format
				$this->DateFrom			= $this->DateFrom ? date('Y-m-d', strtotime($this->DateFrom)) : date('Y-m-d', strtotime("-1 month"));
				$QueryFrom				= date('Y-m-d 00:00:00', strtotime($this->DateFrom));
				$this->DateTo			= $this->DateTo ? date('Y-m-d', strtotime($this->DateTo)) : date('Y-m-d');
				$QueryTo				= date('Y-m-d 23:59:59', strtotime($this->DateTo));

				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {
					$Connection = Propel::getConnection();

					$arrayOrder	= array();


					$Query	= "SELECT "
							. "us2_order.order_id AS order_id, "
							. "DATE_FORMAT(us2_order.order_created_date, '%Y-%m-%d') AS created_date, "
							. "DATE_FORMAT(us2_order.order_created_date, '%m/%d/%Y') AS created_date_formatted, "
							. "sf_guard_user_profile.company AS company_name, "
							. "customer.name AS mailer_name, "
							. "FORMAT(us2_order.total_due, 2) AS order_total, "
							. "FORMAT((us2_order.wholesale_order_amount + us2_order.wholesale_tax_amount), 2) AS wholesale_total, "
							. "FORMAT((us2_order.total_due - (us2_order.wholesale_order_amount + us2_order.wholesale_tax_amount)), 2) AS net_total, "
							. "us2_order_type.name AS order_type, "
							. "us2_order_handling_status.name AS order_status, "
							. "CONCAT('Page=ViewCompleteOrderDetail&OrderId=', us2_order.order_id) AS view_link "
							. "FROM us2_order "
							. "LEFT JOIN customer ON us2_order.customer_id = customer.customer_id "
							. "LEFT JOIN us2_order_type ON us2_order.us2_order_type_id = us2_order_type.us2_order_type_id "
							. "LEFT JOIN sf_guard_user_profile ON us2_order.user_id = sf_guard_user_profile.user_id "
							. "LEFT JOIN us2_order_handling_status ON us2_order.order_handling_status_id = us2_order_handling_status.us2_order_handling_status_id "
							. "WHERE us2_order.store_id = '".STORE_ID."' "
							. "AND us2_order.client_id = '{$this->CurrentClientId}' "
							. "AND us2_order.us2_order_type_id IN (1,3) "
							. "AND us2_order.order_created_date BETWEEN '{$QueryFrom}' AND '{$QueryTo}' ";

					// Get RecordsTotal
					$QueryTotal = "SELECT COUNT(*) AS count FROM ( {$Query} ) A";

					$debug[]	= $QueryTotal;
					$Rs = $Connection->executeQuery($QueryTotal);

					while ($Rs->next()) {
						$RecordsTotal = $Rs->get('count');
					}

					// Get RecordsFiltered
					if (!empty($this->searchClause)) {
						$QueryFiltered = "SELECT COUNT(*) AS count FROM (SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause} ) AS b";

						$debug[]	= $QueryFiltered;
						$Rs = $Connection->executeQuery($QueryFiltered);

						while ($Rs->next()) {
							$RecordsFiltered = $Rs->get('count');
						}
					} else {
						$RecordsFiltered = $RecordsTotal;
					}

					// Get Data
					$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";

					$debug[]	= $QueryData;
					$Rs = $Connection->executeQuery($QueryData);

					while ($Rs->next()) {
						$row					= $Rs->getRow();
						$row['created_date']	= $row['created_date_formatted'];
						unset($row['created_date_formatted']);
						$row['view_link']		= '<a href="/?token=' . Convert::EncodeURL($row['view_link']) . '" target="_blank">View&nbsp;Order</a>';
						$data[] = array_values($row);
					}
				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetMyWorkspaceData":
				$this->GetDataTableParameters();

				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {
					$Connection = Propel::getConnection();

					if ($this->AccessControl->hasGroup(array('ADMIN','STORE ADMIN')) && isset($this->UsingUserId)) {
						$this->UsingUserId	= intval($this->UsingUserId);
						if ($this->UsingUserId == -1) {
							$QueryUserId = "";
						} else {
							$QueryUserId = "AND us2_order_product.created_by_user_id = {$this->UsingUserId} ";
						}
						$Query	= "SELECT "
								. "us2_order_product.order_product_id, "
								. "us2_image.preview_url AS image, "
								. "CONCAT( "
								. "us2_product.name,'|', "
								. "us2_order_product.order_notes, '|', "
								. "us2_order_product.product_id, '|', "
								. "0 "
								. ") AS description, "
								. "'' AS complete, "
								. "'' AS cancel "
								. "FROM us2_order_product "
								. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
								. "LEFT JOIN us2_product ON us2_order_product.product_id = us2_product.product_id "
								. "LEFT JOIN us2_image ON us2_product.small_image_id = us2_image.us2_image_id "
								. "WHERE us2_order_product.customer_id = {$this->CurrentCustomerId} "
								. $QueryUserId
								. "AND us2_order_product.parent_us2_order_product_id = 0 "
								. "AND us2_order_product.order_handling_status_id < 9 "
								. "AND us2_order_product_compliance.order_product_compliance_id IS NULL";
					} else {
						$Query	= "SELECT "
								. "us2_order_product.order_product_id, "
								. "us2_image.preview_url AS image, "
								. "CONCAT( "
								. "us2_product.name,'|', "
								. "us2_order_product.order_notes, '|', "
								. "us2_order_product.product_id, '|', "
								. "0 "
								. ") AS description, "
								. "'' AS complete, "
								. "'' AS cancel "
								. "FROM us2_order_product "
								. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
								. "LEFT JOIN us2_product ON us2_order_product.product_id = us2_product.product_id "
								. "LEFT JOIN us2_image ON us2_product.small_image_id = us2_image.us2_image_id "
								. "WHERE us2_order_product.customer_id = {$this->CurrentCustomerId} "
								. "AND us2_order_product.created_by_user_id = {$this->CurrentUserId} "
								. "AND us2_order_product.parent_us2_order_product_id = 0 "
								. "AND us2_order_product.order_handling_status_id < 9 "
								. "AND us2_order_product_compliance.order_product_compliance_id IS NULL";
					}

					// Get RecordsTotal
					$QueryTotal = "SELECT COUNT(*) AS count FROM ( {$Query} ) A";

					$debug[]	= $QueryTotal;
					$Rs = $Connection->executeQuery($QueryTotal);

					while ($Rs->next()) {
						$RecordsTotal = $Rs->get('count');
					}

					// Get RecordsFiltered
					if (!empty($this->searchClause)) {
						$QueryFiltered = "SELECT COUNT(*) AS count FROM (SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause} ) AS b";

						$debug[]	= $QueryFiltered;
						$Rs = $Connection->executeQuery($QueryFiltered);

						while ($Rs->next()) {
							$RecordsFiltered = $Rs->get('count');
						}
					} else {
						$RecordsFiltered = $RecordsTotal;
					}

					// Get Data
					$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";

					$debug[]	= $QueryData;
					$Rs = $Connection->executeQuery($QueryData);

					while ($Rs->next()) {
						$row				= $Rs->getRow();

						$order_product_id	= $row['order_product_id'];
						$product_id			= $row['product_id'];

						if (!empty($row['image'])) {
							$PreviewImage = "/?token=" . Convert::EncodeURL(urldecode(http_build_query(array(
								"Page" => "ProductImage",
								"URL" => $row['image']
							), "", "&")));
							if ($PreviewImage) {
								$preview_image = '<img src="' . $PreviewImage . '" class="workspace-thumbnail" alt="">';
							}
						} else {
							$preview_image = '';
						}

						$desc			= explode('|', $row['description']);

						$total_quan = number_format($desc[5], 0);

						$description	= "<ul style=\"list-style: none inside; line-height: 1.5\">"
										. "<li>Product: {$desc[0]}</li>"
										. "<li>Order Note: {$desc[1]}</li>"
										. "<li>Ref #: {$desc[2]}</li>"
										. "<li>Quantity: {$total_quan}</li>"
										. "</ul>";

						$complete_token		= Convert::EncodeURL("Page=CustomizeOrder&OrderProductId={$order_product_id}&ProductId={$product_id}");
						$complete			= "<a href=\"/?token={$complete_token}\" class=\"btn-complete active-button\">complete</a>";

						$cancel				= "<a href=\"#\" class=\"btn-workspace-cancel dangerous-button\" data-order-product-id=\"{$order_product_id}\">cancel</a>";

						$data[]				= array(
							$order_product_id,
							$preview_image,
							$description,
							$complete,
							$cancel
						);
					}
				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetOrderHistoryData":
				$this->GetDataTableParameters();

				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {
					$Connection = Propel::getConnection();

					$Query	= "SELECT "
							. "us2_order_product.order_product_id AS order_product_id, "
							. "us2_order_product.product_id AS product_id, "
							. "us2_order_product.customer_id AS customer_id, "
							. "DATE_FORMAT(us2_order_product_compliance.submitted_date, '%Y-%m-%d') AS requested, "
							. "DATE_FORMAT(us2_order_product_compliance.submitted_date, '%m/%d/%Y') AS requested_formatted, "
							. "us2_product.name AS mailer_name, "
							. "us2_product.product_type_id as product_type_id, "
							. "COALESCE(us2_order_product.total_quan, 0) AS quantity, "
							. "COALESCE(us2_order_product.total_price, 0) AS price, "
							. "us2_order_product_mailing_list.dms_count_net AS dms_count_net, "
							. "us2_order_product_mailing_list.conquest_count_net AS conquest_count_net, "
							. "'' AS details, "
							. "'' AS agreement, "
							. "'' AS proof, "
							. "us2_order_product.recipient_list_id AS maillist, "
							. "us2_order_product_compliance.stage AS status "
							. "FROM us2_order_product "
							. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
							. "LEFT JOIN us2_order_product_mailing_list ON us2_order_product.order_product_id = us2_order_product_mailing_list.order_product_id AND us2_order_product.recipient_list_id = us2_order_product_mailing_list.pull_master_id "
							. "LEFT JOIN us2_product ON us2_order_product.product_id = us2_product.product_id "
							. "WHERE us2_order_product.customer_id = {$this->CurrentCustomerId} "
							. "AND us2_order_product.parent_us2_order_product_id = 0 "
							. "AND us2_order_product.order_handling_status_id < 9 "
							. "AND us2_order_product_compliance.stage IN ('Completed', 'Processing')";

					// Get RecordsTotal
					$QueryTotal = "SELECT COUNT(*) AS count FROM ( {$Query} ) A";

					$debug[]	= $QueryTotal;
					$Rs = $Connection->executeQuery($QueryTotal);

					while ($Rs->next()) {
						$RecordsTotal = $Rs->get('count');
					}

					// Get RecordsFiltered
					if (!empty($this->searchClause)) {
						$QueryFiltered = "SELECT COUNT(*) AS count FROM (SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause} ) AS b";

						$debug[]	= $QueryFiltered;
						$Rs = $Connection->executeQuery($QueryFiltered);

						while ($Rs->next()) {
							$RecordsFiltered = $Rs->get('count');
						}
					} else {
						$RecordsFiltered = $RecordsTotal;
					}

					// Get Data
					$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";

					$debug[]	= $QueryData;
					$Rs = $Connection->executeQuery($QueryData);

					while ($Rs->next()) {
						$row				= $Rs->getRow();

						$order_product_id	= $row['order_product_id'];
						$product_id			= $row['product_id'];
						$customer_id		= $row['customer_id'];
						$quantity			= $row['quantity'];
						$dms_count_net		= $row['dms_count_net'];
						$conquest_count_net	= $row['conquest_count_net'];

						// Get the associated list order product
						$ListOrderProduct	= $this->GetConquestListOrderProduct($order_product_id);

						// Wholesale is false because we are presenting this to the dealer/retail customer
						// Get the price of the mail piece
						$MailPrice			= $this->GetPrice($customer_id, $product_id, $quantity, false);
						// Get the price for the mailing list
						$ListPrice			= (!empty($ListOrderProduct)) ? $this->GetPrice($customer_id, $ListOrderProduct->getProductId(), $conquest_count_net, false) : 0;

						// Get the combined price for the product plus conquest pricing
						$row['price']			= $MailPrice + $ListPrice;

						$modify_token		= Convert::EncodeURL("Page=CustomizeOrder&OrderProductId={$order_product_id}&ProductId={$product_id}");
						$row['requested']	= $row['requested_formatted'];
						unset($row['requested_formatted']);
						$row['quantity']	= "<span id=\"history-quantity-{$order_product_id}\">".number_format($row['quantity'], 0)."</span>";
						$row['price']		= "<span id=\"history-price-{$order_product_id}\">$".number_format($row['price'], 2)."</span>";
						$row['details']		= "<a href=\"#\" class=\"btn-history-details\" data-id=\"{$order_product_id}\"><img src=\"/images/amms_store/info.svg\" class=\"dticon\" alt=\"details\" /></a>";
						$row['agreement']	= "<a href=\"#\" class=\"btn-history-agreement\" data-id=\"{$order_product_id}\"><img src=\"/images/amms_store/shopping-cart.svg\" class=\"dticon\" alt=\"agreement\" /></a>";
						if ($row['product_type_id'] == 1) {
							$row['proof']		= "<a href=\"#\" class=\"btn-history-pdf\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/pdf-file.svg\" class=\"dticon\" alt=\"pdf\" /></a>";
							if (!empty($row['maillist'])) {
								$row['maillist']	= "<span id=\"history-maillist-{$order_product_id}\"><a href=\"#\" class=\"btn-history-maillist\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/download.svg\" class=\"dticon\" alt=\"maillist\" /></a></span>";
							} else {
								$row['maillist']	= "<span id=\"history-maillist-{$order_product_id}\" class=\"icon-history-pending\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/ajax_indicator00.gif\" class=\"dticon\" alt=\"maillist\" /></span>";
							}
						} else {
							$row['proof']		= "<a href=\"#\" class=\"btn-history-pdf\" data-order-product-id=\"{$order_product_id}\"><img src=\"/images/amms_store/pdf-file.svg\" class=\"dticon\" alt=\"pdf\" /></a>";
							$row['maillist']	= "<span id=\"history-maillist-{$order_product_id}\"><img src=\"/images/amms_store/forbidden.svg\" class=\"dticon\" alt=\"maillist\" /></span>";
						}
						$row['complete']	= "<a href=\"#\" class=\"btn-history-complete options-button\" data-order-product-id=\"{$order_product_id}\">complete</a>";
						$row['cancel']		= "<a href=\"#\" class=\"btn-history-cancel dangerous-button\" data-order-product-id=\"{$order_product_id}\">cancel</a>";
						unset($row['product_id']);
						unset($row['product_type_id']);
						unset($row['customer_id']);
						unset($row['dms_count_net']);
						unset($row['conquest_count_net']);
						if (STORE_ID == CE_STORE_ID) {
							unset($row['agreement']);
						}

						$data[] = array_values($row);
					}
				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetProofUrl":
				// Initialize data
				$data = null;
				$error = null;
				$debug = array();

				try {
					$Connection = Propel::getConnection();

					$OrderProductId = $this->getRequestParameter("OrderProductId", 0);
					if (!empty($OrderProductId)) {
						// Get the most recent proof
						$Query	= "SELECT proof_url FROM us2_order_proof "
								. "WHERE us2_order_product_id = '{$OrderProductId}' "
								. "ORDER BY us2_order_proof_id DESC "
								. "LIMIT 1";
						$debug[] = $Query;

						$Rs = $Connection->executeQuery($Query);

						while ($Rs->next()) {
							$data = $Rs->get('proof_url');
						}
					}
				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$result = array(
					"data" => $data,
					"debug" => $debug
				);
				if (!empty($error)) {
					$result['error'] = $error;
				}

				return $this->renderText(json_encode($result));
				break;

			case "GetMailingList":
				// Initialize data
				$Content = '';

				try {
					$Connection = Propel::getConnection();

					$OrderProductId = $this->getRequestParameter("OrderProductId", 0);
					if (!empty($OrderProductId)) {
						// Get the mailing list id
						$Query	= "SELECT recipient_list_id FROM us2_order_product "
								. "WHERE order_product_id = '{$OrderProductId}'";
						$debug[] = $Query;

						$Rs = $Connection->executeQuery($Query);

						while ($Rs->next()) {
							$pull_master_id = $Rs->get('recipient_list_id');
						}

						if (!empty($pull_master_id)) {
							$url = "cyberhackney.ammscore.com/PullData/?version=1.01&user_id=1&mode=mail&pull_master_id={$pull_master_id}";
							$PullData = $this->curlGet($url);
							$PullData = json_decode($PullData, true);

							// Leave out the address field to satisfy conquest data restrictions
							$HeaderFields	= array('FIRST','MIDDLE','LAST','CITY','STATE','ZIP');
							$arrayFields	= $PullData['fields'];
							$arrayData		= $PullData['data'];
							// Create header
							$Content		= "\"".implode('","', $HeaderFields)."\"\n";
							// For each row in arrayData
							foreach ($arrayData as $data) {
								$temp			= array();
								// Using only those fields we want
								foreach ($HeaderFields as $field) {
									// Construct the row
									$temp[] = '"'.$data[$field].'"';
								}
								// Add it to the result
								$Content .= implode(',', $temp)."\n";
							}
						} else {
							die("The mailing list for this job has not been created yet.");
						}
					}
				} catch (Exception $e) {
					$error = $e->getMessage();

					die($error);
				}

				header("Cache-Control: maxage=1");
				header("Pragma: public");
				header("Content-type: text/csv");
				header("Content-Disposition: attachment; filename=\"order_{$OrderProductId}.csv\"");
				header("Content-Description: PHP Generated Data");
				header("Content-Transfer-Encoding: binary");
				header('Content-Length:' . strlen($Content));
				return $this->renderText($Content);
				break;

			case "ApproveCompliance":
				try {
					$Connection = Propel::getConnection();

					$OrderProductId = $this->getRequestParameter("OrderProductId", 0);
					$debug = array();
					if (!empty($OrderProductId)) {
						// Move display of order product to Pending Payment page
						$Query	= "UPDATE us2_order_product_compliance SET "
								. "stage = 'Payment', "
								. "approved_yn = 'Y', "
								. "approved_by_user_id = '{$this->AccessControl->UserId}', "
								. "approved_date = NOW() "
								. "WHERE order_product_id = {$OrderProductId} "
								. "AND stage = 'Compliance'";
						$debug[] = $Query;

						$Connection->executeQuery($Query);

						// Set stage to Compliance so that mailing list processing can start
						$Query	= "UPDATE us2_order_product_mailing_list SET "
								. "stage = 'Compliance' "
								. "WHERE order_product_id = {$OrderProductId} "
								. "AND stage = 'New'";
						$debug[] = $Query;

						$Connection->executeQuery($Query);
					}

					return $this->renderText(json_encode(array("success" => true, "debug" => $debug)));
				} catch (Exception $e) {
					$error = $e->getMessage();

					return $this->renderText(json_encode(array("success" => false, "error" => $error, "debug" => $debug)));
				}
				break;

			case "CompletePaymentInvoice":

// error_log("CompletePaymentInvoice");
				try {

				// Begin using non-cached classes
					// require_once (SF_ROOT_DIR . "/apps/webservices/includes/inc.ammspricing_config.php");
					// require_once (SF_ROOT_DIR . "/apps/webservices/includes/inc.ammspayment_config.php");
					// require_once (SF_ROOT_DIR . "/apps/webservices/includes/class.ammspricing_var.php");
					// require_once (SF_ROOT_DIR . "/apps/webservices/includes/class.ammspayment_var.php");
					// require_once (SF_ROOT_DIR . "/apps/webservices/includes/inc.ammslist_config.php");
					// require_once (SF_ROOT_DIR . "/apps/webservices/includes/class.ammslist_var.php");

					// require_once (SF_ROOT_DIR . "/classes/verisign.class.php");
					// require_once (SF_ROOT_DIR . "/classes/authorizenet.class.php");
					// require_once (SF_ROOT_DIR . "/classes/crypt_cypher.php");
					// require_once (SF_ROOT_DIR . '/classes/AmmsPayment.class.php');
					// require_once (SF_ROOT_DIR . '/classes/AmmsPricing.class.php');

					// $CAmmsPayment = new AmmsPayment();
					// $CAmmsPricing = new AmmsPricing();
				// End using non-cached classes
				// Begin using cached classes
					require_once (SF_ROOT_DIR . "/apps/webservices/includes/inc.ammspayment_config.php");
					require_once (SF_ROOT_DIR . "/apps/webservices/includes/class.ammspayment_var.php");
					require_once (SF_ROOT_DIR . "/apps/webservices/includes/inc.ammslist_config.php");
					require_once (SF_ROOT_DIR . "/apps/webservices/includes/class.ammslist_var.php");

					require_once (SF_ROOT_DIR . "/classes/verisign.class.php");
					require_once (SF_ROOT_DIR . "/classes/authorizenet.class.php");
					require_once (SF_ROOT_DIR . "/classes/crypt_cypher.php");
					require_once (SF_ROOT_DIR . '/lib/class.ammspayment_cache2.php');

					$CAmmsPayment = new AmmsPayment_Cache();
				// End using cached classes

					$Connection = Propel::getConnection();

					// This is the order product that we are completing
					$OrderProductId			= $this->getRequestParameter("OrderProductId", 0);
					$Us2OrderProduct		= Us2OrderProductPeer::retrieveByPK($OrderProductId);
					// Set draft to N or it will not show up in GetItemsInCart
					$Us2OrderProduct->setIsDraftYn('N');
					$Us2OrderProduct->save();

// error_log("OrderProductId: {$OrderProductId}");
					// Get the order it's attached to
					$OrderId				= $Us2OrderProduct->getOrderId();
// error_log("OldOrderId: {$OrderId}");
					$ItemsInCart			= Us2OrderProductPeer::GetItemsInCart($OrderId);
// error_log("count(ItemsInCart({$OrderId})): " . count($ItemsInCart));

					// If there are other items in the cart
					if (count($ItemsInCart) > 1) {
						// Get the original order for this line item
						$OldOrder							= Us2OrderPeer::retrieveByPK($OrderId);

						// Create a new order with just this one item
						$NewOrder							= new Us2Order();
						$NewOrder->setStoreId(STORE_ID);
						$NewOrder->setUserId($OldOrder->getUserId());
						$NewOrder->setCustomerId($OldOrder->getCustomerId());
						$NewOrder->setClientId($OldOrder->getClientId());
						$NewOrder->setIsCartYn('Y');
						$NewOrder->setCartCreatedDate(date('Y-m-d H:i:s'));
						$NewOrder->save();

						$NewOrderId							= $NewOrder->getOrderId();
// error_log("NewOrderId: {$NewOrderId}");

						// Move the line item to the new order
						$Us2OrderProduct->setOrderId($NewOrderId);
						$Us2OrderProduct->save();

						// Calculate pricing for $NewOrder.
						$Input								= new AddPayment();
						$Input->Username					= "amms";
						$Input->Password					= "6gjknJKLSF*";
						$Input->ClientId					= CustomerPeer::GetClientByCustomer($NewOrder->getCustomerId());
						$Input->CustomerId					= $NewOrder->getCustomerId();
						$Input->UserId						= "4";
						$Input->OrderId						= $NewOrder->getOrderId();
// error_log("calling UpdateOrder 1...");
						try { $Response = $CAmmsPayment->UpdateOrder($Input); } catch ( SoapFault $E ) {
							//echo print_r($E, true) . "<br />";
						}
// error_log("UpdateOrder 1 returned.");

						// Recalculate pricing for $OldOrder to remove the order product.
						$Input								= new AddPayment();
						$Input->Username					= "amms";
						$Input->Password					= "6gjknJKLSF*";
						$Input->ClientId					= CustomerPeer::GetClientByCustomer($OldOrder->getCustomerId());
						$Input->CustomerId					= $OldOrder->getCustomerId();
						$Input->UserId						= "4";
						$Input->OrderId						= $OldOrder->getOrderId();
// error_log("calling UpdateOrder 2...");
						try { $Response = $CAmmsPayment->UpdateOrder($Input); } catch ( SoapFault $E ) {
							//echo print_r($E, true) . "<br />";
						}
// error_log("UpdateOrder 2 returned.");
$temp = Us2OrderPeer::retrieveByPK($Input->OrderId);
// error_log("After UpdateOrder 2: ".print_r($temp, true));

						// Use this order ID for close
						$this->OrderId						= $NewOrder->getOrderId();
					} else {
						// There is only one item, so just use the existing order ID for close
						$this->OrderId						= $OrderId;
						$this->Order						= Us2OrderPeer::retrieveByPK($OrderId);

						// Calculate pricing for $this->Order.
						$Input								= new AddPayment();
						$Input->Username					= "amms";
						$Input->Password					= "6gjknJKLSF*";
						$Input->ClientId					= CustomerPeer::GetClientByCustomer($this->Order->getCustomerId());
						$Input->CustomerId					= $this->Order->getCustomerId();
						$Input->UserId						= "4";
						$Input->OrderId						= $this->OrderId;
// error_log("calling UpdateOrder 3...");
						try { $Response = $CAmmsPayment->UpdateOrder($Input); } catch ( SoapFault $E ) {
							//echo print_r($E, true) . "<br />";
						}
// error_log("UpdateOrder 3 returned.");
$temp = Us2OrderPeer::retrieveByPK($Input->OrderId);
// error_log("After UpdateOrder 3: ".print_r($temp, true));

					}

// error_log("ThisOrderId: ".$this->OrderId);

					// Reload the order
					$this->Order = Us2OrderPeer::retrieveByPK($this->OrderId);

					define('_VALID_RBS', 1 );
					define('_VALID_CYB_CRYPT', 1);


					/**
					* Submit the order
					*********************************************************************************/

					$PaymentType						= "INVOICE";

					$Customer							= CustomerPeer::retrieveByPK($this->Order->getCustomerId());

					/*` Clear the list of pending payments
					`````````````````````````````````````````````````````````````````````````````````*/
					$Input								= new AddPayment();
					$Input->Username					= "amms";
					$Input->Password					= "6gjknJKLSF*";
					$Input->ClientId					= CustomerPeer::GetClientByCustomer($this->Order->getCustomerId());
					$Input->CustomerId					= $this->Order->getCustomerId();
					$Input->UserId						= "4";
					$Input->OrderId						= $this->Order->getOrderId();

// error_log("calling ClearPayment...");
					$CAmmsPayment->ClearPayment($Input);
// error_log("ClearPayment returned.");
$temp = Us2OrderPeer::retrieveByPK($Input->OrderId);
// error_log("After ClearPayment: ".print_r($temp, true));



					// Calculate pricing for $this->Order.
					$Input								= new AddPayment();
					$Input->Username					= "amms";
					$Input->Password					= "6gjknJKLSF*";
					$Input->ClientId					= CustomerPeer::GetClientByCustomer($this->Order->getCustomerId());
					$Input->CustomerId					= $this->Order->getCustomerId();
					$Input->UserId						= "4";
					$Input->OrderId						= $this->OrderId;
// error_log("calling UpdateOrder 4...");
					try { $Response = $CAmmsPayment->UpdateOrder($Input); } catch ( SoapFault $E ) {
						//echo print_r($E, true) . "<br />";
					}
// error_log("UpdateOrder 4 returned.");
$temp = Us2OrderPeer::retrieveByPK($Input->OrderId);
// error_log("After UpdateOrder 4: ".print_r($temp, true));





					$Payment							= new AddPayment();
					// $third_party_billing_id		= stripslashes($Input->ThirdPartyBillingId);
					// $stored_value_id 			= intval($Input->StoredValueId);
					// $is_wholesale_payment 		= $Input->WholesalePayment;

					$Payment->Username					= "amms";
					$Payment->Password					= "6gjknJKLSF*";
					$Payment->ClientId					= CustomerPeer::GetClientByCustomer($this->Order->getCustomerId());
					$Payment->CustomerId				= $this->Order->getCustomerId();
					$Payment->UserId					= "4";
					$Payment->OrderId					= $this->Order->getOrderId();
					$Payment->PaymentType				= "INVOICE";
					$Payment->WholesalePayment			= 0;		// not a payment amount! true for wholesale; false for retail

// error_log("calling AddPayment...");
// error_log("OrderId: {$Payment->OrderId}, PaymentAmount: {$Payment->PaymentAmount}, WholesalePayment: {$Payment->WholesalePayment}");
					try { $Response = $CAmmsPayment->AddPayment($Payment); } catch ( SoapFault $E ) {
						//echo print_r($E, true) . "<br />";
					}
// error_log("AddPayment returned.");


					/*` Try processing the payment based on the payment method selected
					``````````````````````````````````````````````````````````````````````````````````````*/

					$Order								= new ProcessPayment();
					$Order->Username					= "amms";
					$Order->Password					= "6gjknJKLSF*";
					$Order->ClientId					= CustomerPeer::GetClientByCustomer($this->Order->getCustomerId());
					$Order->CustomerId					= $this->Order->getCustomerId();
					$Order->UserId						= "4";
					$Order->OrderId						= $this->Order->getOrderId();

// error_log("calling ProcessPayment...");
					try { $Response = $CAmmsPayment->ProcessPayment($Order); } catch ( SoapFault $E ) {
						#$echo print_r($E, true) . "<br />";
					}
// error_log("ProcessPayment returned: ".print_r($Response, true));

					if ($Response->Code == 'ERROR') {
// error_log("Error");
						// var_dump($Response);exit;
						// print_r($Response,true);
						// $this->ErrorMessage = print_r($Response,true);
						if ($Response->ErrorCode == 1030) {
							$ErrorMessage = 'You do not have enough store credit to pay for this order. Try adding
							a credit card to your payment to pay the remaining balance';
						}

						if (!$ErrorMessage) {
							$ErrorMessage = 'Error: There is an error while processing your order.<br>Please double check the account information you entered and try again.';
						}
					} else {
// error_log("Success");
						$this->Order->setIsCartYn ('N');
						$this->Order->setOrderCreatedDate (date('Y-m-d H:i:s'));
						$this->Order->save();

						$Date = $this->Order->getOrderCreatedDate();

						if ($Date && $Date != '0000-00-00 00:00:00') {
							/* Order is completed
							* Check to see if we need to send any notification to the admins
							***********************************************************************/
							$arrayOrderProductId = Us2OrderProductPeer::GetItemsInCart($this->Order->getOrderId());

							foreach ($arrayOrderProductId as $OrderProductId) {
								Us2OrderPeer::CreateNotificationMessage($OrderProductId);
							}

						} else {
							$ErrorMessage = 'Unable to process your payment. Please try again.';
						}
					}

				} catch (Exception $e) {
					$error = $e->getMessage();

					return $this->renderText(json_encode(array("success" => false, "error" => $error, "debug" => $debug)));
				}

				// NOTE: We intentionally omit the break statement here. We *want* to fall into CompletePayment.

			case "CompletePayment":
// error_log("CompletePayment");
				try {
					$Connection = Propel::getConnection();

					$OrderProductId = $this->getRequestParameter("OrderProductId", 0);
// error_log("OrderProductId: {$OrderProductId}");
					$debug = array();
					if (!empty($OrderProductId)) {
						// Move display of order product to Processing stage
						$Query	= "UPDATE us2_order_product_compliance SET "
								. "stage = 'Processing', "
								. "payment_yn = 'Y', "
								. "payment_by_user_id = '{$this->AccessControl->UserId}', "
								. "payment_date = NOW() "
								. "WHERE order_product_id = {$OrderProductId} "
								. "AND stage = 'Payment'";
						$debug[] = $Query;

						$Connection->executeQuery($Query);
					}

					return $this->renderText(json_encode(array("success" => true, "debug" => $debug)));
				} catch (Exception $e) {
					$error = $e->getMessage();

					return $this->renderText(json_encode(array("success" => false, "error" => $error, "debug" => $debug)));
				}
				break;

			case "LoadLastSevenServices":
				$customers = array();
				$radius = $_GET['radius'];

				$request = self::MarketEvalCustomersRequest("dms", "services", 7, $radius);

				foreach ($request as $evalId => $data) {
					$zips = array();
					$customers[$evalId]["RequestDate"] = date("D, M j", strtotime($data['RequestDate']));
					$customers[$evalId]["TotalPurchaseReady"]["Count"] = count($data['Customers']);
					foreach ($data['Customers'] as $id => $cusData) {
						++$zips[$cusData['zip']];
					}
					$customers[$evalId]["TotalPurchaseReady"]["ZipBreakdown"] = $zips;
					unset($zips);
				}
				unset($request);
				$request = self::MarketEvalCustomersRequest("dms","services",7,$radius,"samemakemarketshare");
				foreach($request as $eval => $data){
					$customers[$eval] = array_merge($customers[$eval],$data);
				}

				$request = self::MarketEvalCustomersRequest("dms","services",7,$radius,"samemakesnscount");
				foreach($request as $eval => $data){

					$customers[$eval]["SameMakeSnsCount"] = $data;
				}

				$response = json_encode($customers);
				return $this->renderText($response);

				break;

			case "CheckOrderProductMailingList":
				// Initialize data
				$data = array();
				$error = null;
				$debug = array();

				try {

					$OrderProductId = $this->getRequestParameter("OrderProductId", 0);
					if (!empty($OrderProductId)) {

						$Connection = Propel::getConnection();

						$Query	= "SELECT "
								. "us2_order_product.order_product_id AS order_product_id, "
								. "us2_order_product.total_quan AS total_quan, "
								. "us2_order_product.customer_id AS customer_id, "
								. "us2_order_product.product_id AS product_id, "
								. "us2_order_product.recipient_list_id AS recipient_list_id, "
								. "0 AS price, "
								. "us2_order_product_mailing_list.dms_count_net AS dms_count_net, "
								. "us2_order_product_mailing_list.conquest_count_net AS conquest_count_net "
								. "FROM us2_order_product "
								. "LEFT JOIN us2_order_product_mailing_list ON us2_order_product.order_product_id = us2_order_product_mailing_list.order_product_id AND us2_order_product.recipient_list_id = us2_order_product_mailing_list.pull_master_id "
								. "LEFT JOIN us2_product ON us2_order_product.product_id = us2_product.product_id "
								. "WHERE us2_order_product.order_product_id = {$OrderProductId}";

						$debug[]	= $QueryTotal;
						$Rs = $Connection->executeQuery($Query);

						while ($Rs->next()) {
							$row = $Rs->getRow();
							if (!empty($row['recipient_list_id'])) {

								// Get the associated list order product
								$ListOrderProduct	= $this->GetConquestListOrderProduct($OrderProductId);

								// Wholesale is selected only if the Wholesale variable exists and is not empty
								$Wholesale = !empty($this->Wholesale);

								// Get the price of the mail piece
								$MailPrice			= $this->GetPrice($row['customer_id'], $row['product_id'], $row['total_quan'], $Wholesale);
								// Get the price for the mailing list
								$ListPrice			= $this->GetPrice($row['customer_id'], $ListOrderProduct->getProductId(), $row['conquest_count_net'], $Wholesale);

								$price					= $MailPrice + $ListPrice;

								$response = array(
									"processed" => true,
									"list_size" => number_format($row['total_quan'], 0),
									"list_id" => $row['recipient_list_id'],
									"price" => number_format($price, 2)
								);

								return $this->renderText(json_encode($response));
							}
						}
					}

				} catch (Exception $e) {
					$error = $e->getMessage();
				}

				$response = array(
					"processed" => false,
					"list_size" => '0',
					"list_id" => 0,
					"price" => 0.00
				);

				return $this->renderText(json_encode($response));
				break;

			case "LoadLatestService":
				$customers = array();
				$radius = $_GET['radius'];

				$request = self::MarketEvalCustomersRequest("dms", "services", 1, $radius);

				foreach ($request as $evalId => $data) {
					$zips = array();
					$customers[$evalId]["RequestDate"] = date("D, M j Y", strtotime($data['RequestDate']));
					$customers[$evalId]["TotalPurchaseReady"]["Count"] = count($data['Customers']);
					foreach($data['Customers'] as $id => $cusData)
					{
						++$zips[$cusData['zip']];
					}
					$customers[$evalId]["TotalPurchaseReady"]["ZipBreakdown"] = $zips;
					unset($zips);
				}
				unset($request);
				$request = self::MarketEvalCustomersRequest("dms", "services", 1, $radius, "samemakemarketshare");

				foreach ($request as $eval => $data) {
					$customers[$eval] = array_merge($customers[$eval], $data);
				}

				$request = self::MarketEvalCustomersRequest("dms", "services", 1, $radius, "samemakesnscount");
				foreach ($request as $eval => $data) {

					$customers[$eval]["SameMakeSnsCount"] = $data;
				}

				$request = self::MarketEvalCustomersRequest("dms", "services", 1, $radius, "samemakerecentcustomerscount");
				foreach ($request as $eval => $data) {
					$customers[$eval]["RecentCustomers"] = $data;
				}

				$request = self::MarketEvalCustomersRequest("dms", "services", 1, $radius, "samemakeinactivecustomerscount");
				foreach ($request as $eval => $data) {
					$customers[$eval]["InactiveCustomers"] = $data;
				}

				$request = self::MarketEvalCustomersRequest("dms", "services", 1, $radius, "samemakelostcustomerscount");
				foreach ($request as $eval => $data) {
					$tmpData = $data;
					foreach ($data as $key => $value) {

						$tmpData["All"]["Total"] += $value["total"];
						$tmpData["All"]["SNS"] += $value["sns"];
						$tmpData["All"]["1-2"] += $value["1-2"];
						$tmpData["All"]["3-4"] += $value["3-4"];
						$tmpData["All"]["5gt"] += $value["5gt"];
					}
					$customers[$eval]["LostCustomers"] = $tmpData;
				}

				$response = json_encode($customers);
				return $this->renderText($response);

				break;

			case "LoadLatestSale":
				$customers = array();
				$radius = $_GET['radius'];

				$request = self::MarketEvalCustomersRequest("dms", "sales", 1, $radius);

				foreach ($request as $evalId => $data) {
					$zips = array();
					$customers[$evalId]["RequestDate"] = date("D, M j", strtotime($data['RequestDate']));
					$customers[$evalId]["TotalPurchaseReady"]["Count"] = count($data['Customers']);
					foreach ($data['Customers'] as $id => $cusData) {
						++$zips[$cusData['zip']];
					}
					$customers[$evalId]["TotalPurchaseReady"]["ZipBreakdown"] = $zips;
					unset($zips);
				}
				unset($request);
				$request = self::MarketEvalCustomersRequest("dms", "sales", 1, $radius, "samemakemarketshare");
				foreach ($request as $eval => $data) {
					$customers[$eval] = array_merge($customers[$eval], $data);
				}

				$request = self::MarketEvalCustomersRequest("dms", "sales", 1, $radius, "samemakesnscount");
				foreach ($request as $eval => $data) {

					$customers[$eval]["SameMakeSnsCount"] = $data;
				}

				$request = self::MarketEvalCustomersRequest("dms", "sales", 1, $radius, "samemakeequitybreakdowncount");
				foreach($request as $eval => $data){
					$customers[$eval]["Breakdown"] = $data;
				}
				$response = json_encode($customers);
				return $this->renderText($response);

				break;

			case "GetOrderProductNotesJSON":{
				$response = array();
				$od = $_GET['OrderProductId'];
				$conn = Propel::getConnection();
				$stmt = $conn->prepareStatement("SELECT `note` FROM `us2_order_product_note` WHERE `order_product_id` = {$od} ORDER BY `order_product_note_id` DESC");

				$result = $stmt->executeQuery();
				while ($result->next()) {
					$response[] = array("note" => $result->get("note"));
				}
				return $this->renderText(json_encode($response));
			}

			case "PostAutoCampaignAgreement":

				$result = false;
				$debug = array();

				$params = $this->getRequest()->getParameterHolder()->getAll();

				$date_fields = array('mail_date', 'sale_date');

				foreach ($date_fields as $date_field) {
					foreach ($params[$date_field] as $key => $value) {
						$params[$date_field][$key] = $this->ISO8601Date($value);
					}
				}

				$conn = Propel::getConnection();

				$Query		= "INSERT INTO us2_auto_campaign_agreement SET "
							. "client_id = '{$params['client_id']}', "
							. "customer_id = '{$params['customer_id']}', "
							. "user_id = '{$params['user_id']}', "
							. "order_product_id = '{$params['order_product_id']}', "
							. "client_name = '{$params['client_name']}', "
							. "client_contact = '{$params['client_contact']}', "
							. "dealership_name = '{$params['dealership_name']}', "
							. "dealership_contact = '{$params['dealership_contact']}', "
							. "dealership_phone = '{$params['dealership_phone']}', "
							. "dealership_address = '{$params['dealership_address']}', "
							. "dealership_city = '{$params['dealership_city']}', "
							. "dealership_state = '{$params['dealership_state']}', "
							. "dealership_zip = '{$params['dealership_zip']}', "
							. "total_qty = '{$params['total_qty']}', "
							. "mail_drops = '{$params['mail_drops']}', "
							. "samples = '{$params['samples']}', "
							. "mail_date_1 = '{$params['mail_date'][0]}', "
							. "quantity_1 = '{$params['quantity'][0]}', "
							. "sale_date_1 = '{$params['sale_date'][0]}', "
							. "mail_date_2 = '{$params['mail_date'][1]}', "
							. "quantity_2 = '{$params['quantity'][1]}', "
							. "sale_date_2 = '{$params['sale_date'][1]}', "
							. "mail_date_3 = '{$params['mail_date'][2]}', "
							. "quantity_3 = '{$params['quantity'][2]}', "
							. "sale_date_3 = '{$params['sale_date'][2]}', "
							. "mail_date_4 = '{$params['mail_date'][3]}', "
							. "quantity_4 = '{$params['quantity'][3]}', "
							. "sale_date_4 = '{$params['sale_date'][3]}', "
							. "campaign_name = '{$params['campaign_name']}', "
							. "paper_size = '{$params['paper_size']}', "
							. "print_color = '{$params['print_color']}', "
							. "bleeds_yn = '{$params['bleeds']}', "
							. "paper_description = '{$params['paper_description']}', "
							. "paper_select = '{$params['paper_select']}', "
							. "paper_type = '{$params['paper_type']}', "
							. "paper_weight = '{$params['paper_weight']}', "
							. "envelope_size = '{$params['envelope_size']}', "
							. "envelope_type = '{$params['envelope_type']}', "
							. "envelope_color = '{$params['envelope_color']}', "
							. "envelope_description = '{$params['envelope_description']}', "
							. "insert_1 = '{$params['insert'][0]}', "
							. "insert_size_1 = '{$params['insert_size'][0]}', "
							. "insert_color_1 = '{$params['insert_color'][0]}', "
							. "insert_bleeds_1_yn = '{$params['insert_bleeds'][0]}', "
							. "insert_2 = '{$params['insert'][1]}', "
							. "insert_size_2 = '{$params['insert_size'][1]}', "
							. "insert_color_2 = '{$params['insert_color'][1]}', "
							. "insert_bleeds_2_yn = '{$params['insert_bleeds'][1]}', "
							. "special_instructions = '{$params['special_instructions']}', "
							. "add_on_1 = '{$params['add_on'][0]}', "
							. "add_on_2 = '{$params['add_on'][1]}', "
							. "add_on_3 = '{$params['add_on'][2]}', "
							. "add_on_attach_1 = '{$params['add_on_attach'][0]}', "
							. "add_on_attach_2 = '{$params['add_on_attach'][1]}', "
							. "add_on_attach_3 = '{$params['add_on_attach'][2]}', "
							. "postage_class = '{$params['postage_class']}', "
							. "postage_type = '{$params['postage_type']}', "
							. "postage_instructions = '{$postage_instructions}', "
							. "data_select = '{$params['data_select']}', "
							. "data_instructions = '{$params['data_instructions']}', "
							. "list_criteria = '{$params['list_criteria']}', "
							. "client_authorized_name = '{$params['client_authorized_name']}', "
							. "client_authorized_signature = '{$params['client_authorized_signature']}', "
							. "agreement_date = NOW() "
							. "ON DUPLICATE KEY UPDATE "
							. "dealership_name = '{$params['dealership_name']}', "
							. "dealership_contact = '{$params['dealership_contact']}', "
							. "dealership_phone = '{$params['dealership_phone']}', "
							. "dealership_address = '{$params['dealership_address']}', "
							. "dealership_city = '{$params['dealership_city']}', "
							. "dealership_state = '{$params['dealership_state']}', "
							. "dealership_zip = '{$params['dealership_zip']}', "
							. "total_qty = '{$params['total_qty']}', "
							. "mail_drops = '{$params['mail_drops']}', "
							. "samples = '{$params['samples']}', "
							. "mail_date_1 = '{$params['mail_date'][0]}', "
							. "quantity_1 = '{$params['quantity'][0]}', "
							. "sale_date_1 = '{$params['sale_date'][0]}', "
							. "mail_date_2 = '{$params['mail_date'][1]}', "
							. "quantity_2 = '{$params['quantity'][1]}', "
							. "sale_date_2 = '{$params['sale_date'][1]}', "
							. "mail_date_3 = '{$params['mail_date'][2]}', "
							. "quantity_3 = '{$params['quantity'][2]}', "
							. "sale_date_3 = '{$params['sale_date'][2]}', "
							. "mail_date_4 = '{$params['mail_date'][3]}', "
							. "quantity_4 = '{$params['quantity'][3]}', "
							. "sale_date_4 = '{$params['sale_date'][3]}', "
							. "campaign_name = '{$params['campaign_name']}', "
							. "paper_size = '{$params['paper_size']}', "
							. "print_color = '{$params['print_color']}', "
							. "bleeds_yn = '{$params['bleeds']}', "
							. "paper_description = '{$params['paper_description']}', "
							. "paper_select = '{$params['paper_select']}', "
							. "paper_type = '{$params['paper_type']}', "
							. "paper_weight = '{$params['paper_weight']}', "
							. "envelope_size = '{$params['envelope_size']}', "
							. "envelope_type = '{$params['envelope_type']}', "
							. "envelope_color = '{$params['envelope_color']}', "
							. "envelope_description = '{$params['envelope_description']}', "
							. "insert_1 = '{$params['insert'][0]}', "
							. "insert_size_1 = '{$params['insert_size'][0]}', "
							. "insert_color_1 = '{$params['insert_color'][0]}', "
							. "insert_bleeds_1_yn = '{$params['insert_bleeds'][0]}', "
							. "insert_2 = '{$params['insert'][1]}', "
							. "insert_size_2 = '{$params['insert_size'][1]}', "
							. "insert_color_2 = '{$params['insert_color'][1]}', "
							. "insert_bleeds_2_yn = '{$params['insert_bleeds'][1]}', "
							. "special_instructions = '{$params['special_instructions']}', "
							. "add_on_1 = '{$params['add_on'][0]}', "
							. "add_on_2 = '{$params['add_on'][1]}', "
							. "add_on_3 = '{$params['add_on'][2]}', "
							. "add_on_attach_1 = '{$params['add_on_attach'][0]}', "
							. "add_on_attach_2 = '{$params['add_on_attach'][1]}', "
							. "add_on_attach_3 = '{$params['add_on_attach'][2]}', "
							. "postage_class = '{$params['postage_class']}', "
							. "postage_type = '{$params['postage_type']}', "
							. "postage_instructions = '{$postage_instructions}', "
							. "data_select = '{$params['data_select']}', "
							. "data_instructions = '{$params['data_instructions']}', "
							. "list_criteria = '{$params['list_criteria']}', "
							. "client_authorized_name = '{$params['client_authorized_name']}', "
							. "client_authorized_signature = '{$params['client_authorized_signature']}', "
							. "agreement_date = NOW()";

						$debug[] = $Query;

						$result = $conn->executeUpdate($Query);

						return $this->renderText(json_encode(array("success" => $result, "params" => $params, "debug" => $debug)));

			case "PostUpdateAgreementInternal":

				$result = false;
				$debug = array();

				$params = $this->getRequest()->getParameterHolder()->getAll();
				$conn = Propel::getConnection();

				$mail_campaign_yn	= ((@$params['mail_campaign_yn'] == 'Y') ? 'Y' : 'N');
				$print_campaign_yn	= ((@$params['print_campaign_yn'] == 'Y') ? 'Y' : 'N');

				$Query		= "UPDATE us2_auto_campaign_agreement SET "
							. "sales_rep = '{$params['sales_rep']}', "
							. "account_mgr = '{$params['account_mgr']}', "
							. "mail_campaign_yn = '{$mail_campaign_yn}', "
							. "print_campaign_yn = '{$print_campaign_yn}', "
							. "updated_by_user_id = '{$params['user_id']}', "
							. "updated_date = NOW() "
							. "where order_product_id = '{$params['order_product_id']}'";

				$debug[] = $Query;

				$result = $conn->executeUpdate($Query);

				return $this->renderText(json_encode(array("success" => $result, "params" => $params, "debug" => $debug)));

				break;

			case "GetWaitingApprovalCustomerUploads":
				$result = self::GetCustomerUploadsTableDataByStatus(1);
				return $this->renderText(json_encode($result));
			case "GetCompletedCustomerUploads":
				$result = self::GetCustomerUploadsTableDataByStatus(99);
				return $this->renderText(json_encode($result));
			case "GetCanceledCustomerUploads":
				$result = self::GetCustomerUploadsTableDataByStatus(6);
				return $this->renderText(json_encode($result));
			case "GetCustomerUploads":
				$result = self::GetCustomerUploadsTableDataByStatus("all");
				return $this->renderText(json_encode($result));
			case "ApproveCustomerUpload":
				$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$q = "UPDATE `us2_customer_upload` SET `us2_customer_upload_stage_id` =  3, `us2_customer_upload_approved_date` = NOW(), `us2_customer_upload_approved_yn`='Y' WHERE `us2_customer_upload_id` = :id";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":id",$_POST['upload_id'],PDO::PARAM_INT);
				try{
					$stmt->execute();
				} catch (Exception $ex) {
					error_log($ex->getMessage());
				}

				return $this->renderText();
			case "CancelCustomerUpload":
				$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$q = "UPDATE `us2_customer_upload` SET `us2_customer_upload_stage_id` = 6, `us2_customer_upload_user_id` = {$this->CurrentUserId} WHERE `us2_customer_upload_id` = :id";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":id",$_POST['upload_id'],PDO::PARAM_INT);
				try{
					$stmt->execute();
				} catch (Exception $ex) {
					error_log($ex->getMessage());
				}

				return $this->renderText();

			case "GetCategoriesJSON":
				$arrayCategories		= Us2ProductGroupPeer::GetAllCategoriesByStoreInDisplayOrder(STORE_ID, $ViewAll=true);
				$jsonTreeCode			= $this->createJsonTree($arrayCategories);

				return $this->renderText($jsonTreeCode);

			case "GetProductCategoriesJSON":
				$ProductId					= $this->getRequestParameter("ProductId", 0);
				$arrayCategories			= Us2ProductGroupPeer::GetAllCategoriesByStoreInDisplayOrder(STORE_ID, $ViewAll=true);
				$this->arrayProductGroup	= Us2ProductGroupMembershipPeer::GetArrayProductGroup($ProductId);
				$jsonTreeCode				= $this->createJsonMembershipTree($arrayCategories);

				return $this->renderText($jsonTreeCode);

			case "StoreFancyProduct":
				// get product ID
				$id = $this->getRequestParameter('id', 0);
				// get product views
				$views = $this->getRequestParameter('views', '');
				// insert views into database
				$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				if (empty($id)) {
					$stmt = $conn->prepare("INSERT INTO fancy_product SET views=:views");
					// $stmt = $conn->prepare("INSERT INTO fancy_product SET client_id=:client_id, customer_id=:customer_id, name=:name, views=:views");
					// $stmt->bindValue(":client_id", $client_id, PDO::PARAM_INT);
					// $stmt->bindValue(":customer_id", $customer_id, PDO::PARAM_INT);
					// $stmt->bindValue(":name", $name, PDO::PARAM_STR);
					$stmt->bindValue(":views", $views, PDO::PARAM_STR);
				} else {
					$stmt = $conn->prepare("UPDATE fancy_product SET views=:views WHERE fancy_product_id=:id");
					// $stmt = $conn->prepare("UPDATE fancy_product SET client_id=:client_id, customer_id=:customer_id, name=:name, views=:views WHERE fancy_product_id=:id");
					// $stmt->bindValue(":client_id", $client_id, PDO::PARAM_INT);
					// $stmt->bindValue(":customer_id", $customer_id, PDO::PARAM_INT);
					// $stmt->bindValue(":name", $name, PDO::PARAM_STR);
					$stmt->bindValue(":views", $views, PDO::PARAM_STR);
					$stmt->bindValue(":id", $id, PDO::PARAM_INT);
				}
				try {
					$stmt->execute();
					if (empty($id)) {
						$id		= $conn->lastInsertId();
					}
				} catch (Exception $ex) {
					error_log($ex->getMessage());
					$id		= 0;
				}

				return $this->renderText(json_encode(array("id" => $id)));

			case "LoadFancyProduct":
				// get product ID
				$id = $this->getRequestParameter('id', 0);
				// select product by ID
				$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$q = "SELECT views FROM fancy_product WHERE fancy_product_id=:id";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":id", $id, PDO::PARAM_INT);

				try {
					$stmt->execute();
				} catch(Exception $ex) {
					error_log($ex->getMessage());
					return $this->renderText(json_encode(array("error"=>$ex->getMessage())));
				}

				while (($row = $stmt->fetch(PDO::FETCH_ASSOC))!== false) {
					// It's already JSON encoded so no need to do it again
					return $this->renderText($row["views"]);
				}

			case "StoreFancyDesign":
				// get product views
				$views = $this->getRequestParameter('views', '');
				// insert views into database
				$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				if (empty($this->id)) {
					$q = "INSERT INTO fancy_design SET client_id=:client_id, customer_id=:customer_id, name=:name, views=:views";
					$stmt = $conn->prepare($q);
					$stmt->bindValue(":client_id", $client_id, PDO::PARAM_INT);
					$stmt->bindValue(":customer_id", $customer_id, PDO::PARAM_INT);
					$stmt->bindValue(":name", $name, PDO::PARAM_STR);
					$stmt->bindValue(":views", $views, PDO::PARAM_STR);
				} else {
					$q = "UPDATE fancy_product SET client_id=:client_id, customer_id=:customer_id, name=:name, views=:views WHERE id=:id";
					$stmt = $conn->prepare($q);
					$stmt->bindValue(":client_id", $client_id, PDO::PARAM_INT);
					$stmt->bindValue(":customer_id", $customer_id, PDO::PARAM_INT);
					$stmt->bindValue(":name", $name, PDO::PARAM_STR);
					$stmt->bindValue(":views", $views, PDO::PARAM_STR);
					$stmt->bindValue(":id", $this->id, PDO::PARAM_INT);
				}
				try {
					$stmt->execute();
					$id		= $conn->lastInsertId();
				} catch (Exception $ex) {
					error_log($ex->getMessage());
					$id		= 0;
				}

				return $this->renderText($id);

			case "LoadFancyDesign":
				// get product ID
				$id = $this->getRequestParameter('id', 0);
				// select product by ID
				$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$q = "SELECT * FROM fancy_design WHERE fancy_design_id=:id";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":id", $id, PDO::PARAM_INT);

				try {
					$stmt->execute();
				} catch(Exception $ex) {
					error_log($ex->getMessage());
					return $this->renderText(json_encode(array("error"=>$ex->getMessage())));
				}

				while (($row = $stmt->fetch(PDO::FETCH_ASSOC))!== false) {
					// It's already JSON encoded so no need to do it again
					return $this->renderText($row["views"]);
				}

			default:

		} // switch

	}

	private function createJsonMembershipTree ($arrayCategories, $parentId=0, $root=true)
	{
		$arrayNode = array();

		foreach ($arrayCategories as $Id => $Group) {
			$branch = $this->createJsonMembershipTree($Group['categories'], $Id, false);

			if (!empty($branch)) {
				$node = array(
					"id"				=> $Id,
					"label"				=> addslashes($Group['name']),
					"inode"				=> true,
					"open"				=> false,
					"checkbox"			=> true,
					"radio"				=> false,
					"branch"			=> $branch,
					"checked"			=> in_array($Id, $this->arrayProductGroup)
				);
			} else {
				$node = array(
					"id"				=> $Id,
					"label"				=> addslashes($Group['name']),
					"inode"				=> false,
					"checkbox"			=> true,
					"radio"				=> false,
					"checked"			=> in_array($Id, $this->arrayProductGroup)
				);
			}

			$arrayNode[] = $node;
		}

		if ($root) {
			return json_encode($arrayNode);
		} else {
			return $arrayNode;
		}
	}

	private function createJsonTree($arrayCategories, $parentId=0, $root=true)
	{
		$arrayNode = array();

		foreach ($arrayCategories as $Id => $Group) {
			$node = array(
				"id"				=> $Id,
				"label"				=> addslashes($Group['name']),
				"inode"				=> true,
				"open"				=> false,
				"branch"			=> $this->createJsonTree($Group['categories'], $Id, false),
				"clickType"			=> "VIEW"
			);
			$arrayNode[] = $node;
		}

		$arrayNode[]		= array(
			"id"				=> 0,
			"label"				=> "Add a category here",
			"inode"				=> false,
			"parentId"			=> $parentId,
			"clickType"			=> "ADD"
		);

		if ($root) {
			return json_encode($arrayNode);
		} else {
			return $arrayNode;
		}
	}

	private function GetCustomerUploadsTableDataByStatus($stat = 1){
				$this->GetDataTableParameters();

				$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				//$QueryData = "SELECT * FROM ( {$Query} ) AS a WHERE 1{$this->searchClause}{$this->orderClause}{$this->limitClause}";
				if($stat == "all"){
					$idFilter = "1";
				}
				else{

					$idFilter = "`us2_customer_upload_stage_id` = $stat";
				}
				$q = "SELECT `us2_customer_upload`.*,`customer`.`name` AS `customer_name`, "
						. "`us2_file_map`.`us2_file_map_name`"
						. "FROM `us2_customer_upload` "
						. "LEFT JOIN `customer` ON `us2_customer_upload`.`customer_id` = `customer`.`customer_id`"
						. "LEFT JOIN `us2_file_map` ON `us2_customer_upload`.`us2_file_map_id` = `us2_file_map`.`us2_file_map_id` "
						. "WHERE {$idFilter} {$this->searchClause}{$this->orderClause}{$this->limitClause}";
				$stmt	= $conn->prepare($q);
				try{
					$stmt->execute();
				}catch(Exception $ex){
					error_log($ex->getMessage());
					error_log($q);
					error_log(json_encode($_GET));
					return $this->renderText(json_encode(array("error"=>$ex->getMessage())));
				}
				$data = array();
				$currentHost = $_SERVER['SERVER_NAME'];
				while(($row = $stmt->fetch(PDO::FETCH_ASSOC))!== false){
					$file = pathinfo($row['us2_customer_upload_file_location']);
					$file['extension'] = strtolower($file['extension']);


					switch($file['extension']){
						case "csv":
						case "txt":
							$fa = "fa-file-text-o";
							break;
						default:
							$fa = "fa-file-o";
							break;
					}
					$file = "<a href='/?token=".Convert::EncodeURL("Page=DownloadCustomerUploadFile")."&file_id={$row['us2_customer_upload_id']}' style='text-align:center'><span class='fa $fa fa-2x'></span><br/>{$file['filename']}</a>";
					// if(
					// ($currentHost == "admin.printhd.us" && strpos($file['dirname'],"/web3/data") !== false)
					// ||
					// ($currentHost != "admin.printhd.us" && strpos($file['dirname'], "/web12/data") !== false)
					// ){
					//     $file = "<a href='/consumer/DownloadCustomerUploadFile?file_id={$row['us2_customer_upload_id']}' style='text-align:center'><span class='fa $fa fa-2x'></span><br/>{$file['filename']}</a>";
					// }
					// else{
					//     $file = "<span class='fa $fa fa-2x'></span><br/>{$file['filename']}";
					// }
					switch($stat){
						case 1:
							$approve = "<button class='btn-approve active-button' data-approve-id='{$row['us2_customer_upload_id']}'>Approve</button>";
							$cancel = "<button class='btn-cancel dangerous-button' data-cancel-id='{$row['us2_customer_upload_id']}'>Cancel</button>";
							$data[] = array(
								$row['customer_name'],
								$file,
								$row['us2_customer_upload_type'],
								$row['us2_customer_upload_import_type'],
								$row['us2_file_map_name'],
								$row['us2_row_count'],
								$row['us2_customer_upload_date'],
								$approve,
								$cancel
							);
							break;
						case 3:
						case 6:
						case 99:
						case "all":
							#Doing some special formating for the stage id
							$stage = self::GetImportsStageHtml($row['us2_customer_upload_stage_id']);
							$row['us2_row_count'] = $row['us2_row_count'] > 0?$row['us2_row_count']:0;
							$row['us2_initial_date']	= $row['us2_initial_date'] == null ? " ":$row['us2_initial_date'];
							$row['us2_ending_date']	= $row['us2_ending_date'] == null ? " ":$row['us2_ending_date'];
							$data[] = array(
								$row['customer_name'],
								$file,
								$row['us2_customer_upload_type'],
								$row['us2_customer_upload_import_type'],
								$row['us2_file_map_name'],
								$stage,
								$row['us2_row_count'],
								$row['us2_initial_date'],
								$row['us2_ending_date'],
								$row['us2_customer_upload_date']
							);
							break;

					}

				}
				$q = "SELECT COUNT(*) AS `total`, "
					. "(SELECT COUNT(*) "
					. "FROM `us2_customer_upload` "
					. "LEFT JOIN `customer` ON `us2_customer_upload`.`customer_id` = `customer`.`customer_id`"
					. "LEFT JOIN `us2_file_map` ON `us2_customer_upload`.`us2_file_map_id` = `us2_file_map`.`us2_file_map_id` "
					. "WHERE $idFilter {$this->searchClause}) as `filtered_total` "
					. "FROM `us2_customer_upload` "
					. "LEFT JOIN `customer` ON `us2_customer_upload`.`customer_id` = `customer`.`customer_id`"
					. "LEFT JOIN `us2_file_map` ON `us2_customer_upload`.`us2_file_map_id` = `us2_file_map`.`us2_file_map_id` "
					. "WHERE $idFilter";
				$stmt = $conn->prepare($q);

				try{
					$stmt->execute();
				} catch (Exception $ex) {
					error_log($ex->getMessage());
					error_log($q);
					return $this->renderText(json_encode(array("error"=>$ex->getMessage())));
				}
				while(($row = $stmt->fetch(PDO::FETCH_ASSOC))!== false){
					$RecordsTotal = $row['total'];
					$RecordsFiltered = $row['filtered_total'];
				}


				$result = array(
					"draw" => $this->draw,
					"recordsTotal" => $RecordsTotal,
					"recordsFiltered" => $RecordsFiltered,
					"data" => $data
				);

				return $result;
	}
	private function GetImportsStageHtml($stage){
		#9 steps to complete. .11 each step;

		$completion = .11;
		$barcolorclass = "progress-bar-info";
		$message = "";
		switch (intval($stage)){
			case 0: #Waiting for file creation
				$message = "Creating";
				break;
			case 1: #Waiting Approval
				$completion *= 2;
				$message = "Approving";
				break;
			case 2: #Approval Complete
				$completion *= 3;
				$message = "Approved";
				break;
			case 3: #Transfering File
				$completion *= 4;
				$message = "Transfering";
				break;
			case 4: #Failed Creating File
				$barcolorclass = "progress-bar-danger";
				$message = "Creating";
				break;
			case 5: #Failed File Trander
				$completion *= 4;
				$barcolorclass = "progress-bar-danger";
				$message = "Transfering";
				break;
			case 6: #Canceled
				$completion *= 3;
				$barcolorclass = "progress-bar-warning";
				$message = "Canceled";
				break;
			case 7: #Importing
				$completion *= 5;
				$message = "Importing";
				break;
			case 8: #Verifiying Postal Address
				$completion *= 6;
				$message = "NCOA";
				break;
			case 9: #Waiting Mail Match
				$completion = (.11 * 7);
				$message = "Mail Matching";
				break;
			case 10: #Mail Matching
				$completion = (.11 * 8);
				$message = "Matching";
				break;
			case 99: #Complete
				$barcolorclass = "progress-bar-success";
				$message = "Complete";
				$completion = 1;
				break;
		}
		$completion *= 100;
		$html = "<div class='progress' style='margin-bottom:0;'>"
				. "<div class='progress-bar {$barcolorclass}' role='progressbar' aria-valuenow='{$completion}' aria-valuemin='0' aria-valuemax='100' style='width:{$completion}%'>"
				. "{$message}"
				. "</div>"
				. "</div>";
		return $html;
	}
	private function GetPrice($CustomerId, $ProductId, $Quantity, $Wholesale=false) {
		ob_start();

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

		if (empty($this->CAmmsPricing)) {
			$this->CAmmsPricing = new AmmsPricing_Cache(86400);
		}

		$Input					= new PriceProduct();
		$Input->Username		= 'amms';
		$Input->Password		= '6gjknJKLSF*';
		$Input->ClientId		= CLIENT_ID;
		$Input->CustomerId		= $CustomerId;
		$Input->ProductId		= $ProductId;
		$Input->Quan			= $Quantity;
		$Input->PriceDate		= ''; // defaults to today
		$Input->CouponCode		= '';
		$Input->WholesaleYn		= $Wholesale ? 'Y' : 'N';

		$Response				= $this->CAmmsPricing->PriceProduct($Input);
		$Price					= $Quantity * $Response->UnitPrice;

		ob_end_clean();

		return $Price;
	}

	private function GetConquestListOrderProduct($OrderProductId) {
		// See if we already have a mailing list item
		$C1 = new Criteria();
		$C1->addAnd(Us2OrderProductPeer::PARENT_US2_ORDER_PRODUCT_ID, $OrderProductId);
		$C1->addAnd(Us2OrderProductPeer::ORDER_HANDLING_STATUS_ID, 9, Criteria::LESS_THAN);
		$arrayListOrderProduct = Us2OrderProductPeer::doSelect($C1);

		$Us2OrderProduct = Us2OrderProductPeer::retrieveByPk($OrderProductId);

		// If we don't have a mailing list item
		if (empty($arrayListOrderProduct)) {
			// Get the correct mailing list item to use
			$C2 = new Criteria();
			$C2->addAnd(Us2ProductPeer::STORE_ID, STORE_ID);
			$C2->addAnd(Us2ProductPeer::PRODUCT_TYPE_ID, 4);			// List
			$C2->addAnd(Us2ProductPeer::NAME, "Conquest%", Criteria::LIKE);
			$C2->addAnd(Us2ProductPeer::ACTIVE_YN, 'Y');
			$C2->addAnd(Us2ProductPeer::STATUS_ID, 2);
			$C2->addDescendingOrderByColumn(Us2ProductPeer::PRODUCT_ID);
			$arrayListProduct = Us2ProductPeer::doSelect($C2);

			if (!empty($arrayListProduct)) {
				// Get the most recent one
				$ListProduct = reset($arrayListProduct);

				$ListOrderProduct = new Us2OrderProduct();
				$ListOrderProduct->setProductId($ListProduct->getProductId());
				$ListOrderProduct->setOrderId($Us2OrderProduct->getOrderId());
				$ListOrderProduct->setCustomerId($Us2OrderProduct->getCustomerId());
				$ListOrderProduct->setParentUs2OrderProductId($OrderProductId);
				$ListOrderProduct->save();
			} else {
				$ListOrderProduct = false;
			}
		} else {
			$ListOrderProduct = reset($arrayListOrderProduct);
		}

		return $ListOrderProduct;
	}



	/**
	 *
	 * @param string $marketType
	 * @param string $filterType
	 * @param int $limit
	 * @param int $radius
	 * @param string $get
	 * @return array Customer or MarketShare Object
	 */
	private function MarketEvalCustomersRequest($marketType,$filterType,$limit,$radius,$get='') {
		$url = "http://marketeval.ammscore.com/customers";
		if(!empty($get)){
			$url .= "/{$get}";
		}
		$this->customerID = intval($this->CurrentCustomerId);
		$this->clientID = intval(CustomerPeer::GetClientByCustomer($this->customerID));
		$query = array(
			"customer_id" => $this->clientID,
			"mailer_id" => $this->customerID,
			"market_type" => $marketType,
			"filter_type" => $filterType,
			"limit" => $limit,
			"radius" => $radius
		);
		$url .= "?" . http_build_query($query, '', '&');
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
		curl_setopt($ch, CURLOPT_TIMEOUT, 300);
		curl_setopt($ch, CURLOPT_ENCODING, "gzip");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$response = curl_exec($ch);
		curl_close($ch);
		$response = json_decode($response,true);
		return $response;
	}

	private function MarketEvalSettingRequest($path="", $extra=array(),$method="get"){
		$url = "http://marketeval.ammscore.com/Snapshots";
		if(!empty($path)){
			$url .= "/{$path}";
		}
		$this->customerID = intval($this->CurrentCustomerId);
		$this->clientID = intval(CustomerPeer::GetClientByCustomer($this->customerID));

		$query = array("customer_id" => $this->clientID, "mailer_id"=>$this->customerID);
		$query = array_merge($query,$extra);
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
		curl_setopt($ch, CURLOPT_TIMEOUT, 300);
		curl_setopt($ch, CURLOPT_ENCODING, "gzip");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		if($method == "post"){
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
			curl_setopt($ch, CURLOPT_HEADER, FALSE);
			curl_setopt($ch, CURLOPT_POST,count($query));
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query,'','&'));
		}
		elseif($method == "get"){
			$url .= "?" . http_build_query($query, '', '&');
		}
		 curl_setopt($ch, CURLOPT_URL, $url);
		$response = curl_exec($ch);
		curl_close($ch);
		$response = json_decode($response,true);
		return $response;
	}


	/**
	 * Extracts parameters and builds the search, order, and limit clauses for a datatables request.
	 */
	private function GetDataTableParameters()
	{
		// Get all parameters
		$draw			= intval($this->getRequestParameter('draw'));
		$columns		= $this->getRequestParameter('columns');
		$order			= $this->getRequestParameter('order');
		$start			= intval($this->getRequestParameter('start', -1));
		$length			= intval($this->getRequestParameter('length', -1));
		$search			= $this->getRequestParameter('search');

		// Get searchable columns
		$arrayColumnName	= array();
		$arraySearchable	= array();
		foreach ($columns as $column) {
			$arrayColumnName[] = $column['name'];
			if ($column['searchable'] == 'true') {
				$arraySearchable[] = addslashes($column['name']);
			}
		}

		// Get search clause
		$searches			= array();
		if (!empty($search['value'])) {
			$searchValue = addslashes($search['value']);

			if ($search['regex']) {
				$searchVerb = 'REGEXP';
			} else {
				$searchVerb = 'LIKE';
			}

			foreach ($arraySearchable as $column) {
				$searches[] = "{$column} {$searchVerb} '{$searchValue}'";
			}
		}


		if (!empty($searches)) {
			$this->searchClause = ' AND ( ' . implode(' OR ', $searches) . ' )';
		} else {
			$this->searchClause = '';
		}


		// Get order clause
		$orders = array();
		foreach ($order as $order_by) {
			$orders[] = $arrayColumnName[$order_by['column']] . ' ' . addslashes($order_by['dir']);
		}
		if (!empty($orders)) {
			$this->orderClause = ' ORDER BY ' . implode(', ', $orders);
		} else {
			$this->orderClause = '';
		}


		// Get limit clause
		if ($start >= 0 && $length>= 0) {
			$this->limitClause = " LIMIT {$start}, {$length}";
		} elseif ($length >= 0) {
			$this->limitClause = " LIMIT {$length}";
		} else {
			$this->limitClause = '';
		}


		$this->draw = $draw;
	}


	/**
	* Private Function:
	*********************************************************************************/
	private function executeRemoveRateCard()
	{
		$Us2RateCard = Us2RateCardPeer::retrieveByPk($this->RateCardId);

		if($Us2RateCard)
		{
			$Us2RateCard->setActiveYn('N');
			$Us2RateCard->save();
		}

		header("Location: ". $_SERVER['HTTP_REFERER']); exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeSaveCasListOrder()
	{
		$this->CheckAuthentication();
		$this->setTemplate('SaveCasListOrder');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeReloadOrderProductList()
	{
		$this->setTemplate('ReloadOrderProductList');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeSaveProductMailingOption()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');
		$this->setTemplate('SaveProductMailingOption');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeViewCompleteOrderDetail()
	{
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));

		$this->DisplayCEClientSelector = true;

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Order Summary" );
		$this->setTemplate('ViewCompleteOrderDetail');
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeUploadCsvList()
	{
		$this->CheckAuthentication();
		$this->setTemplate('UploadCsvList');
		$this->setLayout(false);

		$this->isAdmin = $this->AccessControl->hasGroup("ADMIN");

		if ($this->isAdmin) {
			$this->customerID = intval($this->CurrentCustomerId);
			$this->clientID = intval(CustomerPeer::GetClientByCustomer($this->customerID));

			$ch = new CyberHackney();
			$this->clients = $ch->get("Customers");
			$this->customers = $ch->get("Mailers", array("version" => "1.01", "customer_id" => $this->clientID));
			$this->customers = $this->customers["results"];
		}

		return '_Success';
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeUploadFile()
	{
		$this->CheckAuthentication();
		$this->setTemplate('UploadFile');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeDownloadRecipientList()
	{
		$this->CheckAuthentication();
		$this->setTemplate('DownloadRecipientList');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	 * Private Function:
	 ********************************************************************************/
	private function executeEmailManager()
	{
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));

		$this->DisplayCEClientSelector = true;

		$data	= $this->getRequestParameter('token');
		$data	= base64_decode($data);
		parse_str($data,$data);

		$fileInfo		= $this->getRequestParameter('fileInfo', null);
		$customerIDs	= $this->getRequestParameter('emailCustomerId', array());

		if (isset($customerIDs) && !empty($customerIDs))
		{
			$c				= new Criteria();
			$c->add(CustomerPeer::CUSTOMER_ID,$customerIDs,Criteria::IN);
			$c->addJoin(CustomerPeer::CUSTOMER_ID,  SfGuardUserProfilePeer::CUSTOMER_ID);
			$c->addSelectColumn(CustomerPeer::CUSTOMER_ID);
			$c->addSelectColumn(CustomerPeer::NAME);
			$c->addSelectColumn(SfGuardUserProfilePeer::COMPANY);
			$customers		= CustomerPeer::doSelectRs($c);
			$this->cust		= array();

			while ($customers->next())
			{
				$cusId							= $customers->get(1);
				$this->cust[$cusId]['name']		= $customers->get(2);
				$this->cust[$cusId]['company']	= $customers->get(3);
			}
			//Separating recipient type id to extract list
			$recipientCustomers		= array();
			$cyberhackneyCustomers	= array();

			$c = new Criteria();
			$c->add(Us2OrderProductPeer::CUSTOMER_ID,$customerIDs,Criteria::IN);
			$c->add(Us2OrderProductPeer::RECIPIENT_TYPE_ID,array(5),Criteria::IN);
			$c->addSelectColumn(Us2OrderProductPeer::CUSTOMER_ID);
			$c->addSelectColumn(Us2OrderProductPeer::RECIPIENT_TYPE_ID);
			$rs = Us2OrderProductPeer::doSelectRS($c);
			while ($rs->next())
			{
				switch ($rs->get(2)){
					case 1:
						if(!in_array($rs->get(2), $recipientCustomers))
						{
							$recipientCustomers[]		= $rs->get(1);
						}
						break;
					case 5:
						if(!in_array($rs->get(1), $cyberhackneyCustomers))
						{
							$cyberhackneyCustomers[]	= $rs->get(1);
						}
						break;
					default:
						break;
				}

			}


			for ($xy=0;$xy<2;$xy++)
			{
				$c = new Criteria();
				$FromDate		= date('Y-m-d H:i:s', strtotime($this->getRequestParameter('fromDate', date('Y-m-d H:i:s', strtotime('-24 days 00:00:00')))));
				$ToDate			= date('Y-m-d H:i:s', strtotime($this->getRequestParameter('toDate', date('Y-m-d H:i:s', strtotime('today 23:59:59')))));
				if ($xy==0 && count($recipientCustomers)>0)
				{
					$c->add(Us2OrderProductPeer::CUSTOMER_ID,$recipientCustomers,Criteria::IN);
					$c->add(Us2OrderProductPeer::CREATED_DATE,$FromDate,Criteria::GREATER_EQUAL);
					$c->add(Us2OrderProductPeer::CREATED_DATE,$ToDate,Criteria::LESS_EQUAL);
					$c->addJoin(Us2OrderProductPeer::RECIPIENT_LIST_ID,  Us2RecipientListPeer::US2_RECIPIENT_LIST_ID);
					$c->addJoin(Us2OrderProductPeer::PRODUCT_ID, Us2ProductPeer::PRODUCT_ID);
					$c->addJoin(Us2OrderProductPeer::ORDER_PRODUCT_ID, Us2ListDownloadPeer::ORDER_PRODUCT_ID);
					$c->addSelectColumn(Us2OrderProductPeer::CUSTOMER_ID);
					$c->addSelectColumn(Us2OrderProductPeer::ORDER_PRODUCT_ID);
					$c->addSelectColumn(Us2ProductPeer::NAME);
					$c->addSelectColumn(Us2RecipientListPeer::LIST_COUNT);
					$c->addSelectColumn(Us2RecipientListPeer::CREATED_DATE);
					$c->addSelectColumn(Us2RecipientListPeer::SOURCE_XML);
					$c->addSelectColumn(Us2ListDownloadPeer::DOWNLOADED_YN);
					$rs = Us2OrderProductPeer::doSelectRs($c);
					$x = 0;
					while ($rs->next())
					{
						$downloaded = $rs->get(7);
						$this->cust[$rs->get(1)][$x]['order_product_id']	= $rs->get(2);
						$this->cust[$rs->get(1)][$x]['product_name']		= $rs->get(3);
						$this->cust[$rs->get(1)][$x]['list_count']			= $rs->get(4);
						$this->cust[$rs->get(1)][$x]['created_date']		= $rs->get(5);
						$this->cust[$rs->get(1)][$x]['list_details']		= $rs->get(6);
						$this->cust[$rs->get(1)][$x]['downloaded_yn']		= (!is_null($downloaded))?$downloaded:"N";
					}

				}
				else
				{
					$sortByColumn		= $this->getRequestParameter("sortByColumn", "");

					$pageLimit			= intval($this->getRequestParameter("pageLimit", 10));
					if (!in_array($pageLimit, array(10,15,25,100))) { $pageLimit = 10; }

					$pageOffset			= intval($this->getRequestParameter("pageOffset", 1)) - 1;
					if ($pageOffset < 0) { $pageOffset = 0; }

					$tempIds			= array();
					$pullInfo			= array();
					$sortByColumn		= explode("_",$sortByColumn);
					$sortByColumn[1]	= ($sortByColumn[1] != "Desc" && $sortByColumn[1] != "Asc")?"DESC":$sortByColumn[1];
					$wilmaCon			= Propel::getConnection();
					$select				= "SELECT `us2_order_product`.`customer_id`,`us2_order_product`.`recipient_list_id`,`us2_order_product`.`order_notes`,`us2_order`.`order_created_date`,`us2_order_product`.`order_product_id` ";
					$countSelect		= "SELECT count(`us2_order_product`.`order_product_id`)as totalRows ";
					$query				= ""
										. "FROM `us2_order_product` JOIN `us2_order` ON `us2_order_product`.`order_id` = `us2_order`.`order_id` "
										. "WHERE `us2_order_product`.`customer_id` in (".implode(",",$cyberhackneyCustomers).") "
										. "AND `us2_order_product`.`recipient_type_id` = 5 "
										. "AND `us2_order`.`is_cart_yn` = 'N' "
										. "AND `us2_order`.`order_created_date` BETWEEN '".$FromDate."' AND '".$ToDate."' "
										. "AND `us2_order`.`order_handling_status_id` != 9 "
										. "ORDER BY `us2_order_product`.`customer_id` ASC";
					$countQuery			= $countSelect.$query;
					$query				= $select.$query;
					switch($sortByColumn[0])
					{
						case 'ProductName':
							$query		.=", `us2_order_product`.`order_notes` ".strtoupper($sortByColumn[1]);
							break;
						default:
							$query		.=", `us2_order`.`order_created_date` ".strtoupper($sortByColumn[1]);
							break;
					}
					$query				.=" LIMIT ".($pageLimit*$pageOffset).",$pageLimit";

					$stmt				= $wilmaCon->prepareStatement($query);
					$rs					= $stmt->executeQuery();
					while ($rs->next())
					{
						$row = $rs->getRow();
						if(!in_array($row['customer_id'], $tempIds))
						{
							$tempIds[]			= $row['customer_id'];
						}
						$pullInfo[$row['order_product_id']] = array('name'=>$row['order_notes'],'date'=>$row['order_created_date'],'customer_id'=>$row['customer_id'],'pull_id'=>$row['recipient_list_id']);
					}
					$stmt				=$wilmaCon->prepareStatement($countQuery);
					$rs					=$stmt->executeQuery();
					while ($rs->next())
					{
						$row			= $rs->getRow();
						$totalCount		=$row['totalRows'];
					}


					$attributes			= array('active_yn'=>'Y');
					foreach ($tempIds as $csId)
					{
						$attributes['mailer_id']		= $csId;
						$cyber							= new CyberHackney();
						$response						= $cyber->get("Pulls",$attributes);

						if ($response === false)
						{
							error_log('CyberHackney Email List -- Error'."\r\n");
						}
						else
						{
							$x = 0;

							foreach ($pullInfo as $orderProduct => $pullValues)
							{
								if ($csId != $pullValues['customer_id']){continue;}
								foreach ($response['results'] as $values)
								{
									if($values['pull_master_id']!= $pullValues['pull_id']){continue;}
									$this->cust[$csId][$x]['order_product_id']	= $values['pull_master_id'];
									$this->cust[$csId][$x]['product_name']		= $pullInfo[$orderProduct]['name'];
									$this->cust[$csId][$x]['list_count']		= $values['net_records'];
									$this->cust[$csId][$x]['created_date']		= $pullInfo[$orderProduct]['date'];
									$this->cust[$csId][$x]['list_details']		= "http://cyberhackney.ammscore.com/PullData?active_yn=Y&pull_id={$values['pull_id']}&user_id={$values['user_id']}&mailer_id={$values['mailer_id']}&customer_id={$values['customer_id']}";
									$c											= new Criteria();
									$c->add(Us2ListDownloadPeer::ORDER_PRODUCT_ID,$values['pull_master_id']);
									$c->addSelectColumn(Us2ListDownloadPeer::DOWNLOADED_YN);
									$rs											= Us2ListDownloadPeer::doSelectRS($c);
									while($rs->next()){
										$downloaded								= $rs->get(1);
										$this->cust[$csId][$x]['downloaded_yn']	= (!is_null($downloaded))?$downloaded:'N';
									}
									$x++;

								}
							}


						}
					}
				}
			}
			$protocol	= (USE_HTTPS && (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT']	== 443)) ? "https://" : "http://";
			$domainName	= $_SERVER['HTTP_HOST'].'/';
			$tempCheckMark	= '<img style="vertical-align: middle;" src="'.$protocol.$domainName.'images/amms_store/activeicon.gif" alt="Green Checkmark">';

			$tableBody	= '';
			foreach ($this->cust as $customerId	=> $x)
			{

				$count = count($x);
				$count -= 2;
				for ($t=0;$t<$count;$t++)
				{
					if ($x[$t]['downloaded_yn']!='Y')
					{
						$buttonText = "Download";
						$checkMark = "";
						$class = "options-button";
					}
					else
					{
						$buttonText = "Download";
						$checkMark = $tempCheckMark;
						$class = "disabled-button";
					}

					$tableBody	.= "<tr>"
								. "<td>".$x['company']."</td>"
								. "<td>".$x['name']."</td>"
								. "<td>".$x[$t]['product_name']."</td>"
								. "<td>{$x[$t]['list_count']}</td>"
								. "<td>{$x[$t]['created_date']}</td>"
								. "<td><button class='{$class} blank' onclick='downloadFile(this)' data-value='{$x[$t]['list_details']}' data-level1='{$customerId}' data-level2='{$t}'><span class='ui-icon ui-icon-white ui-icon-arrowthickstop-1-s'></span></button></td>"
								. "<td>".$checkMark."</td>"
								. "</tr>";
				}

			}

			$this->setFlash('emailCustomerVariables',$this->cust);
			$tableBody		= (is_null($tableBody)||$tableBody =='')?"<td colspan='7' style='text-align:center; font-weight:bold;'>No lists have been uploaded yet</td>":$tableBody;
			$response		= array();
			$response[]		= $tableBody;
			$response[]		= $totalCount;
			$response[]		= intval(ceil($totalCount/$pageLimit));
			$buttons		= "";
			$totalButtons	= (($pageOffset+3) <= $response[2])?($pageOffset+3):($response[2]);
			for($offset = $pageOffset;$offset<=$totalButtons;$offset++)
			{
				if ($offset<=0) {continue;}
				$buttons	.= "&nbsp;<button class='pagination-button blank' onclick='loadPage($offset)'>$offset</button>&nbsp;";
			}
			$response[]		= $buttons;
			$response[]		= $pageOffset;

			return $this->renderText(json_encode($response));
		}
		elseif (isset ($fileInfo)) //If customer clicked the download button TODO: Add method to handle xml data
		{
			$url	= $fileInfo;

			// $ferr = fopen(SF_ROOT_DIR."/log/error.log",'a'); //For Testing
			$ch		= curl_init();
			//curl_setopt($ch, CURLOPT_VERBOSE, 1);//For testing
			//curl_setopt($ch, CURLOPT_STDERR, $ferr); //For Testing

			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
			curl_setopt($ch, CURLOPT_TIMEOUT, 300);
			curl_setopt($ch, CURLOPT_URL, $url);

			if (($fp = fopen(SF_ROOT_DIR."/web/uploads/assets/EmailList.csv","w")) !== false) {
				curl_setopt($ch, CURLOPT_ENCODING , "gzip");
				curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
				$response	= curl_exec($ch);
				if (!$response)
				{
					echo curl_error($ch);exit;
				}
				$response			= json_decode($response, true);
				$fields				= array('CUSTOMER_NAME','FIRST','MIDDLE_NAME','LAST','ADDRESS','CITY','STATE','ZIP','HOME_PHONE','CELL_PHONE','WORK_PHONE','EMAIL');
				$result				= fputcsv($fp, $fields);

				if ($result === false) die("error while writing to file");
				$concatFields		= array();
				foreach ($response['data'] as $field)
				{
					$line			= array();
					$concatField	= $field['ADDRESS'].$field['CITY'].$field['STATE'].$field['ZIP'];
					//If this fields are in array then do not write the record to file
					if(in_array($concatField, $concatFields)){continue;}

					$concatFields[] = $field['ADDRESS'].$field['CITY'].$field['STATE'].$field['ZIP'];
					foreach ($fields as $fieldName)
					{
						$line[]		= (isset($field[$fieldName]))?$field[$fieldName]:"";

					}
					unset($field);
					fputcsv($fp, $line);
				}
				fclose($fp);
				$file				= SF_ROOT_DIR."/web/uploads/assets/EmailList.csv";
				echo $file;exit;
			}
			else
			{
				echo "Error";exit;
			}
		}
		elseif (isset($data['download'])&& $data['download']!= '')
		{
			/*
			 * Inserting download check in us2_list_download
			 */
			$x					= $data['level1'];
			$t					= $data['level2'];

			$this->cust = $this->getFlash('emailCustomerVariables');
			$us2ListDownload	= new Us2ListDownload();
			$us2ListDownload->setOrderProductId($this->cust[$x][$t]['order_product_id']);
			$us2ListDownload->setCustomerId($x);
			$us2ListDownload->setListCount($this->cust[$x][$t]['list_count']);
			$us2ListDownload->setUserId(intval($this->CurrentUserId));
			$us2ListDownload->setListUploadDate($this->cust[$x][$t]['created_date']);
			$us2ListDownload->setDownloadedYn('Y');
			$us2ListDownload->setDownloadTimestamp(date("Y-m-d H:i:s"));
			$us2ListDownload->setDownloadIp($_SERVER['REMOTE_ADDR']);
			$us2ListDownload->save();

			$file			= $data['download'];
			$downloadName	= trim($this->cust[$x][$t]['product_name']).".csv";
			header("Cache-Control: maxage=1");
			header("Pragma: public");
			header("Content-type: text/csv");
			header("Content-Disposition: attachment; filename=\"". $downloadName."\"");
			header("Content-Description: PHP Generated Data");
			header("Content-Transfer-Encoding: binary");
			header('Content-Length:' . filesize($file));
			readfile($file);

			exit;
		}
		else
		{
			$c = new Criteria();
			$c->add(CustomerPeer::CLIENT_ID,$this->CurrentClientId);
			$c->addSelectColumn(CustomerPeer::CUSTOMER_ID);
			$c->addSelectColumn(CustomerPeer::NAME);
			$c->addSelectColumn(CustomerPeer::EMAIL);
			$c->addAscendingOrderByColumn(CustomerPeer::NAME);
			$customers = CustomerPeer::doSelectRs($c);

			$this->cust = array();
			while($customers->next())
			{
				$cusId						= $customers->get(1);
				$email						= (trim($customers->get(3))=='')?'--':trim($customers->get(3));
				$name						= (trim($customers->get(2))=='')?$email:trim($customers->get(2));
				$this->cust[$cusId]['name'] = $name;
			}
			$this->getResponse()->setTitle( WEBSITE_TITLE ." - Email Manager" );
			$this->ActiveMenu = "Admin";
			$this->setTemplate('EmailManager');
			return '_Success';exit;
		}
	}

	private function executeOrderManager()
	{
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));

		$Connection = Propel::getConnection();

		if (!empty($this->Cancel)) {
			$OrderProductId = $this->getRequestParameter("OrderProductId");
			if (!empty($OrderProductId)) {

				// Cancel the specified order product and any children thereof.
				$Query	= "UPDATE us2_order_product SET order_handling_status_id=9 "
						. "WHERE order_product_id = {$OrderProductId} "
						. "OR parent_us2_order_product_id = {$OrderProductId}";

				$result = $Connection->executeQuery($Query);
				$results = array("success" => true);

				return $this->renderText(json_encode($results));
			}
			$results = array("success" => false);
			return $this->renderText(json_encode($results));
		}

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Order Manager" );
		$this->setTemplate('OrderManager');

		if (STORE_ID == CE_STORE_ID) {
			$this->DisplayCEClientSelector = true;
			return '_CE';
		} else {
			return '_Success';
		}
	}

	private function executeGetOrderProductNotes()
	{
		$this->CheckAuthentication();
		$this->setLayout(false);
		$this->setTemplate('OrderProductNotes');

		$Connection = Propel::getConnection();

		// This is order product id
		$OrderProductId		= $this->getRequestParameter('Id');

		$Query	= "SELECT us2_order_product_compliance.order_product_compliance_id, us2_order_product_compliance.submitted_date, us2_order_product_compliance.stage, "
				. "us2_order_product.order_product_id , us2_order_product.order_notes, customer.name AS customer_name, "
				. "us2_order_proof_id, uproduce_job_id, is_test_yn, proof_url, tiny_image_url, small_image_url, "
				. "medium_image_url, large_image_url, image_process_filename, image_converted_yn, last_updated_date, us2_order_proof.stored_date "
				. "FROM us2_order_product "
				. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
				. "LEFT JOIN customer ON us2_order_product.customer_id = customer.customer_id "
				. "LEFT JOIN us2_order_proof ON us2_order_product.order_product_id = us2_order_proof.us2_order_product_id "
				. "WHERE us2_order_product.order_product_id = {$OrderProductId}";

		$Rs = $Connection->executeQuery($Query);

		while ($Rs->next()) {
			$this->Compliance = $Rs->getRow();
		}

		$Query	= "SELECT us2_order_product_note.*, TRIM(CONCAT(first_name, ' ', last_name)) AS user "
				. "FROM us2_order_product_note "
				. "LEFT JOIN sf_guard_user_profile ON us2_order_product_note.created_by_user_id = sf_guard_user_profile.user_id "
				. "WHERE order_product_id = {$OrderProductId} "
				. "ORDER BY order_product_note_id DESC";

		$Rs = $Connection->executeQuery($Query);
		$this->arrayNote = array();

		while ($Rs->next()) {
			$this->arrayNote[] = $Rs->getRow();
		}

		return '_Success';
	}

	/**
	 * Return a friendly date (m/d/Y, optionally h:i a) if the supplied date is valid; otherwise return blank.
	 */
	private function FriendlyDate($date, $IncludeTime=false) {
		$FormatString	= $IncludeTime ? 'm/d/Y h:i a' : 'm/d/Y';

		// If the date is not 0000
		if (!preg_match("/^0000/", $date)) {
			$time = strtotime($date);
			if ($time !== false) {
				return date($FormatString, $time);
			}
		}

		return '';
	}

	/**
	 * Return a date in ISO-8601 format (Y-m-d, optionally H:i:s) if the supplied date is valid; otherwise return 0000-00-00.
	 */
	private function ISO8601Date($date, $IncludeTime=false) {
		if ($IncludeTime) {
			$FormatString	= 'Y-m-d H:i:s';
			$DefaultTime	= '0000-00-00 00:00:00';
		} else {
			$FormatString	= 'Y-m-d';
			$DefaultTime	= '0000-00-00';
		}

		$time = strtotime($date);
		if ($time !== false) {
			return date($FormatString, $time);
		} else {
			return $DefaultTime;
		}
	}

	private function executeGetAutoCampaignAgreement()
	{
		// If not already authenticated
		if (!$this->AccessControl->isAuthenticated) {
			return false;
		}

		$this->setLayout(false);
		$this->setTemplate('AutoCampaignAgreement');

		$Connection = Propel::getConnection();

		$this->OrderProductId	= $this->getRequestParameter('Id', 0);
		// non-editable view if 1
		$this->ReadOnly			= $this->getRequestParameter('ReadOnly', 0);

		$Query1		= "SELECT * FROM us2_auto_campaign_agreement WHERE order_product_id = {$this->OrderProductId}";

		$Rs1 = $Connection->executeQuery($Query1);

		while ($Rs1->next()) {
			$agreement = $Rs1->getRow();
		}

		if (!empty($agreement)) {
			$agreement['mail_date_1'] = $this->FriendlyDate($agreement['mail_date_1']);
			$agreement['sale_date_1'] = $this->FriendlyDate($agreement['sale_date_1']);
			$agreement['mail_date_2'] = $this->FriendlyDate($agreement['mail_date_2']);
			$agreement['sale_date_2'] = $this->FriendlyDate($agreement['sale_date_2']);
			$agreement['mail_date_3'] = $this->FriendlyDate($agreement['mail_date_3']);
			$agreement['sale_date_3'] = $this->FriendlyDate($agreement['sale_date_3']);
			$agreement['mail_date_4'] = $this->FriendlyDate($agreement['mail_date_4']);
			$agreement['sale_date_4'] = $this->FriendlyDate($agreement['sale_date_4']);
		} else {

			$Query2 = "SELECT name, contact_name FROM client WHERE client_id = " . SF_CLIENT_ID;

			$Rs2 = $Connection->executeQuery($Query2);
			while ($Rs2->next()) {
				$Client = $Rs2->getRow();
			}

			require_once(SF_ROOT_DIR . "/classes/class.customer_profile.php");
			$CustomerProfile = new CustomerProfile();
			$arrayCustomerProfileId = $CustomerProfile->getCustomersDefaultProfile(array($this->AccessControl->CustomerId));
			$CustomerProfileData = $CustomerProfile->GetProfileData($arrayCustomerProfileId[$this->AccessControl->CustomerId]);

			$Us2OrderProduct		= Us2OrderProductPeer::retrieveByPk($this->OrderProductId);
			$Us2Product				= Us2ProductPeer::retrieveByPk($Us2OrderProduct->getProductId());

			if ($Us2Product->getProductTypeId() == 1) {
				$ExtraParamsXml				= $Us2OrderProduct->getExtraParamsXml();

				if (!empty($ExtraParamsXml)) {
					$ExtraParams				= json_decode($ExtraParamsXml, true);

					$CountDms					= $ExtraParams['CountDms'];
					$CountConquest				= $ExtraParams['CountConquest'];
					$TotalQuantity				= intval($CountDms) + intval($CountConquest);
				} else {
					$CountDms					= 0;
					$CountConquest				= 0;
					$TotalQuantity				= 0;
				}
			} else {
				$TotalQuantity			= $Us2OrderProduct->getTotalQuan();
			}



			$C						= new Criteria();
			$C->add(Us2ProductWoPropsPeer::PRODUCT_ID, $Us2Product->getUs2ProductTemplateId());

			$this->ProductWoProps		= Us2ProductWoPropsPeer::doSelectOne($C);

			if (!empty($this->ProductWoProps)) {
				$this->ProductWoPropsId		= $this->ProductWoProps->getUs2ProductWoPropsId();
				$this->EnvelopeId			= $this->ProductWoProps->getEnvelopeId();
				if ($this->EnvelopeId > 0) {
					$Us2EnvelopeStyles			= Us2EnvelopeStylesPeer::retrieveByPk($this->EnvelopeId);
					$this->EnvelopeStyle		= $Us2EnvelopeStyles->getEnvelopeDesc();
				} else {
					$this->EnvelopeStyle		= '';
				}
				$ProductSize				= $this->ProductWoProps->getFinalSize();
				$ProductColors				= $this->ProductWoProps->getBwOrColor();
				$PrintSides					= $this->ProductWoProps->getPrintedSides();
				$Bleeds						= $this->ProductWoProps->getBleeds();

				$this->PaperTypeId			= $this->ProductWoProps->getPaperTypeId();
				$PaperTypes					= Us2PaperTypesPeer::retrieveByPk($this->PaperTypeId);
				$this->PaperType			= $PaperTypes->getPaperType();

				$this->PostalClassId		= $this->ProductWoProps->getPostalClassId();
				$Us2PostalClass				= Us2PostalClassPeer::retrieveByPk($this->PostalClassId);
				$this->PostalClass			= $Us2PostalClass->getPostalClass();
			} else {
				$this->ProductWoPropsId		= '';
				$this->EnvelopeId			= '';
				$this->EnvelopeStyle		= '';
				$ProductSize				= '';
				$ProductColors				= '';
				$PrintSides					= '';
				$Bleeds						= '';
				$this->PaperTypeId			= '';
				$this->PaperType			= '';
				$this->PostallClassId		= '';
				$this->PostalClass			= '';
			}





			$agreement = array(
					"client_id"						=> SF_CLIENT_ID,
					"customer_id"					=> $AccessControl->CustomerId,
					"user_id"						=> $AccessControl->UserId,
					"order_product_id"				=> $this->OrderProductId,
					"client_name"					=> $Client['name'],
					"client_contact"				=> $Client['contact_name'],
					"dealership_name"				=> $CustomerProfileData['sales_dealer_name'],
					"dealership_contact"			=> $CustomerProfileData['sales_contact_name'],
					"dealership_phone"				=> $CustomerProfileData['sales_contact_phone'],
					"dealership_address"			=> $CustomerProfileData['sales_address'],
					"dealership_city"				=> $CustomerProfileData['sales_city'],
					"dealership_state"				=> $CustomerProfileData['sales_state'],
					"dealership_zip"				=> $CustomerProfileData['sales_zip'],
					"total_qty"						=> $TotalQuantity,
					"mail_drops"					=> 1,
					"samples"						=> 0,
					"mail_date_1"					=> date('m/d/Y', strtotime("+7 days")),
					"quantity_1"					=> $TotalQuantity,
					"sale_date_1"					=> '',
					"mail_date_2"					=> '',
					"quantity_2"					=> '',
					"sale_date_2"					=> '',
					"mail_date_3"					=> '',
					"quantity_3"					=> '',
					"sale_date_3"					=> '',
					"mail_date_4"					=> '',
					"quantity_4"					=> '',
					"sale_date_4"					=> '',
					"campaign_name"					=> $Us2OrderProduct->getOrderNotes(),
					"paper_size"					=> $ProductSize,
					"print_color"					=> $ProductColors,
					"bleeds_yn"						=> $Bleeds,
					"paper_description"				=> $this->PaperType,
					"paper_select"					=> $this->PaperType,
					"paper_type"					=> $this->PaperType,
					"paper_weight"					=> $this->PaperType,
					"envelope_size"					=> $this->EnvelopeStyle,
					"envelope_type"					=> $this->EnvelopeStyle,
					"envelope_color"				=> $this->EnvelopeStyle,
					"envelope_description"			=> $this->EnvelopeStyle,
					"insert_1"						=> '',
					"insert_size_1"					=> '',
					"insert_color_1"				=> '',
					"insert_bleeds_1_yn"			=> '',
					"insert_2"						=> '',
					"insert_size_2"					=> '',
					"insert_color_2"				=> '',
					"insert_bleeds_2_yn"			=> '',
					"special_instructions"			=> '',
					"add_on_1"						=> '',
					"add_on_2"						=> '',
					"add_on_3"						=> '',
					"add_on_attach_1"				=> '',
					"add_on_attach_2"				=> '',
					"add_on_attach_3"				=> '',
					"postal_class_id"				=> $this->PostalClassId,
					"postage_class"					=> $this->PostalClass,
					"postage_type"					=> '',
					"data_select"					=> '',
					"data_instructions"				=> '',
					"list_criteria"					=> '',
					"client_authorized_name"		=> '',
					"client_authorized_signature"	=> ''
			);
		}


		$this->agreement = $agreement;

		if (!empty($this->ReadOnly)) {
			return "_ReadOnly";
		} else {
			$this->getWorkOrderArrays();
			return "_Success";
		}
	}


	private function getWorkOrderArrays() {
		$Connection = Propel::getConnection();
		// Load options arrays for select controls
		$Query = "SELECT DISTINCT final_size AS value FROM us2_product_wo_props ORDER BY value";
		$Rs = $Connection->executeQuery($Query);
		$temp = array();
		while ($Rs->next()) {
			$temp[]								= $Rs->get('value');
		}
		$this->arrayCampaignPaperSize		= array_combine($temp, $temp);

		$Query = "SELECT DISTINCT CONCAT(printed_sides, ' ', bw_or_color) AS value FROM us2_product_wo_props ORDER BY value";

		// Load options arrays for select controls
		$Query = "SELECT DISTINCT bw_or_color AS value FROM us2_product_wo_props ORDER BY value";
		$Rs = $Connection->executeQuery($Query);
		$temp = array();
		while ($Rs->next()) {
			$temp[]								= $Rs->get('value');
		}
		$this->arrayColor					= array_combine($temp, $temp);

		$this->arrayYesNo					= array(
				"yes"				=> "Yes",
				"no"				=> "No"
			);

		$Query = "SELECT DISTINCT paper_type AS value FROM us2_paper_types WHERE active_yn = 'yes' ORDER BY value";
		$Rs = $Connection->executeQuery($Query);
		$temp = array();
		while ($Rs->next()) {
			$temp[]								= $Rs->get('value');
		}
		$this->arrayPaper					= array_combine($temp, $temp);

		$this->arrayPaperType				= array_combine($temp, $temp);

		$this->arrayPaperWeight				= array_combine($temp, $temp);

		$Query = "SELECT DISTINCT envelope_desc AS value FROM us2_envelope_styles WHERE active_yn = 'yes' ORDER BY value";
		$Rs = $Connection->executeQuery($Query);
		$temp = array();
		while ($Rs->next()) {
			$temp[]								= $Rs->get('value');
		}
		$this->arrayEnvelopeSize			= array_combine($temp, $temp);

		$this->arrayEnvelopeType			= array_combine($temp, $temp);

		$this->arrayEnvelopeColor			= array_combine($temp, $temp);

		$temp								= array(
				"Blackbook Value",
				"Variable Imaging",
				"Bleeds",
				"Match Mail",
				"Inkjet",
				"UV Coating 1 Side",
				"UV Coating 2 Sides",
				"Peek-A-Boo",
				"Bingo Scratch Card",
				"Rectangle Scratch Off Label",
				"Car Look A Like Key",
				"Treasure Chest Key",
				"Bluebook Value",
				"QR Code Application",
				"Spanish Translation",
				"BDC - Credit Phone Calls",
				"BDC - Buyback / BK Phone Calls",
				"Title Alteration"
			);
		$this->arrayAddOn					= array_combine($temp, $temp);

		$temp								= array(
				"Yellow Sticky Note - Black Laser",
				"Yellow Sticky Note - Color Laser",
				"Visa Black Gift Card",
				"Soft Card Simplex 4 Color",
				"Soft Card Duplex 4 Color",
				"Soft Card 4 Color over Black Laser"
			);
		$this->arrayAddOnWithProduct		= array_combine($temp, $temp);

		$Query = "SELECT DISTINCT postal_class_id AS `key`, postal_class AS value FROM us2_postal_class WHERE active_yn = 'yes' ORDER BY postal_class";
		$Rs = $Connection->executeQuery($Query);
		$temp = array();
		while ($Rs->next()) {
			$temp[$Rs->get('key')]				= $Rs->get('value');
		}
		$this->arrayPostageClass			= $temp;

		$temp								= array(
				"Letter",
				"PC",
				"Flat"
			);
		$this->arrayPostageType				= array_combine($temp, $temp);

		$temp								= array(
				"Model Auto Data",
				"Model Auto Data with VIN",
				"Credit Data",
				"Saturation Data",
				"Summarized Credit",
				"Summarized Credit with VIN",
				"Fleet Owners",
				"Business Data"
			);
		$this->arrayData					= array_combine($temp, $temp);
	}


	private function getWorkOrderArraysOLD() {
		// Load options arrays for select controls
		$temp								= array(
				"8.5 x 11",
				"8.5 x 14",
				"4.25 x 5.5",
				"4 x 6",
				"5.5 x 8.5",
				"5.5 x 11",
				"6 x 9",
				"6 x 11",
				"6 x 14",
				"6 x 12",
				"7 x 10",
				"10 x 14"
			);
		$this->arrayCampaignPaperSize		= array_combine($temp, $temp);

		$temp								= array(
				"Simplex 4 Color Laser",
				"Duplex 4 Color Laser",
				"Simplex Black Laser",
				"Duplex Black Laser",
				"4 Color over Black Laser"
			);
		$this->arrayColor					= array_combine($temp, $temp);

		$this->arrayYesNo					= array(
				"Y"				=> "Yes",
				"N"				=> "No"
			);

		$temp								= array(
				"Gloss",
				"Offset",
				"Matte",
				"Dull",
				"3up Check",
				"Docu Card"
			);
		$this->arrayPaper					= array_combine($temp, $temp);

		$temp								= array(
				"Text",
				"Cover"
			);
		$this->arrayPaperType				= array_combine($temp, $temp);

		$temp								= array(
				"60#",
				"70#",
				"80#",
				"100#",
				"10PT",
				"12PT"
			);
		$this->arrayPaperWeight				= array_combine($temp, $temp);

		$temp								= array(
				"#9",
				"#10",
				"6 x 9",
				"A6",
				"A7",
				"9 x 12"
			);
		$this->arrayEnvelopeSize			= array_combine($temp, $temp);

		$temp								= array(
				"Window",
				"Regular",
				"Booklet",
				"Catalog"
			);
		$this->arrayEnvelopeType			= array_combine($temp, $temp);

		$temp								= array(
				"White",
				"Ivory"
			);
		$this->arrayEnvelopeColor			= array_combine($temp, $temp);

		$temp								= array(
				"Blackbook Value",
				"Variable Imaging",
				"Bleeds",
				"Match Mail",
				"Inkjet",
				"UV Coating 1 Side",
				"UV Coating 2 Sides",
				"Peek-A-Boo",
				"Bingo Scratch Card",
				"Rectangle Scratch Off Label",
				"Car Look A Like Key",
				"Treasure Chest Key",
				"Bluebook Value",
				"QR Code Application",
				"Spanish Translation",
				"BDC - Credit Phone Calls",
				"BDC - Buyback / BK Phone Calls",
				"Title Alteration"
			);
		$this->arrayAddOn					= array_combine($temp, $temp);

		$temp								= array(
				"Yellow Sticky Note - Black Laser",
				"Yellow Sticky Note - Color Laser",
				"Visa Black Gift Card",
				"Soft Card Simplex 4 Color",
				"Soft Card Duplex 4 Color",
				"Soft Card 4 Color over Black Laser"
			);
		$this->arrayAddOnWithProduct		= array_combine($temp, $temp);

		$temp								= array(
				"1st Class",
				"Standard Class",
				"Saturation",
				"Standard W/ Dropship",
				"Full Rate"
			);
		$this->arrayPostageClass			= array_combine($temp, $temp);

		$temp								= array(
				"Letter",
				"PC",
				"Flat"
			);
		$this->arrayPostageType				= array_combine($temp, $temp);

		$temp								= array(
				"Model Auto Data",
				"Model Auto Data with VIN",
				"Credit Data",
				"Saturation Data",
				"Summarized Credit",
				"Summarized Credit with VIN",
				"Fleet Owners",
				"Business Data"
			);
		$this->arrayData					= array_combine($temp, $temp);
	}


	private function executeAddOrderProductNote()
	{
		if (@$this->iAccessControl->sAuthenticated) {
			return $this->renderText(json_encode(0));
		}
		$this->setLayout(false);

		$Connection = Propel::getConnection();

		$OrderProductId		= $this->getRequestParameter('OrderProductId');
		$Note				= $this->getRequestParameter('Note');
		$Note				= addslashes(stripslashes($Note));

		$Query	= "INSERT INTO us2_order_product_note SET "
				. "order_product_id = '{$OrderProductId}', "
				. "note = '{$Note}', "
				. "created_by_user_id = '{$this->AccessControl->UserId}', "
				. "created_date = NOW()";

		$Rs = $Connection->executeQuery($Query);

		return $this->renderText(json_encode($Rs));
	}

	private function executeUploadComplianceFile()
	{
		if (!$this->AccessControl->isAuthenticated) {
			return $this->renderText(json_encode($false));
		}

		require_once(SF_ROOT_DIR . '/apps/' . SF_APP . '/lib/class.riak_transport.php');

		$UploadDir	= sfConfig::get('sf_upload_dir');
		$UserName	= SfGuardUserProfilePeer::GetNameByUserId($this->AccessControl->UserId);

		$RiakTransport = new RiakTransport();

		$Request = $this->getRequest();
		if ($Request->hasFiles()) {
			foreach ($Request->getFileNames() as $index => $uploadedFile) {
				$FileName	= $Request->getFileName($uploadedFile);
				$FileSize	= $Request->getFileSize($uploadedFile);
				$FileType	= $Request->getFileType($uploadedFile);
				$FileError	= $Request->hasFileError($uploadedFile);

				// Generate a unique file name
				$TempName	= uniqid("{$this->OrderProductId}_{$this->AccessControl->UserId}_");
				$Path		= $UploadDir.'/'.$TempName;
				// Move file to this location
				$Request->moveFile($uploadedFile, $Path);
				// Open file for reading as binary
				$length		= filesize($Path);
				if ($FileSize != $length) {
					unlink($Path);
					die("Error1");
				}
				$file		= fopen($Path, 'rb');
				$ByteArray	= fread($file, $FileSize);
				// Riak appears to get funky with binary data, so let's just base64 encode everything
				$Base64		= base64_encode($ByteArray);

				$result = $RiakTransport->Save($this->OrderProductId, $FileName, $FileSize, $this->AccessControl->UserId, $UserName, $Base64);

				unlink($Path);
			}
		}

		return $this->renderText(json_encode($result));
	}


	private function executeDownloadComplianceFile()
	{
		if (!$this->AccessControl->isAuthenticated) {
			return false;
		}

		$this->setLayout(false);

		require_once(SF_ROOT_DIR . '/apps/' . SF_APP . '/lib/class.riak_transport.php');

		$UploadId			= $this->getRequestParameter('Id', '0');
		$UseJson			= $this->getRequestParameter('Json', 0);
		$arrayId			= explode('_', $UploadId);
		$OrderProductId		= $arrayId[0];
		$Key				= $arrayId[1];

		$RiakTransport		= new RiakTransport();

		$IndexData			= $RiakTransport->GetIndexData($OrderProductId, $Key);
		$FileName			= $IndexData['filename'];
		$FileSize			= $IndexData['filesize'];

		// Riak appears to get funky with binary data, so let's just base64 encode everything
		$Base64				= $RiakTransport->Get($OrderProductId, $Key);
		if ($Base64 === false) {
			exit;
		}
		$ByteArray			= base64_decode($Base64);

		$length				= sizeof($ByteArray);

		if (!empty($UseJson)) {
			$result = array(
				'filename' => $FileName,
				'length' => $length,
				'content' => base64_encode($ByteArray)
			);

			return $this->renderText(json_encode($result));
		} else {
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Cache-Control: private", false); // required for certain browsers
			header("Content-Transfer-Encoding: binary");

			header("Content-Type: application/octet-stream");
			header("Content-Disposition: inline; filename=\"{$FileName}\";");
			echo $ByteArray;
		}
		exit;
	}


	private function executeListComplianceFiles()
	{
		if (!$this->AccessControl->isAuthenticated) {
			return false;
		}

		$Id				= $this->getRequestParameter('Id');
		if (is_numeric($Id)) {
			$OrderProductId = $Id;
		} else {
			$temp = explode('_', $Id);
			$OrderProductId = $temp[0];
		}

		require_once(SF_ROOT_DIR . '/apps/' . SF_APP . '/lib/class.riak_transport.php');

		$RiakTransport	= new RiakTransport();

		$Index			= $RiakTransport->GetIndexData($OrderProductId);

		return $this->renderText(json_encode($Index));
	}


	private function executeDeleteComplianceFile()
	{
		if (!$this->AccessControl->isAuthenticated) {
			return false;
		}

		$this->setLayout(false);

		require_once(SF_ROOT_DIR . '/apps/' . SF_APP . '/lib/class.riak_transport.php');

		$UploadId			= $this->getRequestParameter('Id');
		$arrayId			= explode('_', $UploadId);
		$OrderProductId		= $arrayId[0];
		$Key				= $arrayId[1];

		$RiakTransport = new RiakTransport();
		$result = $RiakTransport->Delete($OrderProductId, $Key);

		return $this->renderText(json_encode(array('success' => $result)));
		exit;
	}


	private function executeAutoCampaignAgreement()
	{
		$this->CheckAuthentication();
		$this->setTemplate('AutoCampaignAgreement');

		$this->getWorkOrderArrays();

		return '_Success'; exit;
	}


	/**
	* Private Function:
	*********************************************************************************/
	private function executeRemoveOrderProductList()
	{
		$this->CheckAuthentication();
		$this->setTemplate('RemoveOrderProductList');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeDeleteCategory()
	{
		$this->CheckAuthentication();
		$this->setTemplate('DeleteCategory');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeRecipientListMap()
	{
		$this->CheckAuthentication();
		$this->setTemplate('RecipientListMap');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executePricingDetail()
	{
		$this->CheckAuthentication();
		$this->setTemplate('PricingDetail');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeAddPricing()
	{
		$this->CheckAuthentication();
		$this->setTemplate('AddPricing');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeSetCategoryStatus()
	{
		$this->setTemplate('SetCategoryStatus');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeCasOrderSelection()
	{
		$TypeId = ($this->TypeId < 1) ? 1 : $this->TypeId;
		$this->setTemplate("CasOrderSelection{$TypeId}");
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeDeleteProduct()
	{
		$this->setTemplate('DeleteProduct');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeEditGroup()
	{
		$this->setTemplate('EditGroup');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeEditUserGroup()
	{
		$this->setTemplate('EditUserGroup');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeSaveGroupPermission()
	{
		$this->setTemplate('SaveGroupPermission');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Save Other Setting
	*********************************************************************************/
	private function executeSaveOtherSetting()
	{
		$this->setTemplate('SaveOtherSetting');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Save Product Info
	*********************************************************************************/
	private function executeSaveProductInfo()
	{
		$this->CheckAuthentication();
		$this->setTemplate('SaveProductInfo');
		$this->ProductId		= $this->getRequestParameter('ProductId', 0);
		$this->ProductName		= $this->getRequestParameter('productName', '');
		$this->ProductDesc		= $this->getRequestParameter('description', '');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Save Product Addon Call Script
	*********************************************************************************/
	private function executeSaveProductAddonCallScript()
	{
		$this->CheckAuthentication();
		$this->ProductId			= $this->getRequestParameter('ProductId');
		$this->callCenterScript		= $this->getRequestParameter('callCenterScript');
		$this->setTemplate('SaveProductAddonCallScript');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Save Product Info
	*********************************************************************************/
	private function executeSaveProductAddonEmail()
	{
		$this->CheckAuthentication();
		$this->ProductId			= $this->getRequestParameter('ProductId');
		$this->emailContent			= $this->getRequestParameter('emailContent');
		$this->setTemplate('SaveProductAddonEmail');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Checkout
	*********************************************************************************/
	private function executeCheckout()
	{
		$this->CheckAuthentication();
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Checkout" );
		$this->setTemplate('Checkout');


		if ($this->Action == 'GetPaymentContent') {
			$PaymentType = $_REQUEST['PaymentType'];
			$this->setLayout(false);

			switch ($this->PaymentType) {
				case 'STORED-VALUE':	return '_StoredValue'; 	exit; break;
				case 'CREDIT-CARD': 	return '_CreditCard'; 	exit; break;
				case 'INVOICE':			return '_Invoice'; 		exit; break;
				case 'DIRECT-BILL':		return '_DirectBill'; 	exit; break;
				default:
					return $this->renderText('Please select your desired payment method above... ');
			}
		}

		return '_Success'; exit;
	}

	/**
	* Private Function: CheckoutRight
	*********************************************************************************/
	private function executeCheckoutRight()
	{
		$this->CheckAuthentication();
		$this->setLayout(false);
		$this->setTemplate('CheckoutRight');

		return '_Success'; exit;
	}

	// private function executeProcessList()
	// {
	// 	$this->CheckAuthentication();
	// 	$this->getResponse()->setTitle( WEBSITE_TITLE ." - Review" );
	// 	$this->Us2Product = Us2ProductPeer::retrieveByPk($this->ProductId);
	// 	$this->setTemplate('OrderReview');

	// 	$customerID = intval($this->CurrentCustomerId);
	// 	$clientID = intval(CustomerPeer::GetClientByCustomer($customerID));
	// 	$userID = intval($this->CurrentAmmsAuthUserId);

	// 	$this->clientID = $clientID;
	// 	$this->customerID = $customerID;
	// 	$this->userID = $userID;

	// 	$Us2OrderProduct = Us2OrderProductPeer::retrieveByPk($this->OrderProductId);
	// 	$this->Us2OrderProduct = $Us2OrderProduct;

	// 	if ($this->Us2Product->getProductTypeId() == 1) {

	// 		$Result			= $this->CreateMailingList();

	// 		if (!empty($Result['upload_master_id'])) {
	// 			$UploadMasterId			= $Result['upload_master_id'];

	// 			$url	= "/?token=" . Convert::EncodeURL("Page=OrderReview&OrderProductId={$this->OrderProductId}&ProductId={$this->ProductId}&CampaignOrderId={$this->CampaignOrderId}&CampaignOrderItemId={$this->CampaignOrderItemId}&UploadMasterId={$Result['upload_master_id']}&UploadId={$Result['upload_id']}");
	// 			header("Location: $url");
	// 			exit;
	// 		}
	// 	}

	// 	$url	= "/?token=" . Convert::EncodeURL("Page=OrderReview&OrderProductId={$this->OrderProductId}&ProductId={$this->ProductId}&CampaignOrderId={$this->CampaignOrderId}&CampaignOrderItemId={$this->CampaignOrderItemId}");
	// 	header("Location: $url");
	// 	exit;

	// }



	/**
	* Private Function: Order Review
	*********************************************************************************/
	private function executeOrderReview()
	{
		$this->CheckAuthentication();
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Review" );
		$this->Us2Product = Us2ProductPeer::retrieveByPk($this->ProductId);
		$this->setTemplate('OrderReview');

		$customerID = intval($this->CurrentCustomerId);
		$clientID = intval(CustomerPeer::GetClientByCustomer($customerID));
		$userID = intval($this->CurrentAmmsAuthUserId);

		$this->clientID = $clientID;
		$this->customerID = $customerID;
		$this->userID = $userID;

		$Us2OrderProduct = Us2OrderProductPeer::retrieveByPk($this->OrderProductId);
		$this->Us2OrderProduct = $Us2OrderProduct;

		// If we are in the Asbury or CE store
		if (in_array(STORE_ID, array(ASBURY_STORE_ID, CE_STORE_ID))) {
			return $this->executeAsburyOrderReview();
		}

		$ch = new CyberHackney();

		switch ($_SERVER["REQUEST_METHOD"]) {
			case "GET":
				// Print
				if ($this->Us2Product->getProductTypeId() == 1) {

					$pulls = $ch->get("Pulls", array(
						"customer_id" => $clientID,
						"mailer_id" => $customerID,
						// "user_id" => $userID,
						"active_yn" => "Y"
					));

					// determine if order product's recipient list id is
					// in the list of currently available pulls
					$assigned = false;
					foreach ($pulls["results"] as $pull) {
						if ($pull["pull_master_id"] == $Us2OrderProduct->getRecipientListId()) {
							$assigned = true;
							$OrderPull		= $ch->get("Pulls", array(
								"pull_master_id" => $pull["pull_master_id"]
							));
							$this->OrderPull = reset($OrderPull["results"]);
							// echo "<pre>pull: ".print_r($pull, true)."\nOrderPull: ".print_r($this->OrderPull, true)."</pre>";
							break;
						}
					}

					// If we have a pull master id, set the value
					$PullMasterId	= $Us2OrderProduct->getRecipientListId();
					if (!empty($PullMasterId)) {
						$this->PullMasterId = $PullMasterId;
					}

					$this->assigned = $assigned;
					$this->Us2OrderProduct = $Us2OrderProduct;
					return '_Print';
				} else {
					unset($this->UploadMasterId);
				}

				return '_Custom';
			case "POST":
				try {

					// Order must be approved by checking the approved checkbox.
					if ($this->OrderApproved !== "on") {
						throw new Exception("Proof must be approved.", 403);
					}

					// Retrieve pull meta data to get the list quantity.
					$response = CyberHackneyRequest::get("Pulls?" . http_build_query(array(
						"pull_master_id" => $this->PullMasterId
					), "", "&"));
					$response->throw_for_status();

					$decoded = json_decode($response->body, true);
					if (is_null($decoded)) {
						throw new Exception("Not valid JSON", 500);
					}

					if (!array_key_exists("results", $decoded)) {
						throw new Exception("Response object did not contain an expected 'results' field.", 500);
					}

					$pull = reset($decoded["results"]);
					if (!array_key_exists("net_records", $pull)) {
						throw new Exception("No quantity on pull found.", 500);
					}

					// Pull quantity must exceed minimum order quantity
					$quantity = intval($pull["net_records"]);
					if ($quantity < $this->Us2Product->getMinimumOrderQty()) {
						throw new Exception("The minimum order quantity was not met.", 422);
					}

					// Before confirming the order, we want to check if this product
					// is associated with a callscript. The existence of such an association
					// implies that we should create, or prompt to create, a call center order
					// for this order product, without necessarily flagging the order for
					// fulfillment just yet.
					$conn = Propel::getConnection();
					$stmt = $conn->prepareStatement("
						SELECT
							client_id,
							product_id,
							script_id
						FROM callcenter_product_script
						WHERE client_id = ?
						AND product_id = ?
					");
					$stmt->setInt(1, $clientID);
					$stmt->setInt(2, $Us2OrderProduct->getProductId());
					$result = $stmt->executeQuery();

					// Fetch call center provider auth credentials
					$provider = "picos";
					$stmt = $conn->prepareStatement("
						SELECT *
						FROM callcenter_provider_auth
						JOIN callcenter_provider
							ON callcenter_provider.callcenter_provider_id = callcenter_provider_auth.callcenter_provider_id
						WHERE callcenter_provider.code = ?
						LIMIT 1
					");
					$stmt->setString(1, $provider);
					$auth = $stmt->executeQuery();
					if (!$auth->first()) {
						throw new Exception(sprintf("No provider authentication was found for '%s'", $provider));
					}

					if ($result->first()) {
						$response = CallCenterRequest::post("orders", array(), array(
							"order_product_id" => $this->OrderProductId,
							"script_id" => $result->getInt("script_id"),
							"list_id" => $this->PullMasterId,
							"active" => "false",
							"provider" => $provider,
							"token" => $auth->getString("token")
						));
						$response->throw_for_status();
					}

					// Update the pull's status to FILTER, a way of locking the pull
					// to prevent future modifications.
					$response = CyberHackneyRequest::put("Pulls", array(), array(
						"customer_id" => $clientID,
						"mailer_id" => $customerID,
						"pull_master_id" => $this->PullMasterId,
						"status" => "FILTER"
					));
					$response->throw_for_status();

					// Update the order product's creation date if one doesn't already exist
					$CreatedDate = $Us2OrderProduct->getCreatedDate();
					if (!$CreatedDate || $CreatedDate == '0000-00-00 00:00:00') {
						$Us2OrderProduct->setCreatedDate(date('Y-m-d H:i:s'));
					}

					// The order product is removed from draft status and has its
					// quantity, list, and list type set.
					$Us2OrderProduct->setRecipientListId($this->PullMasterId);
					$Us2OrderProduct->setRecipientTypeId(5);
					$Us2OrderProduct->setCustomerId($customerID);
					$Us2OrderProduct->setTotalQuan($quantity);
					$Us2OrderProduct->setIsDraftYn("N");
					$Us2OrderProduct->setIsOpenYn("N");
					$Us2OrderProduct->save();

					header("Content-Type: application/json");
					return $this->renderText(json_encode(array(
						"status" => true,
						"message" => "",
						"code" => 200
					)));
				} catch (Exception $e) {
					error_log(sprintf(
						"Error reviewing order (%d): %s \n%s",
						$e->getCode(),
						$e->getMessage(),
						$e->getTraceAsString()
					));
					header("Content-Type: application/json");
					return $this->renderText(json_encode(array(
						"status" => false,
						"message" => $e->getMessage(),
						"code" => $e->getCode()
					)));
				}
		} // end switch ($_SERVER["REQUEST_METHOD"])
	}

	/**
	* Private Function: Order Review
	*********************************************************************************/
	private function executeAsburyOrderReview()
	{
		$ListOrderProduct			= $this->GetConquestListOrderProduct($this->OrderProductId);

		$ExtraParamsXml				= $this->Us2OrderProduct->getExtraParamsXml();

		if (!empty($ExtraParamsXml)) {
			$ExtraParams				= json_decode($ExtraParamsXml, true);

			$this->CountDms				= $ExtraParams['CountDms'];
			$this->CountConquest		= $ExtraParams['CountConquest'];
			$this->TotalQuantity		= intval($this->CountDms) + intval($this->CountConquest);
		} else {
			$this->CountDms				= 0;
			$this->CountConquest		= 0;
			$this->TotalQuantity		= 0;
		}

		$this->Product				= Us2ProductPeer::retrieveByPk($this->ProductId);

		if ($this->Product->getProductTypeId() == 1) {

			$C = new Criteria();
			$C->add(Us2ProductWoPropsPeer::PRODUCT_ID, $this->Product->getUs2ProductTemplateId());

			$this->ProductWoProps		= Us2ProductWoPropsPeer::doSelectOne($C);

			if (!empty($this->ProductWoProps)) {
				$this->EnvelopeId			= $this->ProductWoProps->getEnvelopeId();
				if ($this->ProductWoProps->getEnvelopeId() > 0) {
					$Us2EnvelopeStyles			= Us2EnvelopeStylesPeer::retrieveByPk($this->ProductWoProps->getEnvelopeId());
					$this->EnvelopeStyle		= $Us2EnvelopeStyles->getEnvelopeDesc();
				} else {
					$this->EnvelopeStyle		= '';
				}
				$this->ProductSize			= $this->ProductWoProps->getFinalSize();
				$this->ProductColors		= $this->ProductWoProps->getBwOrColor();
				$this->PrintSides			= $this->ProductWoProps->getPrintedSides();
				$this->EnvelopeId			= $this->ProductWoProps->getEnvelopeId();
			} else {
				$this->ProductSize			= '';
				$this->ProductColors		= '';
				$this->PrintSides			= '';
				$this->EnvelopeId			= '';
				$this->EnvelopeStyle		= '';
			}

			// Wholesale is false because we are presenting this to the dealer/retail customer
			// Get the price of the mail piece
			$MailPrice			= $this->GetPrice($this->customerID, $this->Us2OrderProduct->getProductId(), $this->TotalQuantity, false);
			// Get the price for the mailing list
			$ListPrice			= $this->GetPrice($this->customerID, $ListOrderProduct->getProductId(), $this->CountConquest, false);

			$this->TotalPrice = $MailPrice + $ListPrice;
		}

		return "_Asbury";
	}


	/**
	* Private Function: Compliance
	*********************************************************************************/
	private function executeCompliance()
	{
		$this->setTemplate("Compliance");
		$Connection					= Propel::getConnection();

		// Create mailing list record
		$this->Us2OrderProduct		= Us2OrderProductPeer::retrieveByPk($this->OrderProductId);
		$Us2Product					= Us2ProductPeer::retrieveByPk($this->Us2OrderProduct->getProductId());

		// If it's a printable product
		if ($Us2Product->getProductTypeId() == 1) {
			$ExtraParamsXml				= $this->Us2OrderProduct->getExtraParamsXml();

			if (!empty($ExtraParamsXml)) {
				$ExtraParams				= json_decode($ExtraParamsXml, true);
				$MarketEvalRequestId		= $ExtraParams['MarketEvalRequestId'];
				$CountOptionDms				= $ExtraParams['CountOptionDms'];
				$CountDms					= $ExtraParams['CountDms'];
				$CountOptionConquest		= $ExtraParams['CountOptionConquest'];
				$CountConquest				= $ExtraParams['CountConquest'];

				$Query						= "INSERT INTO us2_order_product_mailing_list (order_product_id, dms_count_raw, conquest_count_raw, date_created) VALUES "
											. "( {$this->OrderProductId}, {$CountDms}, {$CountConquest}, NOW() ) "
											. "ON DUPLICATE KEY UPDATE "
											. "dms_count_raw = {$CountDms}, "
											. "conquest_count_raw = {$CountConquest}, "
											. "date_created = NOW()";

				$Connection->executeQuery($Query);
			}
		}

		// Create compliance record
		$Query							= "INSERT INTO us2_order_product_compliance (order_product_id, submitted_date, stage) VALUES "
										. "( {$this->OrderProductId}, NOW(), 'Compliance' ) "
										. "ON DUPLICATE KEY UPDATE "
										. "stage = 'Compliance'";

		$Connection->executeQuery($Query);

		// Send email notification data
		$OrderNotificationData			= $Us2Product->getOrderNotificationData();

		if (!empty($OrderNotificationData)) {
			$ProductId						= $Us2Product->getProductId();
			$ProductName					= $Us2Product->getName();
			$arrayOrderNotification			= unserialize($OrderNotificationData);
			unset($OrderNotificationData);
			$Customer						= CustomerPeer::retrieveByPk($this->CurrentCustomerId);
			$CustomerName					= $Customer->getName()." ($this->CurrentCustomerId)";

			$DistributorInfo				= "";

			// For CE store only
			if (STORE_ID == CE_STORE_ID) {
				$Query							= "SELECT client_id, display_name FROM mp_distributor "
												. "WHERE client_id = '{$this->CurrentClientId}'";

				$Rs								= $Connection->executeQuery($Query);
				while ($Rs->next()) {
					$row							= $Rs->getRow();
					$DistributorInfo				= "Distributor: {$row['display_name']} ({$row['client_id']})<br />";
				}
			}

			$Query							= "SELECT user_id, first_name, last_name "
											. "FROM sf_guard_user_profile "
											. "WHERE user_id = '{$this->AccessControl->UserId}'";

			$Rs								= $Connection->executeQuery($Query);

			$UserName						= '';
			while ($Rs->next()) {
				$row							= $Rs->getRow();
				$UserName						= "{$row['first_name']} {$row['last_name']} ({$row['user_id']})";
			}

			$Subject			= $_SERVER['HTTP_HOST'] . " - Compliance";
			$Body 			= "
				An order has just been submitted for compliance at " .$_SERVER['HTTP_HOST'] .".<br />
<br />
				<b>Details:</b><br />
				Received on: ".date('m/d/Y H:i:s a')."<br />
				IP Address: {$_SERVER['REMOTE_ADDR']}<br />
				{$DistributorInfo}
				Customer: {$CustomerName}<br />
				User: {$UserName}<br />
				Order Product ID: {$this->OrderProductId}<br />
				Product: {$ProductName} ({$ProductId})
				";

			foreach ($arrayOrderNotification as $OrderNotification) {
				// If email
				if ($OrderNotification['method'] == 1) {
					$ToAddress			= $OrderNotification['sendTo'];
					$this->sendMail($ToAddress, $Subject, $Body);
				}
			}
		}

		return "_Asbury";
	}


	// Assumes: $this->Us2OrderProduct is populated
	private function CreateMailingList() {
		$ExtraParamsXml = $this->Us2OrderProduct->getExtraParamsXml();
		$OrderProductId = $this->Us2OrderProduct->getOrderProductId();

		if (empty($ExtraParamsXml)) {
			// We can't process a list because we don't have the required information
		} else {
			$ExtraParams				= json_decode($ExtraParamsXml, true);
			$MarketEvalRequestId		= $ExtraParams['MarketEvalRequestId'];
			$CountOptionDms				= $ExtraParams['CountOptionDms'];
			$CountDms					= $ExtraParams['CountDms'];
			$CountOptionConquest		= $ExtraParams['CountOptionConquest'];
			$CountConquest				= $ExtraParams['CountConquest'];

			$MktEvalDms					= $this->GetMarketEval($OrderProductId, 'dms', 'sales', true);

			// Get the settings for the DMS portion of the list
			switch ($CountOptionDms) {
				case 'All':
					$MailingListDms		= $this->GetMailingListByMaxCount($MktEvalDms, 999999999, 'dms');
					break;

				case 'Count':
					$MailingListDms		= $this->GetMailingListByMaxCount($MktEvalDms, $CountDms, 'dms');
					break;

				case 'ZipCode':
					$MailingListDms		= $this->GetMailingListByZipCode($MktEvalDms, $ExtraParams['ZipCodeDms'], 'dms');
					break;

				default:
					$MailingListDms		= array();
			}

			$MktEvalConquest			= $this->GetMarketEval($OrderProductId, 'conquest', 'sales', true);

			// Get the settings for the Conquest portion of the list
			switch ($CountOptionConquest) {
				case 'All':
					$MailingListConquest	= $this->GetMailingListByMaxCount($MktEvalConquest, 999999999, 'conquest');
					break;

				case 'Count':
					$MailingListConquest	= $this->GetMailingListByMaxCount($MktEvalConquest, $CountConquest, 'conquest');
					break;

				case 'ZipCode':
					$MailingListConquest	= $this->GetMailingListByZipCode($MktEvalConquest, $ExtraParams['ZipCodeConquest'], 'conquest');
					break;

				default:
					$MailingListConquest = array();
			}

			$MailingList		= array_merge($MailingListDms, $MailingListConquest);

			// echo "<pre>";
			// echo "ExtraParams: " . print_r($ExtraParams, true);
			// echo "MailingListDms: " . print_r($MailingListDms, true);
			// echo "MailingListConquest: " . print_r($MailingListConquest, true);
			// echo "MailingList: " . print_r($MailingList, true);
			// exit;

			if (!empty($MailingList)) {

				$arrayHeader		= array("prefix","first","middle","last","address","suite","city","state","zip");

				$arrayConsumer		= array();
				foreach ($MailingList as $consumer) {
					$temp = array();
					foreach ($arrayHeader as $header) {
						$temp[]				= '"' . str_replace('"', '\"', $consumer[$header]) . '"';
					}
					$arrayConsumer[]	= implode(',', $temp);
				}
				$ConsumerData		= implode("\n", $arrayConsumer);
				unset($arrayConsumer);
				$Header				= implode(',', $arrayHeader) . "\n";

				$exportName			= $this->Us2OrderProduct->getOrderNotes();

				// Start output buffer to catch and discard what the CyberHackney class echoes out
				ob_start();

				$CyberHackney		= new CyberHackney();
				$Result				= $CyberHackney->ExportToCyberHackney(0, $this->clientID, $this->customerID, $exportName, $Header, $ConsumerData, $this->CurrentUserId);

				ob_end_clean();

				return $Result;
			} else {
				// TODO: Handle an empty mailing list.
			}
		}

	}


	private function GetFieldNameArray($DealerMakes, $Type) {
		// Create the array of field names based on eval type
		switch ($Type) {
			case 'dms':
				$arrayFieldName				= array('NEVER_SOLD', 'VEHICLE_AGE_2', 'VEHICLE_AGE_3', 'VEHICLE_AGE_4');
				break;

			case 'conquest':
				$arrayFieldName				= array();
				foreach ($DealerMakes as $make) {
					$arrayFieldName[]			= "SALES_MAKE_({$make})";
				}
				break;
		}

		return $arrayFieldName;
	}


	// Assumes: $this->Us2OrderProduct is populated
	private function GetMailingListByMaxCount($MktEvalList, $MaxCount, $Type) {
		// First, construct a list by zip codes
		$ZipCodeList		= array();
		foreach ($MktEvalList['Customers'] as $consumer) {
			if (!array_key_exists($consumer['zip'], $ZipCodeList)) {
				$ZipCodeList[$consumer['zip']]		= array();
			}

			$ZipCodeList[$consumer['zip']][]		= $consumer;
		}

		$MailingList		= array();
		$ZipCodeCounts		= array();
		// Now go around the zip code list,
		// picking off at most one consumer at a time until all zip code buckets are empty
		// Or we reach the max count.
		if ($MaxCount > 0) {
			// This outer loop exits when there are no remaining zip code arrays with elements
			do {
				$done = true;
				foreach ($ZipCodeList as $zip => &$arrayConsumer) {
					if (!array_key_exists($zip, $ZipCodeCounts)) {
						$ZipCodeCounts[$zip] = 1;
					} else {
						$ZipCodeCounts[$zip]++;
					}
					if (!empty($arrayConsumer)) {
						$done				= false;
						$MailingList[]		= array_shift($arrayConsumer);

						if (count($MailingList) >= $MaxCount) {
							// exit both the foreach and the do while loops
							break 2;
						}
					}
				}
			} while (!$done);
		}

		return $MailingList;
	}


	private function GetMailingListByZipCode($MktEvalList, $ZipCodeList, $Type) {
		$arrayZipCode = array();

		foreach ($ZipCodeList as $zipCode) {
			$arrayZipCode[]		= preg_replace('/[^0-9]/', '', $zipCode['name']);
		}

		$MailingList = array();
		foreach ($MktEvalList['Customers'] as $consumer) {
			if (in_array($consumer['zip'], $arrayZipCode)) {
				$MailingList[]		= $consumer;
			}
		}

		return $MailingList;
	}


	private function executeGetCustomers() {
		$ch = new CyberHackney();

		$data = array();
		if ($this->ClientID) {
			$data["customer_id"] = $this->ClientID;
		}

		$customers = $ch->get("Mailers", $data);
		return $this->renderText(json_encode($customers));
	}

	/**
	* Private Function: Order Summary
	*********************************************************************************/
	private function executeUploadManager()
	{
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));

		$this->DisplayCEClientSelector = true;

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Upload Manager" );
		$this->ActiveMenu = "Admin";
		$this->setTemplate('UploadManager');
		return '_Success'; exit;
	}

	/**
	* Private Function: Order Summary
	*********************************************************************************/
	private function executeOrderSummary()
	{
		$this->CheckAuthentication();
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Order Summary" );
		$this->setTemplate('OrderSummary');
		return '_Success'; exit;
	}

	/**
	* Private Function: Repeat last order
	*********************************************************************************/
	private function executeReorder()
	{
		$this->CheckAuthentication();
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Reorder" );
		$this->setTemplate('Reorder');
		return '_Success'; exit;
	}

	/**
	* Private Function: Cancel selected order product
	*********************************************************************************/
	private function executeCancel()
	{
		$this->CheckAuthentication();
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Cancel" );
		$this->setTemplate('Cancel');
		return '_Success'; exit;
	}

	/**
	* Private Function: Display gallery
	*********************************************************************************/
	private function executeGallery()
	{
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Gallery" );
		$this->setLayout('dynamic');
		$this->setTemplate('Gallery');
		return '_Success'; exit;
	}

	/**
	* Private Function: Order History
	*********************************************************************************/
	private function executeOrderHistory()
	{
		$this->CheckAuthentication();
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Order History" );
		$this->ActiveMenu = "My Dashboard";
		$this->setTemplate('OrderHistory');
		// If we are in the Asbury or CE store
		if (STORE_ID == ASBURY_STORE_ID) {
			return '_Asbury';
		}
		elseif (STORE_ID == CE_STORE_ID) {
			return '_CE';
		}
		return '_Success'; exit;
	}


	/**
	* Private Function: Password Changed
	*********************************************************************************/
	private function executePasswordChanged()
	{
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Password Changed" );
		$this->setTemplate('PasswordChanged');
		return '_Success'; exit;
	}

	/**
	* Private Function: Change Password
	*********************************************************************************/
	private function executeChangePassword()
	{
		$this->CheckAuthentication();
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Change Account Password" );
		$this->ActiveMenu = "My Account";
		$this->setTemplate('ChangePassword');
		return '_Success'; exit;
	}

	/**
	* Private Function: My Profile
	*********************************************************************************/
	private function executeMyProfile()
	{
		$this->CheckAuthentication();
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - My Profile" );
		$this->ActiveMenu = "My Dashboard";
		$this->setTemplate('MyProfile');
		return '_Success'; exit;
	}

	/**
	* Private Function: My Workspace
	*********************************************************************************/
	private function executeMyWorkspace()
	{
		$this->CheckAuthentication();

		if (!empty($this->Cancel)) {
				$Connection		= Propel::getConnection();

			$Debug = array();
			$success = 0;
			if ($this->OrderProductId) {

				// Cancel *only* the specified order_product_id or any children
				$Query	= "UPDATE us2_order_product "
						. "SET order_handling_status_id = 9 "
						. "WHERE order_product_id = '{$this->OrderProductId}' "
						. "OR parent_us2_order_product_id = '{$this->OrderProductId}'";
				$Debug[] = $Query;

				$success = $Connection->executeUpdate($Query);
			} elseif ($this->Cancel == "All") {

				// Cancel all order product IDs (including child lists)
				// for the current proxy customer and user *only*
				// that have *not* already been canceled
				// and have *not* been submitted for compliance

				$Query	= "SET SESSION group_concat_max_len = 10000000";
				$Debug[] = $Query;

				$Connection->executeQuery($Query);

				// If admin and no user is selected
				if ($this->AccessControl->hasGroup(array('ADMIN','STORE ADMIN'))) {

					$this->UsingUserId	= intval($this->UsingUserId);
					if ($this->UsingUserId == -1) {
						$QueryUserId = "";
					} else {
						$QueryUserId = "AND us2_order_product.created_by_user_id = {$this->UsingUserId} ";
					}

					// Get the list of ids for all users
					$Query	= "SELECT GROUP_CONCAT(us2_order_product.order_product_id SEPARATOR ',') AS order_product_ids "
							. "FROM us2_order_product "
							. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
							. "WHERE us2_order_product.customer_id = {$this->CurrentCustomerId} "
							. "AND us2_order_product.order_handling_status_id < 9 "
							. $QueryUserId
							. "AND us2_order_product_compliance.order_product_compliance_id IS NULL";
				} else {
					// Get the list of ids for this user
					$Query	= "SELECT GROUP_CONCAT(us2_order_product.order_product_id SEPARATOR ',') AS order_product_ids "
							. "FROM us2_order_product "
							. "LEFT JOIN us2_order_product_compliance ON us2_order_product.order_product_id = us2_order_product_compliance.order_product_id "
							. "WHERE us2_order_product.customer_id = {$this->CurrentCustomerId} "
							. "AND us2_order_product.created_by_user_id = {$this->CurrentUserId} "
							. "AND us2_order_product.order_handling_status_id < 9 "
							. "AND us2_order_product_compliance.order_product_compliance_id IS NULL";
				}
				$Debug[] = $Query;

				$Rs		= $Connection->executeQuery($Query);

				while ($Rs->next()) {
					$OrderProductIds = $Rs->get('order_product_ids');
				}

				if (!empty($OrderProductIds)) {
					// Do the cancel of either the original order product or any children
					$Query	= "UPDATE us2_order_product "
							. "SET order_handling_status_id = 9 "
							. "WHERE order_product_id IN ({$OrderProductIds}) "
							. "OR parent_us2_order_product_id IN ({$OrderProductIds})";
					$Debug[] = $Query;

					$success = $Connection->executeUpdate($Query);
				}
			}

			$result = array("success" => $success,
							"debug" => array(
								"Debug" => $Debug,
								"Cancel" => $this->Cancel,
								"OrderProductId" => $this->OrderProductId,
								"CurrentCustomerId" => $this->CurrentCustomerId,
								"CurrentUserId" => $this->CurrentUserId
							)
						);

			$this->setLayout(false);

			return $this->renderText(json_encode($result));
		}

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - My Workspace" );
		$this->ActiveMenu = "My Dashboard";

		$this->setTemplate('MyWorkspace');
		return '_Success'; exit;
	}

	/**
	* Private Function: My Cart
	*********************************************************************************/
	private function executeMyCart()
	{
		$this->CheckAuthentication();
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - My Order" );
		$this->ActiveMenu = "My Order";
		$this->setTemplate('MyCart');
		return '_Success'; exit;
	}

	/**
	* Private Function: Add Program
	*********************************************************************************/
	private function executeAddProgram()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');

		$this->SaveProgram				= $this->getRequestParameter('SaveProgram');
		$this->ErrorMessage				= array();

		if (!empty($this->SaveProgram)) {
			$this->CustomerId				= intval($this->getRequestParameter('CustomerId'));
			$this->Name						= trim($this->getRequestParameter('Name'));
			$this->Description				= trim($this->getRequestParameter('Description'));
			$this->Cycles					= intval($this->getRequestParameter('Cycles'));
			$this->CreatedByUserId			= $this->CurrentUserId;
			$arrayOrderNotification			= $this->getRequestParameter('sendTo');
			if (!empty($arrayOrderNotification)) {
				if (!is_array($arrayOrderNotification)) {
					$arrayOrderNotification			= array($arrayOrderNotification);
				}
				$arrayOrderNotification		= array_map("trim", $arrayOrderNotification);
				$this->arrayOrderNotificationData		= array();
				foreach ($arrayOrderNotification as $email) {
					if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
						$this->arrayOrderNotificationData[]	= $email;
					}
				}
			} else {
				$this->arrayOrderNotificationData = array();
			}

			if ($this->Name == '') {
				$this->ErrorMessage[]			= 'Please enter Program Name.';
				}
			if ($this->Cycles <= 0) {
				$this->ErrorMessage[]			= 'Please enter Number of Cycles greater than 0.';
			}

			if (empty($this->ErrorMessage)) {
				$Us2Campaign					= new Us2Campaign();
				$Us2Campaign->setStoreId(STORE_ID);
				$Us2Campaign->setClientId(CLIENT_ID);
				$Us2Campaign->setCustomerId($this->CustomerId);
				$Us2Campaign->setName($this->Name);
				$Us2Campaign->setDescription($this->Description);
				$Us2Campaign->setDurationCycles($this->Cycles);
				$Us2Campaign->setCreatedByUserId($this->CreatedByUserId);
				$Us2Campaign->setCreatedDate(date('Y-m-d H:i:s'));
				$Us2Campaign->setOrderNotificationData(serialize($this->arrayOrderNotificationData));
				$Us2Campaign->save();

				$url = '/?token=' . Convert::EncodeURL('Page=ProgramManager');
				header("Location: $url");
				exit;
			}
		}

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Add Program" );
		$this->setTemplate('EditProgram');
		return '_Success'; exit;
	}

	/**
	* Private Function: Edit Program
	*********************************************************************************/
	private function executeEditProgram()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');

		$this->SaveProgram				= $this->getRequestParameter('SaveProgram');
		$this->ErrorMessage				= array();

		if (!empty($this->SaveProgram)) {
			$this->CampaignId				= intval($this->getRequestParameter('CampaignId'));
			$this->CustomerId				= intval($this->getRequestParameter('CustomerId'));
			$this->Name						= trim($this->getRequestParameter('Name'));
			$this->Description				= trim($this->getRequestParameter('Description'));
			$this->Cycles					= intval($this->getRequestParameter('Cycles'));
			$this->CreatedByUserId			= $this->CurrentUserId;
			$arrayOrderNotification			= $this->getRequestParameter('sendTo');
			if (!empty($arrayOrderNotification)) {
				if (!is_array($arrayOrderNotification)) {
					$arrayOrderNotification			= array($arrayOrderNotification);
				}
				$arrayOrderNotification		= array_map("trim", $arrayOrderNotification);
				$this->arrayOrderNotificationData		= array();
				foreach ($arrayOrderNotification as $email) {
					if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
						$this->arrayOrderNotificationData[]	= $email;
					}
				}
			} else {
				$this->arrayOrderNotificationData = array();
			}

			if ($this->Name == '') {
				$this->ErrorMessage[]			= 'Please enter Program Name.';
				}
			if ($this->Cycles <= 0) {
				$this->ErrorMessage[]			= 'Please enter Number of Cycles greater than 0.';
			}

			if (empty($this->ErrorMessage)) {
				if (!empty($this->CampaignId)) {
					$Us2Campaign					= Us2CampaignPeer::retrieveByPk($this->CampaignId);
				} else {
					$Us2Campaign					= new Us2Campaign();
				}
				$Us2Campaign->setStoreId(STORE_ID);
				$Us2Campaign->setClientId(CLIENT_ID);
				$Us2Campaign->setCustomerId($this->CustomerId);
				$Us2Campaign->setName($this->Name);
				$Us2Campaign->setDescription($this->Description);
				$Us2Campaign->setDurationCycles($this->Cycles);
				$Us2Campaign->setUpdatedByUserId($this->CreatedByUserId);
				$Us2Campaign->setUpdatedDate(date('Y-m-d H:i:s'));
				$Us2Campaign->setOrderNotificationData(serialize($this->arrayOrderNotificationData));
				$Us2Campaign->save();

				$url = '/?token=' . Convert::EncodeURL('Page=ProgramManager');
				header("Location: $url");
				exit;
			}
		}

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Edit Program" );
		$this->setTemplate('EditProgram');
		return '_Success'; exit;
	}

	/**
	* Private Function: Add Product
	*********************************************************************************/
	private function executeAddProduct()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Add Product" );
		$this->setTemplate('AddProduct');
		return '_Success'; exit;
	}

	/**
	* Private Function: Add New Group
	*********************************************************************************/
	private function executeAddNewGroup()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');
		$this->setTemplate('AddNewGroup');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Register
	*********************************************************************************/
	private function executeRegister()
	{
		$this->getResponse()->setTitle( WEBSITE_TITLE .' | Register' );
		$this->setTemplate('RegisterNewAccount');
		return '_Success'; exit;
	}

	/**
	* Private Function: Add Customer
	*********************************************************************************/
	private function executeAddCustomer()
	{
		$this->getResponse()->setTitle( WEBSITE_TITLE .' | New Customer' );
		$this->setTemplate('AddCustomer');
		return '_Success'; exit;
	}

	/**
	* Private Function: Group Manager
	*********************************************************************************/
	private function executeGroupManager()
	{
		$this->getResponse()->setTitle( WEBSITE_TITLE .' | Group Manager' );

		$this->DisplayCEClientSelector = true;

		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));
		$this->ActiveMenu = "Admin";
		$this->setTemplate('GroupManager');
		return '_Success'; exit;
	}

	/**
	* Private Function: Sales Report
	*********************************************************************************/
	private function executeSalesReport()
	{
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));
		$this->getResponse()->setTitle( WEBSITE_TITLE .' | Sales Report' );
		$this->ActiveMenu = "Admin";
		$this->setTemplate('SalesReport');
		$this->DisplayCEClientSelector = true;
		// Dates will be submitted in m/d/Y format but must be converted to Y-m-d format
		$this->DateFrom			= $this->DateFrom ? date('Y-m-d', strtotime($this->DateFrom)) : date('Y-m-d', strtotime("-1 month"));
		$this->DateTo			= $this->DateTo ? date('Y-m-d', strtotime($this->DateTo)) : date('Y-m-d');
		return '_Success'; exit;
	}


	/**
	* Private Function: Product Category
	*********************************************************************************/
	private function executeProductCategory()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');
		$this->getResponse()->setTitle( WEBSITE_TITLE .' | Product Category' );
		$this->setTemplate('ProductCategory');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Save Product Category
	*********************************************************************************/
	private function executeSaveProductCategory()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');
		$this->setTemplate('SaveProductCategory');
		$this->setLayout(false);
		$this->Save = $this->getRequestParameter('Save');
		$this->ProductId = $this->getRequestParameter('ProductId');
		$this->ProductGroupId = $this->getRequestParameter('GroupId');
		return '_Success'; exit;
	}

	/**
	* Private Function: Save Order Notification
	*********************************************************************************/
	private function executeSaveOrderNotification()
	{
		$this->CheckAuthentication();
		$this->setTemplate('SaveOrderNotification');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Save Additional Order Info
	*********************************************************************************/
	private function executeSaveAdditionalOrderInfo()
	{
		$this->CheckAuthentication();
		$this->setTemplate('SaveAdditionalOrderInfo');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Save Order Product Additional Order Info
	*********************************************************************************/
	private function executeSaveOrderProductOrderInfo()
	{
		$this->CheckAuthentication();
		$this->setTemplate('SaveOrderProductOrderInfo');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Program Detail
	*********************************************************************************/
	private function executeProgramDetail()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');
		$this->getResponse()->setTitle( WEBSITE_TITLE .' | Program Setup' );

		$this->Action 			= $this->getRequestParameter('DetailAction', '');
		$this->ErrorMessage		= array();
		if ($this->Action == 'Save') {
			$this->CampaignId			= intval($this->getRequestParameter('CampaignId', '0'));
			$this->CampaignDetailId		= intval($this->getRequestParameter('CampaignDetailId', '0'));

			if (!empty($this->CampaignDetailId)) {
				$Us2CampaignDetail 			= Us2CampaignDetailPeer::retrieveByPk($this->CampaignDetailId);
				$Us2CampaignDetail->setUpdatedByUserId($this->CurrentUserId);
				$Us2CampaignDetail->setUpdatedDate(date('Y-m-d H:i:s'));
			} else {
				$Us2CampaignDetail 			= new Us2CampaignDetail();
				$Us2CampaignDetail->setCampaignId($this->CampaignId);
				$Us2CampaignDetail->setCreatedByUserId($this->CurrentUserId);
				$Us2CampaignDetail->setCreatedDate(date('Y-m-d H:i:s'));
			}

			$Cycle						= intval($this->getRequestParameter('Cycle', '0'));
			$Sequence					= intval($this->getRequestParameter('Sequence', '0'));
			$ProductId					= intval($this->getRequestParameter('ProductId', '0'));
			$Offset						= intval($this->getRequestParameter('Offset', '0'));
			$OffsetUnits				= intval($this->getRequestParameter('OffsetUnits', '0'));
			$Required					= intval($this->getRequestParameter('Required', '0'));

			// Validate the form before updating
			if ($Cycle <= 0) {
				$this->ErrorMessage[]	= 'Please select a Cycle.';
			}
			if ($Sequence == 0) {
				$this->ErrorMessage[]	= 'Please enter a Sequence number greater than 0.';
			}
			if ($ProductId <= 0) {
				$this->ErrorMessage[]	= 'Please select a Product.';
			}
			if ($Offset < 0) {
				$this->ErrorMessage[]	= 'Please enter an Offset equal to or greater than 0.';
			}
			if ($OffsetUnits == 0) {
				$this->ErrorMessage[]	= 'Please select an Offset Unit.';
			}

			// If there are no errors
			if (empty($this->ErrorMessage)) {
				$Us2CampaignDetail->setCycle($Cycle);
				$Us2CampaignDetail->setSequence($Sequence);
				$Us2CampaignDetail->setProductId($ProductId);
				$Us2CampaignDetail->setOffset($Offset);
				$Us2CampaignDetail->setOffsetUnits($OffsetUnits);
				$Us2CampaignDetail->setRequiredYn(!empty($Required) ? 'Y' : 'N');
				$Us2CampaignDetail->save();

				header("Location: /?token=" . Convert::EncodeURL("Page=ProgramDetail&CampaignId={$this->CampaignId}")); exit;
			}
		} elseif ($this->Action == 'Delete') {
			$this->CampaignId			= intval($this->getRequestParameter('CampaignId', '0'));
			$this->CampaignDetailId		= intval($this->getRequestParameter('CampaignDetailId', '0'));

			if (!empty($this->CampaignDetailId)) {
				$Us2CampaignDetail 			= Us2CampaignDetailPeer::retrieveByPk($this->CampaignDetailId);
				$Us2CampaignDetail->setUpdatedByUserId($this->CurrentUserId);
				$Us2CampaignDetail->setUpdatedDate(date('Y-m-d H:i:s'));
				$Us2CampaignDetail->setActiveYn('N');
				$Us2CampaignDetail->save();
			}

			header("Location: /?token=" . Convert::EncodeURL("Page=ProgramDetail&CampaignId={$this->CampaignId}")); exit;
		}

		$this->setTemplate('ProgramDetail');
		return '_Success'; exit;
	}

	/**
	* Private Function: Product Detail
	*********************************************************************************/
	private function executeProductDetail()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');
		$this->getResponse()->setTitle( WEBSITE_TITLE .' | Product Setup' );
		$this->setTemplate('ProductDetail');
		return '_Success'; exit;
	}

	/**
	* Private Function: Add Category
	*********************************************************************************/
	private function executeAddCategory()
	{
		$this->setTemplate('AddCategory');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Update Category Info
	*********************************************************************************/
	private function executeUpdateCategoryInfo()
	{
		$this->setTemplate('UpdateCategoryInfo');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Category Info
	*********************************************************************************/
	private function executeCategoryInfo()
	{
		$this->setTemplate('CategoryInfo');
		$this->setLayout(false);
		return '_Success'; exit;
	}

	/**
	* Private Function: Program Manager
	*********************************************************************************/
	private function executeProgramManager()
	{
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));

		$this->DisplayCEClientSelector = true;

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Program Manager" );
		$this->ActiveMenu = "Admin";
		$this->setTemplate('ProgramManager');
		$C = new Criteria();
		$C->add(Us2CampaignPeer::STORE_ID, STORE_ID);
		$C->add(Us2CampaignPeer::CLIENT_ID, CLIENT_ID);
		$C->add(Us2CampaignPeer::ACTIVE_YN, 'Y');
		$this->SearchCampaign = $this->getRequestParameter('SearchCampaign');
		if (!empty($this->SearchCampaign)) {
			$tempSearchCampaign = '%'.addslashes(stripslashes($this->SearchCampaign)).'%';
			$C2 = $C->getNewCriterion(Us2CampaignPeer::NAME, $tempSearchCampaign, Criteria::LIKE);
			$C2->addOr($C->getNewCriterion(Us2CampaignPeer::DESCRIPTION, $tempSearchCampaign, Criteria::LIKE));
			$C->addAnd($C2);
		}
		$this->arrayCampaign = Us2CampaignPeer::doSelect($C);
		if (empty($this->arrayCampaign)) {
			$this->arrayCampaign = array();
		}

		return '_Success'; exit;
	}

	/**
	* Private Function: Category Manager
	*********************************************************************************/
	private function executeCategoryManager()
	{
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));

		$this->DisplayCEClientSelector = true;

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Category Manager" );
		$this->ActiveMenu = "Admin";
		$this->setTemplate('CategoryManager');
		return '_Success'; exit;
	}

	/**
	* Private Function:
	*********************************************************************************/
	private function executeSelectMailingList()
	{
		$this->CheckAuthentication();
		$this->Us2Product = Us2ProductPeer::retrieveByPk($this->ProductId);

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Select Mailing List - ". $this->Us2Product->getName());
		$this->setTemplate('SelectMailingList');
		return '_Success'; exit;
	}

	/**
	* Private Function: Name Campaign
	*********************************************************************************/
	private function executeNameCampaign()
	{
		$this->CheckAuthentication();
		$this->Us2Product = Us2ProductPeer::retrieveByPk($this->ProductId);
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Name This Campaign - ". $this->Us2Product->getName());

		$this->PendingItems = Us2OrderProductPeer::GetPendingItems ($this->CurrentCustomerId, STORE_ID, $this->CurrentUserId);

		foreach ($this->PendingItems as $OrderProductId) {
			$ProductId = Us2OrderProductPeer::GetProductId($OrderProductId);
			if ($ProductId == $this->ProductId) {
				$this->setTemplate('NameCampaign');
				return '_Success'; exit;
			}
		}

		$this->setTemplate('NameCampaign');
		return '_Success';

		exit;
	}

	/**
	* Private Function: Start Campaign
	*********************************************************************************/
	private function executeStartCampaign() {
		$this->CheckAuthentication();

		// Get the old order product if it was in the encoded token string
		$OldOrderProductId	= @$this->OrderProductId;

		$OrderId			= Us2OrderPeer::GetLastIncompleteOrder($this->CurrentCustomerId, STORE_ID, $this->CurrentUserId);

		$Us2Product = Us2ProductPeer::retrieveByPk($this->ProductId);
		$OrderNotes = $Us2Product->getName() . date(' m/d/Y h:i A');

		$Us2OrderProduct = new Us2OrderProduct();
		$Us2OrderProduct->setOrderId($OrderId);
		$Us2OrderProduct->setProductId($this->ProductId);
		$Us2OrderProduct->setCreatedByUserId($this->CurrentUserId);
		$Us2OrderProduct->setCreatedDate(date('Y-m-d H:i:s'));
		$Us2OrderProduct->setCustomerId($this->CurrentCustomerId);
		$Us2OrderProduct->setOrderNotes($OrderNotes);
		$Us2OrderProduct->save();

		$this->OrderProductId = $Us2OrderProduct->getOrderProductId();

		// If we are in the Asbury or CE store
		if (in_array(STORE_ID, array(ASBURY_STORE_ID, CE_STORE_ID))) {
			// Clone order product dial values
			Us2OrderProductPeer::CloneOrderProductDialValues($OldOrderProductId, $this->OrderProductId);
		}

		$redirect = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"];
		return $this->redirect($redirect . "/?token=" . Convert::EncodeURL(http_build_query(array(
			"Page" => "CustomizeOrder",
			"BuyAsIs" => '1',
			"ProductId" => $this->ProductId,
			"OrderProductId" => $this->OrderProductId
		), "", "&")));
	}

	/**
	* Private Function: Customize Order
	*********************************************************************************/
	private function executeCustomizeOrder()
	{
		$this->CheckAuthentication();
		if (empty($this->OrderProductId)) {
			$this->OrderProductId = $this->getRequestParameter('OrderProductId');
		}

		if (empty($this->CampaignOrderId)) {
			// Get the current open order
			$this->OrderId = Us2OrderPeer::GetLastIncompleteOrder($this->CurrentCustomerId, STORE_ID, $this->CurrentUserId);
		} else {
			$this->OrderId = Us2OrderPeer::GetLastCampaignOrder($this->CurrentCustomerId, STORE_ID, $this->CurrentUserId);
		}

		// Make an array of pending order products with this same product id
		$PendingOrderProductIds = Us2OrderProductPeer::GetPendingItems ($this->CurrentCustomerId, STORE_ID, $this->CurrentUserId);

		$this->PendingOrderProducts = array();
		foreach ($PendingOrderProductIds as $OrderProductId) {
			$Us2OrderProduct = Us2OrderProductPeer::retrieveByPk($OrderProductId);
			$_ProductId = $Us2OrderProduct->getProductId();
			if ($this->ProductId != $_ProductId) {
				continue;
			}
			$Us2Product = Us2ProductPeer::retrieveByPk($_ProductId);
			$SmallImageId = $Us2Product->getSmallImageId();
			$Us2Image = Us2ImagePeer::retrieveByPk($SmallImageId);
			if (is_object($Us2Image)) {
				$Image = '<img style="max-width: 75px" src="/?token=' . Convert::EncodeURL(urldecode(http_build_query(array(
					"Page" => "ProductImage",
					"URL" => $Us2Image->getPreviewUrl()
				), "", "&"))) . '"/>';
			} else {
				$Image = '';
			}
			$this->PendingOrderProducts[] = array(
				'Image' => $Image,
				'Date' => date('F d, Y g:iA', strtotime($Us2OrderProduct->getCreatedDate())),
				'Name' => Us2ProductPeer::GetNameById($Us2OrderProduct->getProductId()),
				'OrderNotes' => $Us2OrderProduct->getOrderNotes(),
				'Continue' => Convert::EncodeURL("Page=CustomizeOrder&OrderProductId={$OrderProductId}&ProductId={$Us2OrderProduct->getProductId()}"),
				'Delete' => ''
			);
		}

		// Load the order product if user is modifying an order, otherwise create a new order
		if ($this->OrderProductId) {
			$this->Us2OrderProduct = Us2OrderProductPeer::retrieveByPk($this->OrderProductId);
		} else {
			$this->Us2OrderProduct = new Us2OrderProduct();
			$this->Us2OrderProduct->setOrderId($this->OrderId);
			$this->Us2OrderProduct->setProductId($this->ProductId);
			$this->Us2OrderProduct->setCreatedByUserId($this->CurrentUserId);
			$this->Us2OrderProduct->setCreatedDate(date('Y-m-d H:i:s'));
			$this->Us2OrderProduct->setCustomerId($this->CurrentCustomerId);
			$this->Us2OrderProduct->setOrderNotes($this->OrderNote);
			$this->Us2OrderProduct->save();

			$this->OrderProductId = $this->Us2OrderProduct->getOrderProductId();
		}
		// If we didn't get a product ID, get it from the order product
		if (empty($this->ProductId)) {
			$this->ProductId = $this->Us2OrderProduct->getProductId();
		}
		$this->Us2Product = Us2ProductPeer::retrieveByPk($this->ProductId);
		$this->getResponse()->setTitle(WEBSITE_TITLE . " - Customize Order - " . $this->Us2Product->getName());

		// 1 == PRINT
		if ($this->Us2Product->getProductTypeId() == 1) {
			$customerID = intval($this->CurrentCustomerId);
			$clientID = intval(CustomerPeer::GetClientByCustomer($customerID));
			$userID = intval($this->CurrentAmmsAuthUserId);

			$ch = new CyberHackney();

			// Fetch clients
			$clients = $ch->get("Customers");

			// Fetch customers
			$customers = $ch->get("Mailers", array(
				"version" => "1.01",
				"customer_id" => $clientID
			));
			$customers = $customers["results"];

			// Fetch pulls
			$pulls = $ch->get("Pulls", array(
				"customer_id" => $clientID,
				"mailer_id" => $customerID,
				"user_id" => $userID,
				"active_yn" => "Y"
			));

			$this->assigned = null;
			if ($this->Us2OrderProduct->getRecipientListId() > 0) {
				$this->assigned = $ch->get("Pulls", array(
					"pull_master_id" => $this->Us2OrderProduct->getRecipientListId()
				));
				$this->assigned = $this->assigned["results"][0];
			}

			// Template vars
			$this->clientID = $clientID;
			$this->customerID = $customerID;
			$this->userID = $userID;
			$this->isAdmin = $this->AccessControl->hasGroup(array('ADMIN', 'STORE ADMIN'));
			$this->clients = $clients;
			$this->customers = $customers;
			$this->pulls = $pulls["results"];

			$this->setTemplate('CustomizeOrder_AllInOne_WithAutosave');

			$this->Zipcodes = array('dms' => array(), 'conquest' => array());

			$MktEvalDms						= $this->GetMarketEval($this->OrderProductId, 'dms', 'sales');
			$this->MarketEvalRequestId		= $MktEvalDms['MarketEvalRequestId'];
			$TotalDms						= 0;
			foreach ($MktEvalDms['Customers'] as $eval) {
				if (!array_key_exists($eval['zip'], $this->Zipcodes['dms'])) {
					$this->Zipcodes['dms'][$eval['zip']] = array(
							'city'		=> "{$eval['city']}, {$eval['state']}",
							'distance'	=> number_format($eval['distance'], 3),
							'count'		=> 1
						);
				} else {
					$this->Zipcodes['dms'][$eval['zip']]['count']++;
				}
				$TotalDms++;
			}

			$MktEvalConquest				= $this->GetMarketEval($this->OrderProductId, 'conquest', 'sales');
			$TotalConquest					= 0;
			foreach ($MktEvalConquest['Customers'] as $eval) {
				if (!array_key_exists($eval['zip'], $this->Zipcodes['conquest'])) {
					$this->Zipcodes['conquest'][$eval['zip']] = array(
							'city'		=> "{$eval['city']}, {$eval['state']}",
							'distance'	=> number_format($eval['distance'], 3),
							'count'		=> 1
						);
				} else {
					$this->Zipcodes['conquest'][$eval['zip']]['count']++;
				}
				$TotalConquest++;
			}

			$this->ListNames = array(
				'database'		=> $TotalDms,
				'conquest'		=> $TotalConquest,
				'total'			=> $TotalDms + $TotalConquest
			);
			// If we are in the Asbury or CE store
			if (in_array(STORE_ID, array(ASBURY_STORE_ID, CE_STORE_ID))) {
				return "_Asbury_v2";
			}

			return '_Print';
		}
		elseif($this->Us2Product->getProductTypeId() == 6){
			$price = $this->Us2OrderProduct->getProductUnitPrice();
			if(empty($price)){
				$price = self::GetPrice($this->CurrentCustomerId, $this->Us2OrderProduct->getProductId(), 1);
				$this->Us2OrderProduct->setProductUnitPrice($price);
			}


			$customerID = intval($this->CurrentCustomerId);
			$clientID = intval(CustomerPeer::GetClientByCustomer($customerID));
			$userID = intval($this->CurrentAmmsAuthUserId);

			$ch = new CyberHackney();

			// Fetch clients
			$clients = $ch->get("Customers");

			// Fetch customers
			$customers = $ch->get("Mailers", array(
				"version" => "1.01",
				"customer_id" => $clientID
			));
			$customers = $customers["results"];





			// Template vars
			$this->clientID = $clientID;
			$this->customerID = $customerID;
			$this->userID = $userID;
			$this->isAdmin = $this->AccessControl->hasGroup(array('ADMIN', 'STORE ADMIN'));
			$this->clients = $clients;
			$this->customers = $customers;

			$this->setTemplate('CustomizeOrder_AllInOne_WithAutosave');






			// If we are in the Asbury or CE store
			if (in_array(STORE_ID, array(ASBURY_STORE_ID, CE_STORE_ID))) {
				return "_Asbury_NonMailable";
			}

			return '_Print';
		}
		else {
			$this->setTemplate('CustomizeOrder');
			return '_Custom';
		}

		exit;
	}


	// Pass in OrderProductId to get customer and client. Duh!
	private function GetMarketEval($OrderProductId, $MarketType='', $FilterType='', $UploadList=false)
	{
		$Connection 	= Propel::getConnection();

		$Query	= "SELECT us2_order_product.customer_id AS customer_id, customer.client_id AS client_id "
				. "FROM us2_order_product "
				. "LEFT JOIN customer ON us2_order_product.customer_id = customer.customer_id "
				. "WHERE us2_order_product.order_product_id = {$OrderProductId}";

		$Rs 			= $Connection->executeQuery($Query);

		while ($Rs->next()) {
			$row			= $Rs->getRow();
		}

		if (!empty($row)) {
			$ParamMarketType = !empty($MarketType) ? "&market_type={$MarketType}" : '';
			$ParamFilterType = !empty($FilterType) ? "&filter_type={$FilterType}" : '';
			$UploadList = $UploadList ? "&upload_list=1" : '';
			$url = "marketeval.ammscore.com/customers?customer_id={$row['client_id']}&mailer_id={$row['customer_id']}{$ParamMarketType}{$ParamFilterType}{$UploadList}";
			$result = $this->curlGet($url);
			if (!empty($result)) {
				try {
					// Dereference the array to get rid of the market eval request id
					return reset(json_decode($result, true));
				} catch (Exception $e) {}
			}
		}

		// Return an empty array if it's empty or malformed JSON.
		return array();
	}


	/**
	* Private Function: View Product
	*********************************************************************************/
	private function executeViewProduct()
	{
		$this->Us2Product = Us2ProductPeer::retrieveByPk($this->ProductId);

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - ". $this->Us2Product->getName());
		$this->setTemplate('ViewProduct');
		return '_Success'; exit;
	}

	/**
	* Private Function: View Campaign
	*********************************************************************************/
	private function executeViewCampaign()
	{
		$this->CheckAuthentication();
		$conn = Propel::getConnection();

		// If CompleteOrderItem is set, we came from proof approval,
		// so mark that item configured before we do anything else.
		if (!empty($this->CompleteOrderItem)) {
			// Campaign order item stage id:
			// 1	Item created, pending configuration
			// 2	Item configured
			// 9	Item canceled
			$Us2CampaignOrderItem			= Us2CampaignOrderItemPeer::retrieveByPk($this->CompleteOrderItem);
			$Us2CampaignOrderItem->setStageId(2);
			$Us2CampaignOrderItem->save();
		}

		// See if we have an open campaign
		$C = new Criteria();
		$C->add(Us2CampaignOrderPeer::CAMPAIGN_ID, $this->CampaignId);
		$C->add(Us2CampaignOrderPeer::CUSTOMER_ID, $this->CurrentCustomerId);
		// Campaign order handling status id:
		// 1	Campaign order created, pending configuration of items
		// 2	All items configured, ready to start
		// 9	Campaign order canceled
		$C->add(Us2CampaignOrderPeer::ORDER_HANDLING_STATUS_ID, 1);
		$C->addDescendingOrderByColumn(Us2CampaignOrderPeer::CAMPAIGN_ORDER_ID);

		$this->Us2CampaignOrder				= Us2CampaignOrderPeer::doSelectOne($C);

		if (!empty($this->Us2CampaignOrder)) {
			$this->Us2CampaignOrderId			= $this->Us2CampaignOrder->getCampaignOrderId();
			$Us2CampaignOrderItems				= Us2CampaignOrderItemPeer::retrieveByCampaignOrderId($this->Us2CampaignOrder->getCampaignOrderId());
			$this->Us2CampaignOrderItems		= array();
			foreach ($Us2CampaignOrderItems as $Us2CampaignOrderItem) {
				$this->Us2CampaignOrderItems[$Us2CampaignOrderItem->getCampaignDetailId()]	= $Us2CampaignOrderItem;
			}
		}

		$this->OrderCampaign = $this->getRequestParameter('OrderCampaign');
		if (!empty($this->OrderCampaign)) {
			$this->CampaignId				= $this->getRequestParameter('CampaignId');
			$this->MailCampaign				= $this->getRequestParameter('MailCampaign');
			$this->PhoneCampaign			= $this->getRequestParameter('PhoneCampaign');
			$this->EmailCampaign			= $this->getRequestParameter('EmailCampaign');
			$this->OrderNotes				= $this->getRequestParameter('OrderNotes');
			$this->PullMasterId				= $this->getRequestParameter('PullMasterId');

			// If at least one item was ordered
			if (!empty($this->MailCampaign)) {
				$Us2CampaignOrder				= new Us2CampaignOrder();
				$Us2CampaignOrderItems			= array();
				$ClientId						= CustomerPeer::GetClientByCustomer($this->CurrentCustomerId);

				// Get last campaign order ID
				$OrderId						= Us2OrderPeer::GetLastCampaignOrder($this->CurrentCustomerId, STORE_ID, $this->CurrentUserId);

				$Us2CampaignOrder->setCampaignId($this->CampaignId);
				$Us2CampaignOrder->setCustomerId($this->CurrentCustomerId);
				$Us2CampaignOrder->setClientId($ClientId);
				$Us2CampaignOrder->setOrderHandlingStatusId(1);
				$Us2CampaignOrder->setCreatedByUserId($this->CurrentUserId);
				$Us2CampaignOrder->setCreatedDate(date('Y-m-d H:i:s'));
				$Us2CampaignOrder->setOrderId($OrderId);
				$Us2CampaignOrder->setOrderNotes($this->OrderNotes);
				if (!empty($this->PullMasterId)) {
					$Us2CampaignOrder->setRecipientListId($this->PullMasterId);
					$Us2CampaignOrder->setRecipientTypeId(5);	// Cyberhackney pull master id
				}
				$Us2CampaignOrder->save();
				$this->Us2CampaignOrderId		= $Us2CampaignOrder->getCampaignOrderId();

				// All campaigns must include a direct mail campaign,
				// so go through the mail campaign ids and test for one of the optional pieces.
				foreach ($this->MailCampaign as $CampaignDetailId) {
					$Us2CampaignDetail		= Us2CampaignDetailPeer::retrieveByPk($CampaignDetailId);

					$data 					= array();
					if (in_array($CampaignDetailId, $this->PhoneCampaign)) {
						$data['IncludePhoneCampaign']		= '1';
					} else {
						$data['IncludePhoneCampaign']		= '0';
					}

					if (in_array($CampaignDetailId, $this->EmailCampaign)) {
						$data['IncludeEmailCampaign']		= '1';
					} else {
						$data['IncludeEmailCampaign']		= '0';
					}

					// Create the order product and assign it to the campaign order
					$Us2OrderProduct = new Us2OrderProduct();
					$Us2OrderProduct->setOrderId ($OrderId);
					$Us2OrderProduct->setProductId ($Us2CampaignDetail->getProductId());
					$Us2OrderProduct->setCreatedByUserId($this->CurrentUserId);
					$Us2OrderProduct->setCreatedDate(date('Y-m-d H:i:s'));
					$Us2OrderProduct->setCustomerId ($this->CurrentCustomerId);
					$Us2OrderProduct->setOrderNotes($OrderNotes);
					$result = $Us2OrderProduct->save();

					$Us2CampaignOrderItem	= new Us2CampaignOrderItem();

					$Us2CampaignOrderItem->setCampaignOrderId($this->Us2CampaignOrderId);
					$Us2CampaignOrderItem->setCampaignDetailId($CampaignDetailId);
					$Us2CampaignOrderItem->setCreatedByUserId($this->CurrentUserId);
					$Us2CampaignOrderItem->setCreatedDate(date('Y-m-d H:i:s'));
					$Us2CampaignOrderItem->setData(serialize($data));
					// Campaign order item stage id:
					// 1	Item created, awaiting configuration
					// 2	Item configured
					// 3	Item completed
					// 9	Item canceled
					$Us2CampaignOrderItem->setStageId(1);				// initial entry
					$Us2CampaignOrderItem->setOrderProductId($Us2OrderProduct->getOrderProductId());
					$Us2CampaignOrderItem->save();
					$Us2CampaignOrderItems[$CampaignDetailId]	= $Us2CampaignOrderItem;
				}

				$this->Us2CampaignOrder			= $Us2CampaignOrder;
				$this->Us2CampaignOrderItems	= $Us2CampaignOrderItems;
			}

			header("Location: {$_SERVER['REQUEST_URI']}");
			exit;
		}

		$this->Us2Campaign 			= Us2CampaignPeer::retrieveByPk($this->CampaignId);
		$this->Us2CampaignDetails	= Us2CampaignDetailPeer::retrieveByCampaignId($this->CampaignId);
		$arrayProductId 			= array();

		foreach ($this->Us2CampaignDetails as $CampaignDetail) {
			$arrayProductId[]			= $CampaignDetail->getProductId();
		}

		$arrayProductId				= array_unique($arrayProductId);

		$stmt = $conn->prepareStatement("
			SELECT
				us2_campaign_detail.campaign_detail_id,
				us2_product.product_id,
				us2_product.name as product_name,
				us2_product.small_image_id,
				us2_product.large_image_id,
				us2_image1.preview_url as small_image_url,
				us2_image2.preview_url as large_image_url
			FROM us2_campaign_detail
			LEFT JOIN us2_product ON us2_campaign_detail.product_id = us2_product.product_id
			LEFT JOIN us2_image AS us2_image1 ON us2_product.small_image_id = us2_image1.us2_image_id
			LEFT JOIN us2_image AS us2_image2 ON us2_product.small_image_id = us2_image2.us2_image_id
			WHERE us2_campaign_detail.campaign_id = ?
			AND us2_campaign_detail.active_yn = 'Y'
			ORDER BY us2_campaign_detail.cycle ASC, us2_campaign_detail.active_yn DESC, us2_campaign_detail.sequence ASC
		");
		$stmt->setInt(1, $this->CampaignId);

		$result = $stmt->executeQuery();

		$this->arrayCampaignDetailImages = array();
		while ($result->next()) {
			$row															= $result->getRow();
			$this->arrayCampaignDetailImages[$row['campaign_detail_id']]	= $row;
		}

		$this->getResponse()->setTitle(WEBSITE_TITLE ." - ". $this->Us2Campaign->getName());

		$customerID				= $this->CurrentCustomerId;
		$clientID				= CustomerPeer::GetClientByCustomer($customerID);
		// $userID					= $this->AccessControl->AmmsAuthUserId;
		$userID					= $this->CurrentAmmsAuthUserId;

		$ch = new CyberHackney();

		// Fetch clients
		$clients = $ch->get("Customers");

		// Fetch customers
		$customers = $ch->get("Mailers", array(
			"version" => "1.01",
			"customer_id" => $clientID
		));
		$customers = $customers["results"];

		// Fetch pulls
		$pulls = $ch->get("Pulls", array(
			"customer_id" => $clientID,
			"mailer_id" => $customerID,
			"user_id" => $userID,
			"active_yn" => "Y"
		));

		$assigned = $ch->get("Pulls", array(
			"pull_master_id" => 1
		));

		// Template vars
		$this->clientID = $clientID;
		$this->customerID = $customerID;
		$this->userID = $userID;
		$this->isAdmin = $this->AccessControl->hasGroup(array('ADMIN', 'STORE ADMIN'));
		$this->clients = $clients;
		$this->customers = $customers;
		$this->pulls = $pulls["results"];

		$this->setTemplate('ViewCampaign');
		return '_Success'; exit;
	}

	/**
	* Private Function: Coupon Manager
	*********************************************************************************/
	private function executeCouponManager()
	{
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));

		$this->DisplayCEClientSelector = true;

		$arrayCouponList = array();

		// Get some basic info for the list of coupons
		$C = new Criteria();
		$C->addSelectColumn(Us2CouponPeer::US2_COUPON_ID);
		$C->addSelectColumn(Us2CouponPeer::COUPON_CODE);
		$C->addSelectColumn(Us2CouponPeer::CUSTOMER_ID);
		$C->addSelectColumn(Us2CouponPeer::PRODUCT_ID);
		$C->addSelectColumn(Us2CouponPeer::US2_PRODUCT_GROUP_ID);
		$C->addSelectColumn(Us2CouponPeer::PROGRAM_ID);
		$C->addSelectColumn(Us2CouponPeer::APPLIES_TO_TYPE);
		$C->addSelectColumn(Us2CouponPeer::APPLIES_TO_ID);
		$C->addSelectColumn(Us2CouponPeer::COUPON_TYPE_ID);
		$C->addSelectColumn(Us2CouponPeer::COUPON_VALUE);
		$C->addSelectColumn(Us2CouponPeer::INVOICE_QUAN_LIMIT_MIN);
		$C->addSelectColumn(Us2CouponPeer::INVOICE_QUAN_LIMIT_MAX);
		$C->addSelectColumn(Us2CouponPeer::USAGE_COUNT);
		$C->addSelectColumn(Us2CouponPeer::USAGE_MAX_COUNT);
		$C->addSelectColumn(Us2CouponPeer::START_DATE);
		$C->addSelectColumn(Us2CouponPeer::END_DATE);
		$C->addSelectColumn(Us2CouponPeer::USAGE_MODE);
		$C->addSelectColumn(Us2CouponPeer::CREATED_BY_USER_ID);
		$C->addSelectColumn(Us2CouponPeer::CREATED_DATE);
		$C->addSelectColumn(Us2CouponPeer::UPDATED_BY_USER_ID);
		$C->addSelectColumn(Us2CouponPeer::UPDATED_DATE);
		$C->addSelectColumn(CustomerPeer::NAME);
		$C->addSelectColumn(Us2ProductPeer::NAME);
		$C->addSelectColumn(Us2ProductGroupPeer::NAME);
		$C->addJoin(Us2CouponPeer::CUSTOMER_ID, CustomerPeer::CUSTOMER_ID, Criteria::LEFT_JOIN);
		$C->addJoin(Us2CouponPeer::PRODUCT_ID, Us2ProductPeer::PRODUCT_ID, Criteria::LEFT_JOIN);
		$C->addJoin(Us2CouponPeer::US2_PRODUCT_GROUP_ID, Us2ProductGroupPeer::US2_PRODUCT_GROUP_ID, Criteria::LEFT_JOIN);
		$C->addAnd(Us2CouponPeer::CLIENT_ID, CLIENT_ID);

		$Rs = Us2CouponPeer::doSelectRs($C);

		while ($Rs->next()) {
			$arrayCouponList[$Rs->get(1)] = array(
				'code'					=> $Rs->get(2),
				'customer_id'			=> $Rs->get(3),
				'product_id'			=> $Rs->get(4),
				'category_id'			=> $Rs->get(5),
				'program_id'			=> $Rs->get(6),
				'applies_to_type'		=> $Rs->get(7),
				'applies_to_id'			=> $Rs->get(8),
				'coupon_type_id'		=> $Rs->get(9),
				'coupon_value'			=> $Rs->get(10),
				'invoice_min'			=> $Rs->get(11),
				'invoice_max'			=> $Rs->get(12),
				'usage'					=> $Rs->get(13),
				'usage_max'				=> $Rs->get(14),
				'start'					=> $Rs->get(15),
				'end'					=> $Rs->get(16),
				'mode'					=> $Rs->get(17),
				'created_by_user_id'	=> $Rs->get(18),
				'created_date'			=> $Rs->get(19),
				'updated_by_user_id'	=> $Rs->get(20),
				'updated_date'			=> $Rs->get(21),
				'customer'				=> $Rs->get(22) ? $Rs->get(22) : 'Any',
				'product'				=> $Rs->get(23) ? $Rs->get(23) : 'Any',
				'category'				=> $Rs->get(24) ? $Rs->get(24) : 'Any'
			);
		}

		$this->arrayCouponList = $arrayCouponList;

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Coupon Manager" );
		$this->ActiveMenu = "Admin";
		$this->setTemplate('CouponManager');
		return '_Success'; exit;
	}

	/**
	* Private Function: Coupon Detail
	*********************************************************************************/
	private function executeCouponDetail()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');
		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Coupon Detail" );
		$this->ActiveMenu = "Admin";
		$this->setTemplate('CouponDetail');

		return '_Success'; exit;
	}

	/**
	* Private Function: Add Coupon
	*********************************************************************************/
	private function executeAddCoupon()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');

		$this->AddCoupon 				= $this->getRequestParameter('AddCoupon');

		if (!empty($this->AddCoupon)) {
			$this->CouponCode 				= $this->getRequestParameter('CouponCode');
			$this->CustomerId 				= $this->getRequestParameter('CustomerId');
			$this->ProductId 				= $this->getRequestParameter('ProductId');
			$this->Us2ProductGroupId 		= $this->getRequestParameter('Us2ProductGroupId');
			$this->ProgramId 				= $this->getRequestParameter('ProgramId');
			$this->AppliesToType 			= $this->getRequestParameter('AppliesToType');
			$this->AppliesToId 				= $this->getRequestParameter('AppliesToId');
			$this->CouponTypeId 			= $this->getRequestParameter('CouponTypeId');
			$this->CouponValue 				= $this->getRequestParameter('CouponValue');
			$this->InvoiceQuanLimitMin 		= $this->getRequestParameter('InvoiceQuanLimitMin');
			$this->InvoiceQuanLimitMax 		= $this->getRequestParameter('InvoiceQuanLimitMax');
			$this->UsageMaxCount 			= $this->getRequestParameter('UsageMaxCount');
			$this->StartDate 				= $this->getRequestParameter('StartDate');
			$this->EndDate 					= $this->getRequestParameter('EndDate');
			$this->UsageMode 				= $this->getRequestParameter('UsageMode');
			$this->CreatedByUserId 			= $this->CurrentUserId;

			$Us2Coupon 						= new Us2Coupon();
			$Us2Coupon->setCouponCode($this->CouponCode);
			$Us2Coupon->setClientId(CLIENT_ID);
			$Us2Coupon->setCustomerId($this->CustomerId);
			$Us2Coupon->setProductId($this->ProductId);
			$Us2Coupon->setUs2ProductGroupId($this->Us2ProductGroupId);
			$Us2Coupon->setProgramId($this->ProgramId);
			$Us2Coupon->setAppliesToType($this->AppliesToType);
			$Us2Coupon->setAppliesToId($this->AppliesToId);
			$Us2Coupon->setCouponTypeId($this->CouponTypeId);
			if (intval($this->CouponTypeId) == 1) {			// percent
				$Us2Coupon->setCouponValue(floatval($this->CouponValue)/100);
			} else {										// amount
				$Us2Coupon->setCouponValue(floatval($this->CouponValue));
			}
			$Us2Coupon->setInvoiceQuanLimitMin($this->InvoiceQuanLimitMin);
			$Us2Coupon->setInvoiceQuanLimitMax($this->InvoiceQuanLimitMax);
			$Us2Coupon->setUsageCount(0);
			$Us2Coupon->setUsageMaxCount($this->UsageMaxCount);
			$Us2Coupon->setStartDate(date('Y-m-d', strtotime($this->StartDate)));
			$Us2Coupon->setEndDate(date('Y-m-d', strtotime($this->EndDate)));
			$Us2Coupon->setUsageMode($this->UsageMode);
			$Us2Coupon->setCreatedByUserId($this->CurrentUserId);
			$Us2Coupon->setCreatedDate(date('Y-m-d'));
			$Us2Coupon->save();

			require_once (SF_ROOT_DIR . '/lib/class.ammspricing_cache.php');
			// Just instantiating the class forces a reload if something changed
			$CAmmsPricing = new AmmsPricing_Cache();

			$url = '/?token=' . Convert::EncodeURL('Page=CouponManager');
			header("Location: $url");
			exit;
		}

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Add Coupon" );
		$this->ActiveMenu = "Admin";
		$this->setTemplate('AddCoupon');
		return '_Success'; exit;
	}

	/**
	* Private Function: Edit Coupon
	*********************************************************************************/
	private function executeEditCoupon()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');

		$this->UpdateCoupon 				= $this->getRequestParameter('UpdateCoupon');

		if (!empty($this->UpdateCoupon)) {
			$this->CouponCode 				= $this->getRequestParameter('CouponCode');
			$this->CustomerId 				= $this->getRequestParameter('CustomerId');
			$this->ProductId 				= $this->getRequestParameter('ProductId');
			$this->Us2ProductGroupId 		= $this->getRequestParameter('Us2ProductGroupId');
			$this->ProgramId 				= $this->getRequestParameter('ProgramId');
			$this->AppliesToType 			= $this->getRequestParameter('AppliesToType');
			$this->AppliesToId 				= $this->getRequestParameter('AppliesToId');
			$this->CouponTypeId 			= $this->getRequestParameter('CouponTypeId');
			$this->CouponValue 				= $this->getRequestParameter('CouponValue');
			$this->InvoiceQuanLimitMin 		= $this->getRequestParameter('InvoiceQuanLimitMin');
			$this->InvoiceQuanLimitMax 		= $this->getRequestParameter('InvoiceQuanLimitMax');
			$this->UsageMaxCount 			= $this->getRequestParameter('UsageMaxCount');
			$this->StartDate 				= $this->getRequestParameter('StartDate');
			$this->EndDate 					= $this->getRequestParameter('EndDate');
			$this->UsageMode 				= $this->getRequestParameter('UsageMode');
			$this->CreatedByUserId 			= $this->CurrentUserId;

			$Us2Coupon 						= Us2CouponPeer::retrieveByPk($this->CouponId);
			if (!empty($Us2Coupon)) {
				require_once (SF_ROOT_DIR . '/lib/class.ammspricing_cache.php');
				// Remove the existing coupon from the cache
				AmmsPricing_Cache::UncacheCoupon($Us2Coupon);

				$Us2Coupon->setCouponCode($this->CouponCode);
				$Us2Coupon->setClientId(CLIENT_ID);
				$Us2Coupon->setCustomerId($this->CustomerId);
				$Us2Coupon->setProductId($this->ProductId);
				$Us2Coupon->setUs2ProductGroupId($this->Us2ProductGroupId);
				$Us2Coupon->setProgramId($this->ProgramId);
				$Us2Coupon->setAppliesToType($this->AppliesToType);
				$Us2Coupon->setAppliesToId($this->AppliesToId);
				$Us2Coupon->setCouponTypeId($this->CouponTypeId);
				if (intval($this->CouponTypeId) == 1) {			// percent
					$Us2Coupon->setCouponValue(floatval($this->CouponValue)/100);
				} else {										// amount
					$Us2Coupon->setCouponValue(floatval($this->CouponValue));
				}
				$Us2Coupon->setInvoiceQuanLimitMin($this->InvoiceQuanLimitMin);
				$Us2Coupon->setInvoiceQuanLimitMax($this->InvoiceQuanLimitMax);
				$Us2Coupon->setUsageCount(intval($this->UsageCount));
				$Us2Coupon->setUsageMaxCount(intval($this->UsageMaxCount));
				$Us2Coupon->setStartDate(date('Y-m-d', strtotime($this->StartDate)));
				$Us2Coupon->setEndDate(date('Y-m-d', strtotime($this->EndDate)));
				$Us2Coupon->setUsageMode($this->UsageMode);
				$Us2Coupon->setUpdatedByUserId($this->CurrentUserId);
				$Us2Coupon->setUpdatedDate(date('Y-m-d'));
				$Us2Coupon->save();

				// Just instantiating the class forces a reload if something changed
				$CAmmsPricing = new AmmsPricing_Cache();
			}

			$url = '/?token=' . Convert::EncodeURL('Page=CouponManager');
			header("Location: $url");
			exit;
		}

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Edit Coupon" );
		$this->ActiveMenu = "Admin";
		$this->setTemplate('EditCoupon');

		return '_Success'; exit;
	}

	/**
	* Private Function: Delete Coupon
	*********************************************************************************/
	private function executeDeleteCoupon()
	{
		$this->CheckAuthentication(SF_GUARD_GROUP_PREFIX.'ADMIN');
		// ADMIN function

		if (!empty($this->CouponId)) {
			$Us2Coupon = Us2CouponPeer::retrieveByPk($this->CouponId);
			if (!empty($Us2Coupon)) {
				require_once (SF_ROOT_DIR . '/lib/class.ammspricing_cache.php');
				// Remove the coupon from the cache
				AmmsPricing_Cache::UncacheCoupon($Us2Coupon);
				$Us2Coupon->setClientId(-1);
				$Us2Coupon->setUpdatedByUserId($this->CurrentUserId);
				$Us2Coupon->setUpdatedDate(date('Y-m-d'));
				$Us2Coupon->save();

				// Just instantiating the class forces a reload if something changed
				$CAmmsPricing = new AmmsPricing_Cache();
			}
		}

		$url = '/?token=' . Convert::EncodeURL('Page=CouponManager');
		header("Location: $url");
		exit;
	}

	/**
	* Private Function: Product Manager
	*********************************************************************************/
	private function executeProductManager()
	{
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));

		$this->DisplayCEClientSelector = true;

		// If turning product online or offline
		if (!empty($this->SwitchProductStatus) && !empty($this->StatusId) && !empty($this->ProductId)) {
			$Us2Product = Us2ProductPeer::retrieveByPk($this->ProductId);
			$Us2Product->setStatusId($this->StatusId);
			$Us2Product->save();

			$url = '/?token=' . Convert::EncodeURL('Page=ProductManager');
			header("Location: $url");
			exit;
		}

		$productCategory = 0; # VIEW ALL
		$arrayProduct = Us2ProductPeer::GetProductByCategory(STORE_ID, $productCategory);
		$arrayProductList = array();

		// Get some basic info for the list of products
		$C = new Criteria();
		$C->addSelectColumn(Us2ProductPeer::PRODUCT_ID);
		$C->addSelectColumn(Us2ProductPeer::NAME);
		$C->addSelectColumn(Us2ProductPeer::CREATED_DATE);
		$C->addSelectColumn(Us2ProductPeer::CREATED_BY_USER_ID);
		$C->addSelectColumn(Us2ProductPeer::UPDATED_DATE);
		$C->addSelectColumn(Us2ProductPeer::UPDATED_BY_USER_ID);
		$C->addSelectColumn(Us2ProductPeer::STATUS_ID);
		$C->addAnd(Us2ProductPeer::PRODUCT_ID, $arrayProduct, Criteria::IN);

		if (!empty($this->SearchProduct)) {
			$C->addAnd(Us2ProductPeer::NAME, "%{$this->SearchProduct}%", Criteria::LIKE);
		} else {
			$this->SearchProduct = '';
		}

		$C->addAscendingOrderByColumn(Us2ProductPeer::NAME);
		$Rs = Us2ProductPeer::doSelectRs($C);

		while ($Rs->next()) {
			$arrayProductList[$Rs->get(1)] = array(
				'name' => $Rs->get(2),
				'created_date' => $Rs->get(3),
				'updated_date' => $Rs->get(5),
				'created_by_user_id' => $Rs->get(4),
				'updated_by_user_id' => $Rs->get(6),
				'status_id' => $Rs->get(7)
			);
		}

		$this->arrayProductList = $arrayProductList;

		$this->getResponse()->setTitle( WEBSITE_TITLE ." - Products Manager" );
		$this->ActiveMenu = "Admin";
		$this->setTemplate('ProductManager');
		return '_Success'; exit;
	}

	/**
	* Private Function: Customers
	*********************************************************************************/
	private function executeCustomers()
	{
		$this->getResponse()->setTitle( WEBSITE_TITLE .' | Customers' );
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));
		$this->setTemplate('Customers');
		if (STORE_ID == CE_STORE_ID) {
			$this->DisplayCEClientSelector = true;
		}
		return '_Success'; exit;
	}

	/**
	* Private Function: Payment Profile
	*********************************************************************************/
	private function executePaymentProfile()
	{
		// First, make sure the user is authenticated
		$this->CheckAuthentication();
		$accessGroup				= array('ADMIN','STORE ADMIN');
		$this->isAdmin				= $this->AccessControl->hasGroup( $accessGroup );
		// If it's not an admin, or the customer id is not specified, use the logged-in user's customer id
		if (!$this->isAdmin || empty($this->CustomerId)) {
			$this->CustomerId 			= $this->CurrentCustomerId;
		}

		$C = new Criteria();
		$C->add(Us2AuthnetCustomerProfilePeer::CUSTOMER_ID, $this->CustomerId);
		$C->add(Us2AuthnetCustomerProfilePeer::ACTIVE_YN, 'Y');
		$AuthnetCustomerProfile = Us2AuthnetCustomerProfilePeer::doSelectOne($C);
		// If an active customer profile doesn't exist
		if (empty($AuthnetCustomerProfile)) {
			// Create the profile first
			$this->Action 				= "CreateCustomerProfile";
		}

		$this->getResponse()->setTitle( WEBSITE_TITLE .' | Payment Profile' );

		$url = "/?token=" . Convert::EncodeURL('Page=PaymentProfile&CustomerId=' . $this->CustomerId);
		switch ($this->Action) {
			case "CreateCustomerProfile":
				require_once (SF_ROOT_DIR . "/apps/".SF_APP."/lib/Authorizenet.class.php");
				$Authorizenet 			= new Authorizenet();
				$CustomerProfileId 		= $Authorizenet->CreateProfile($this->CustomerId);
				if (!empty($CustomerProfileId)) {
					$url = '/?token=' . Convert::EncodeURL('Page=PaymentProfile&CustomerId=' . $this->CustomerId);
					header("Location: {$url}"); exit;
				} else {
					die("error");
				}
				break;

			case "DeleteCustomerProfile":
				require_once (SF_ROOT_DIR . "/apps/".SF_APP."/lib/Authorizenet.class.php");
				$Authorizenet 	= new Authorizenet();
				$result 		= $Authorizenet->DeleteCustomerProfile($this->CustomerId);
				if ($result) {
					$url = '/?token=' . Convert::EncodeURL('Page=Customers');
					header("Location: {$url}"); exit;
				} else {
					die("error");
				}
				break;

			case "EditPaymentProfile":
				require_once (SF_ROOT_DIR . "/apps/".SF_APP."/lib/Authorizenet.class.php");
				$this->Submit 						= $this->getRequestParameter('Submit');

				if ($this->Submit) {
					$PaymentProfileId 											= $this->getRequestParameter('PaymentProfileId', '0');
					$AuthnetPaymentProfileId 									= $this->getRequestParameter('AuthnetPaymentProfileId');

					$NewPaymentProfile 											= new AuthorizeNetPaymentProfile;
					$NewPaymentProfile->customerType							= $this->getRequestParameter('CustomerType');	// individual or business

					// Enter card info
					$CardNumber 												= preg_replace("/[^0-9]/", '', $this->getRequestParameter('CardNumber'));
					$LastFour 													= substr($CardNumber, -4);
					$ExpirationDate 											= sprintf("%04d-%02d", preg_replace("/[^0-9]/", '', $this->getRequestParameter('ExpirationYear')), preg_replace("/[^0-9]/", '', $this->getRequestParameter('ExpirationMonth')));
					$CardCode 													= preg_replace("/[^0-9]/", '', $this->getRequestParameter('CardCode'));
					$NewPaymentProfile->payment->creditCard->cardNumber 		= $CardNumber;
					$NewPaymentProfile->payment->creditCard->expirationDate 	= $ExpirationDate;
					$NewPaymentProfile->payment->creditCard->cardCode 			= $CardCode;

					// Enter billing address
					$NewPaymentProfile->billTo->firstName 						= $this->getRequestParameter('FirstName');
					$NewPaymentProfile->billTo->lastName 						= $this->getRequestParameter('LastName');
					$NewPaymentProfile->billTo->company 						= $this->getRequestParameter('Company');
					$NewPaymentProfile->billTo->address 						= $this->getRequestParameter('Address');
					$NewPaymentProfile->billTo->city 							= $this->getRequestParameter('City');
					$NewPaymentProfile->billTo->state 							= $this->getRequestParameter('State');
					$NewPaymentProfile->billTo->zip 							= $this->getRequestParameter('Zip');
					$NewPaymentProfile->billTo->phoneNumber 					= $this->getRequestParameter('Phone');

					$Authorizenet = new Authorizenet();
					$result = $Authorizenet->CreatePaymentProfile($this->CustomerId, $PaymentProfileId, $AuthnetPaymentProfileId, $NewPaymentProfile);

					if ($result) {
						$url = '/?token=' . Convert::EncodeURL('Page=PaymentProfile&CustomerId=' . $this->CustomerId);
						header("Location: {$url}");
						exit;
					} else {
						die("error");
					}
				}

				$this->setTemplate('PaymentProfile');
				return '_Create';
				break;

			case "DeletePaymentProfile":
				require_once (SF_ROOT_DIR . "/apps/".SF_APP."/lib/Authorizenet.class.php");
				$Authorizenet 	= new Authorizenet();
				$result 		= $Authorizenet->DeletePaymentProfile($this->CustomerId, $this->PaymentProfileId);
				if ($result) {
					$url = '/?token=' . Convert::EncodeURL('Page=PaymentProfile&CustomerId='.$this->CustomerId);
					header("Location: {$url}"); exit;
				} else {
					die("error");
				}
				break;

			case "EditShippingAddress":
				require_once (SF_ROOT_DIR . "/apps/".SF_APP."/lib/Authorizenet.class.php");
				$this->Submit 						= $this->getRequestParameter('Submit');

				if ($this->Submit) {
					$ShippingAddressId 											= $this->getRequestParameter('ShippingAddressId', '0');
					$AuthnetShippingAddressId 									= $this->getRequestParameter('AuthnetShippingAddressId');

					$this->Description 											= $this->getRequestParameter('Description');

					$NewShippingAddress 										= new AuthorizeNetAddress;

					// Enter shipping address
					$NewShippingAddress->firstName 								= $this->getRequestParameter('FirstName');
					$NewShippingAddress->lastName 								= $this->getRequestParameter('LastName');
					$NewShippingAddress->company 								= $this->getRequestParameter('Company');
					$NewShippingAddress->address 								= $this->getRequestParameter('Address');
					$NewShippingAddress->city 									= $this->getRequestParameter('City');
					$NewShippingAddress->state 									= $this->getRequestParameter('State');
					$NewShippingAddress->zip 									= $this->getRequestParameter('Zip');
					$NewShippingAddress->phoneNumber 							= $this->getRequestParameter('Phone');

					$Authorizenet = new Authorizenet();
					$result = $Authorizenet->CreateShippingAddress($this->CustomerId, $ShippingAddressId, $AuthnetShippingAddressId, $NewShippingAddress, $this->Description);

					if ($result) {
						$url = '/?token=' . Convert::EncodeURL('Page=PaymentProfile&CustomerId=' . $this->CustomerId);
						header("Location: {$url}");
						exit;
					} else {
						die("error");
					}
				}

				$this->setTemplate('ShippingAddress');
				return '_Create';
				break;

			case "DeleteShippingAddress":
				require_once (SF_ROOT_DIR . "/apps/".SF_APP."/lib/Authorizenet.class.php");
				$Authorizenet 	= new Authorizenet();
				$result 		= $Authorizenet->DeleteShippingAddress($this->CustomerId, $this->ShippingAddressId);
				if ($result) {
					$url = '/?token=' . Convert::EncodeURL('Page=PaymentProfile&CustomerId='.$this->CustomerId);
					header("Location: {$url}"); exit;
				} else {
					die("error");
				}
				break;

			default:
				$this->setTemplate('CustomerProfile');
				return '_Success';
				exit;
		}
	}

	private function executeSampleCSV() {
		header("Content-type: text/x-csv");
		header("Pragma: no-cache");
		header("Expires: 0");
		header('Location: ' . "/ammslist.csv");
		die();
	}

	/**
	* Private Function: Products
	*********************************************************************************/
	private function executeProducts()
	{
		$conn = Propel::getConnection();

		// Fetch campaigns
		$DurationCycles = $this->getRequestParameter("DurationCycles");
		if ($DurationCycles) {
			$stmt0 = $conn->prepareStatement("
				SELECT * FROM (
					SELECT
						us2_campaign.*,
						COALESCE(us2_image.preview_url, 'http://gateway.printhd.us/images/no-pre.png') AS preview_url
					FROM us2_campaign
					JOIN us2_campaign_detail ON us2_campaign.campaign_id = us2_campaign_detail.campaign_id
					JOIN us2_product ON us2_campaign_detail.product_id = us2_product.product_id
					LEFT JOIN us2_image ON us2_product.small_image_id = us2_image.us2_image_id
					WHERE us2_campaign.store_id = ?
					AND (us2_campaign.active_yn = 'Y')
					AND (us2_campaign.status_id = '2')
					AND (us2_campaign.customer_id IN (0, ?))
					AND (us2_campaign.duration_cycles IN (" . implode(',',$DurationCycles) . "))
					ORDER BY us2_campaign_detail.cycle ASC, us2_campaign_detail.sequence ASC
				) campaigns
				GROUP BY campaign_id
				ORDER BY duration_cycles, name
			");
			$stmt0->setInt(1, STORE_ID);
			$stmt0->setInt(2, $this->CurrentCustomerId);
		} else {
			$stmt0 = $conn->prepareStatement("
				SELECT * FROM (
					SELECT
						us2_campaign.*,
						COALESCE(us2_image.preview_url, 'http://gateway.printhd.us/images/no-pre.png') AS preview_url
					FROM us2_campaign
					JOIN us2_campaign_detail ON us2_campaign.campaign_id = us2_campaign_detail.campaign_id
					JOIN us2_product ON us2_campaign_detail.product_id = us2_product.product_id
					LEFT JOIN us2_image ON us2_product.small_image_id = us2_image.us2_image_id
					WHERE us2_campaign.store_id = ?
					AND (us2_campaign.active_yn = 'Y')
					AND (us2_campaign.status_id = '2')
					AND (us2_campaign.customer_id IN (0, ?))
					ORDER BY us2_campaign_detail.cycle ASC, us2_campaign_detail.sequence ASC
				) campaigns
				GROUP BY campaign_id
				ORDER BY duration_cycles, name
			");
			$stmt0->setInt(1, STORE_ID);
			$stmt0->setInt(2, $this->CurrentCustomerId);
		}

		$result0 = $stmt0->executeQuery();
		$this->campaigns = array();
		while ($result0->next()) {
			$row = $result0->getRow();
			if (!array_key_exists($row['duration_cycles'], $this->campaigns)) {
				$this->campaigns[$row['duration_cycles']] = array();
			}

			// Specifically for the thumbnail with 150x150 max dimensions
			$querystring = "src={$row['preview_url']}&w=150&h=150";
			$hash = md5("{$querystring}".PHP_THUMB_PASSWORD);
			$row['php_thumb_link'] = "/phpThumb/phpThumb.php?{$querystring}&hash={$hash}";
			$this->campaigns[$row['duration_cycles']][] = $row;
		}

		// Fetch products
		$ProductGroupIDs = $this->getRequestParameter("ProductGroupId");
		$TemplateID = $this->ProductTemplateId;
		$ProductIDs = $this->getRequestParameter("ProductId");
		$ProductTypeIDs = "1,6";
		if ($ProductIDs) {
			$stmt = $conn->prepareStatement("
				SELECT
					us2_product.*,
					COALESCE(us2_image.preview_url, 'http://gateway.printhd.us/images/no-pre.png') AS preview_url
				FROM us2_product
				LEFT JOIN us2_image ON us2_image.us2_image_id = us2_product.small_image_id
				WHERE (us2_product.store_id = ?)
				AND (us2_product.product_type_id IN ({$ProductTypeIDs}))
				AND (us2_product.status_id = 2)
				AND (us2_product.active_yn = 'Y')
				AND (us2_product.product_id IN (" . $ProductIDs . "))
			");
			$stmt->setInt(1, STORE_ID);
		} else if ($TemplateID) {
			$stmt = $conn->prepareStatement("
				SELECT
					us2_product.*,
					COALESCE(us2_image.preview_url, 'http://gateway.printhd.us/images/no-pre.png') AS preview_url
				FROM us2_product
				LEFT JOIN us2_image ON us2_image.us2_image_id = us2_product.small_image_id
				WHERE (us2_product.store_id = ?)
				AND (us2_product.product_type_id IN ({$ProductTypeIDs}))
				AND (us2_product.status_id = 2)
				AND (us2_product.active_yn = 'Y')
				AND (us2_product.us2_product_template_id = ?)
			");
			$stmt->setInt(1, STORE_ID);
			$stmt->setInt(2, $TemplateID);
		} else if ($ProductGroupIDs) {
			$arrayProductGroupId = array();
			$QueryType = "AND_OR";
			switch ($QueryType) {
				case "OR":
					// Use the OR condition: We only care about the second half
					foreach ($ProductGroupIDs as $ProductGroupID) {
						$temp = explode("-", $ProductGroupID);
						$arrayProductGroupId[]	= $temp[1];
					}
					$QueryProductGroups = "us2_product_group_membership.product_group_id IN (" . implode(",", $arrayProductGroupId) . ")";
					break;

				case "AND":
					// Use the AND condition
					foreach ($ProductGroupIDs as $ProductGroupID) {
						$temp = explode("-", $ProductGroupID);
						$arrayProductGroupId[]	= $temp[1];
					}
					$ProductGroups = array("1");
					foreach ($arrayProductGroupId as $child) {
						$ProductGroups[]	= "us2_product.product_id IN (SELECT product_id FROM us2_product_group_membership WHERE product_group_id = {$child})";
					}
					$QueryProductGroups = implode(" AND ", $ProductGroups);
					break;

				case "AND_OR":
				default:
					// Use the AND/OR condition: We care about the first and second half
					foreach ($ProductGroupIDs as $ProductGroupID) {
						$temp = explode("-", $ProductGroupID);
						if (count($temp) == 1) {
							array_unshift($temp, 0);
						}
						if (!array_key_exists($temp[0], $arrayProductGroupId)) {
							$arrayProductGroupId[$temp[0]]	= array(0);
						}
						if (!empty($temp[1])) {
							$arrayProductGroupId[$temp[0]][]	= $temp[1];
						}
					}
					$ProductGroups = array();
					foreach ($arrayProductGroupId as $parent => $children) {
						$ProductGroups[]	= "us2_product.product_id IN (SELECT product_id FROM us2_product_group_membership WHERE product_group_id IN (" . implode(",", $children) . "))";
					}
					$QueryProductGroups = implode(" AND ", $ProductGroups);
			}
			$stmt = $conn->prepareStatement(
				$Query =
				"SELECT DISTINCT "
					. "us2_product.*, "
					. "COALESCE(us2_image.preview_url, 'http://gateway.printhd.us/images/no-pre.png') AS preview_url "
				. "FROM us2_product "
				. "LEFT JOIN us2_image ON us2_image.us2_image_id = us2_product.small_image_id "
				. "JOIN us2_product_group_membership ON us2_product_group_membership.product_id = us2_product.product_id "
				. "WHERE (us2_product.store_id = ?) "
				. "AND (us2_product.product_type_id IN ({$ProductTypeIDs})) "
				 ."AND (us2_product.status_id = 2) "
				. "AND (us2_product.active_yn = 'Y') "
				. "AND {$QueryProductGroups}"
			);
			$stmt->setInt(1, STORE_ID);
		} else {
			$stmt = $conn->prepareStatement(
				$Query =
				"SELECT "
					. "us2_product.*, "
					. "COALESCE(us2_image.preview_url, 'http://gateway.printhd.us/images/no-pre.png') AS preview_url "
				. "FROM us2_product "
				. "LEFT JOIN us2_image ON us2_image.us2_image_id = us2_product.small_image_id "
				. "WHERE (us2_product.store_id = ?) "
				. "AND (us2_product.product_type_id IN ({$ProductTypeIDs})) "
				. "AND (us2_product.status_id = 2) "
				. "AND (us2_product.active_yn = 'Y')"
			);
			$stmt->setInt(1, STORE_ID);
		}

		$result = $stmt->executeQuery();

		$products = array();
		while ($result->next()) {
			$product = $result->getRow();

			// Specifically for the thumbnail with 150x150 max dimensions
			$querystring = "src={$product['preview_url']}&w=150&h=150";
			$hash = md5("{$querystring}".PHP_THUMB_PASSWORD);
			$product['php_thumb_link'] = "/phpThumb/phpThumb.php?{$querystring}&hash={$hash}";

			$products[] = $product;
		}

		// Fetch categories
		$stmt = $conn->prepareStatement(
			$Query =
			"SELECT DISTINCT "
				. "us2_product_group.us2_product_group_id, "
				. "us2_product_group.parent_us2_product_group_id, "
				. "us2_product_group.name, "
				. "t.name AS parent, "
				. "COALESCE(COUNT(us2_product.product_id), 0) AS product_count "
			. "FROM us2_product_group "

			. "JOIN us2_product_group as t "
				. "ON us2_product_group.parent_us2_product_group_id = t.us2_product_group_id "

			. "LEFT JOIN us2_product_group_membership "
				. "ON us2_product_group.us2_product_group_id = us2_product_group_membership.product_group_id "

			. "LEFT JOIN us2_product "
				. "ON us2_product.product_id = us2_product_group_membership.product_id "
				. "AND us2_product.status_id = 2 "

			. "WHERE us2_product_group.store_id = ? "
			. "AND us2_product_group.status_id = 2 "
			. "GROUP BY us2_product_group.us2_product_group_id "
		);
		$stmt->setInt(1, STORE_ID);
		$result = $stmt->executeQuery();

		$categories = array();
		while ($result->next()) {
			$category = $result->getRow();
			$categories[$category['us2_product_group_id']] = $result->getRow();
		}

		$this->categoryTree = Us2ProductGroupPeer::GetAllCategoriesByStoreInDisplayOrder(STORE_ID, $ViewAll = true);
		$this->categories = $categories;

		$this->limit = 100;
		if (!$this->offset) {
			$this->offset = 1;
		}

		$this->total = count($products);
		$this->products = array_slice($products, $this->offset - 1, $this->limit);

		$selected_groups = array();
		foreach ($ProductGroupIDs as $product_group_id) {
			$selected_groups[$product_group_id] = true;
		}
		$this->selected_groups = $selected_groups;

		$this->nextURL = null;
		if ($this->total >= $this->limit + $this->offset) {
			$next_offset = $this->offset + $this->limit;
			$this->nextURL = Convert::EncodeURL(http_build_query(array("Page" => "Products", "offset" => $next_offset), '', '&'));
		}

		$this->prevURL = null;
		if ($this->offset > $this->limit) {
			$prev_offset = $this->offset - $this->limit;
			$this->prevURL = Convert::EncodeURL(http_build_query(array("Page" => "Products", "offset" => $prev_offset), '', '&'));
		}

		switch ($this->Response) {
			case "JSON":
				header("Content-Type: application/json");
				return $this->renderText(json_encode($this->products));
			case "JSON_CAMPAIGN":
				header("Content-Type: application/json");
				return $this->renderText(json_encode($this->campaigns));
			default:
				$this->getResponse()->setTitle( WEBSITE_TITLE ." - Products" );
				// If we are in the Asbury or CE store
				if (in_array(STORE_ID, array(ASBURY_STORE_ID, CE_STORE_ID))) {
					$this->ActiveMenu = "Campaigns";
				}
				else{
					$this->ActiveMenu = "Products";
				}

				$this->setTemplate("Products");
				return '_Success';
		}
	}

	/**
	* Private Function: Process Post Contact Us Form
	*********************************************************************************/
	private function executePostContact()
	{
		$ReplyToName		= trim($this->getRequestParameter('name'));
		$ReplyToAddress		= trim($this->getRequestParameter('email'));
		$ToAddress			= trim($this->getRequestParameter('to_address'));

		$this->errors = array();

		if (!$ReplyToAddress) {
			$this->errors[]		= '<span class="error">Please enter a return address and try again.</span>';
		}

		$Message			= trim($this->getRequestParameter('message'));

		if (!$Message) {
			$this->errors[]		= '<span class="error">Please type a message and try again.</span>';
		}

		$Message = nl2br($Message);

		$Subject 			= $_SERVER['HTTP_HOST'] . " - Contact Us Form";
		$Body 			= "
			A user has used the quick contact form at " .$_SERVER['HTTP_HOST'] .".<br />
			Replies to this message will go directly to the user.<hr />

			<b>Details:</b><br />
			Received on: ".date('m/d/Y H:i:s a')."<br />
			IP Address: {$_SERVER['REMOTE_ADDR']}<br />
			Customer: {$ReplyToName}<br />
			Email: {$ReplyToAddress}<p /><br />

			<b>Message:</b><p />

			{$Message} <p /><br />
		";


		$this->MessageSent = $this->sendMail($ToAddress, $Subject, $Body, $ReplyToAddress, $ReplyToName);

		if (!$this->MessageSent) {
			$this->errors[] = "A system error has occurred while trying to contact our support representative. Please try again later.";
		}

		$this->setTemplate('ContactUs');
		return "_Success";
	}

	/**
	* Private Function: General send email
	*********************************************************************************/
	private function sendMail($ToAddress, $Subject, $Body, $ReplyToAddress="", $ReplyToName="", $AltBody="TEXT ONLY BODY")
	{
		$this->errors = array();

		// Include the newest php mailer library to send email
		// The 5.2.9 version supports the Exchange server
		require_once SF_ROOT_DIR . '/classes/phpmailer-5.2.9/PHPMailerAutoload.php';

		$Mail = new PHPMailer();
		$Mail->isSMTP();									# Send via SMTP
		$Mail->Host				= 'mail1.ammsusa.com';		# SMTP servers
		$Mail->Username			= 'sysadmin@ammsusa.com';	# SMTP username
		$Mail->Password			= 'Manage50400';			# SMTP password
		$Mail->SMTPSecure		= 'tls';
		$Mail->SMTPAuth 		= true;						# Turn on SMTP authentication
		$Mail->WordWrap 		= 50;						# Set word wrap
		$Mail->isHTML(true);								# Send as HTML
		$Mail->Port				= 587;

		$Client 				= ClientPeer::retrieveByPk(CLIENT_ID);
		$Store 					= Us2StorePeer::retrieveByPk(STORE_ID);
		$StoreName				= $Store->getName();

		// TODO: Does not like using the request@ address. Must use the sysadmin address.
		// $Mail->setFrom("request@" . $_SERVER['HTTP_HOST'], $StoreName);
		$Mail->setFrom('sysadmin@ammsusa.com', $StoreName);

		// TODO: Optionally add the values from the client
		// $Mail->addAddress ($Email, $Name);
		// $Mail->addAddress ($ContactEmail, $ContactName);

		// The actual store recipient. We get that from the form as $ToAddress.
		$Mail->addAddress ($ToAddress);
		// TODO: Test recipient.
		// $Mail->addAddress ('palcivar@ammsusa.com', 'Peter L. Alcivar');
		$Mail->addBCC('sysadmin@ammsusa.com');
		$Mail->addBCC('sailmeeeee@gmail.com');
		$Mail->addBCC('palcivar@ammsusa.com');
		// Reply directly to the sender
		if (!empty($ReplyToAddress)) {
			$Mail->addReplyTo($ReplyToAddress, $ReplyToName);
		}

		$Mail->Subject			= $Subject;
		$Mail->AltBody			= $AltBody;
		$Mail->Body				= $Body;

		$MessageSent = $Mail->send();

		return $MessageSent;
	}

	private function executeTest() {
		$conn = Propel::getConnection();

		// Products
		$stmt = $conn->prepareStatement("
			SELECT
				us2_product.*,
				us2_image.preview_url
			FROM us2_product
			JOIN us2_image ON us2_image.us2_image_id = us2_product.large_image_id
			WHERE (us2_product.store_id = ?)
			AND (us2_product.product_type_id = 1)
			AND (us2_product.status_id = 2)
			AND (us2_product.active_yn = 'Y')
			LIMIT 6
		");
		$stmt->setInt(1, STORE_ID);

		$result = $stmt->executeQuery();

		$products = array();
		while ($result->next()) {
			$products[] = $result->getRow();
		}

		$this->products = $products;
		$this->featured = $products[0];

		$this->getResponse()->setTitle(WEBSITE_TITLE);
		$this->ActiveMenu = "Home";
		$this->setTemplate("Test");
		return "_Success";
	}

	private function executeProductImage() {
		header("Content-Type: image/jpeg");
		$parts = parse_url($this->URL);
		switch ($parts["host"]) {
			case "gateway.printhd.us":
			case "store.printhd.us":
				return $this->renderText(file_get_contents($this->URL));
			default:
				return $this->renderText(file_get_contents($this->URL));
		}
	}

	private function executeMarketEval(){
		require_once(SF_ROOT_DIR . "/classes/PolkAvailable.class.php");
		$this->CheckAuthentication();
		$this->getResponse()->setTitle('Market Eval');
		//GET brands available from polk
		$polk = new PolkAvailable();
		$this->PolkBrands = $polk->GetManufactures();
		//GET Market Eval Settings -- The rest is loaded via ajax.
		$this->mk = self::MarketEvalSettingRequest();
		$this->mk['parameters'] = unserialize($this->mk['parameters']);
		$this->mk['requested_by_user_name'] = sfGuardUserPeer::GetLastFirstById($this->mk['requested_by_user_id']);
		$this->ActiveTab = "Services";
		if(isset($_POST['RequestNewEval'])){

			$this->ActiveTab = "Settings";
			$_POST['parameters']['ignore_b2b'] = (@$_POST['parameters']['ignore_b2b'])?1:0;
			$_POST['parameters']['valid_address_only]'] = @$_POST['parameters']['valid_address_only]']?1:0;
			$_POST['parameters']['exclude_everyone_with_email'] = @$_POST['parameters']['exclude_everyone_with_email']?1:0;
			$_POST['parameters']['exclude_nondealer_makes'] = @$_POST['parameters']['exclude_nondealer_makes']?1:0;

			$mk = array_merge($this->mk['parameters'],$_POST['parameters']);
			$this->mk['parameters'] = $mk;
			$mk['requested_by_user_id'] = $this->CurrentUserId;
			$mk['radius'] = $_POST['parameters']['radius'];

			try{
				self::MarketEvalSettingRequest("",array("market_eval_request"=>$mk),"post");
				$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=MarketEval')."&at=Settings";
				$this->redirect($url);
				exit;
			} catch (Exception $ex) {
				echo "<script>alert('{$ex->getMessage()}')</script>";
			}



			//$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=MarketEval')."&at=Settings";
			//$this->redirect($url);
			//exit;
		}
		if(isset($_GET['at'])){
			$this->ActiveTab = $_GET['at'];
		}
		//$this->setTemplate('ViewMarketEval');
		//$this->canDownloadCsv = false;	// TODO: Set true to display "Export as CSV" button
		$this->setTemplate("MarketEval");

		$this->ActiveMenu = "My Dashboard";
		return '_Success'; exit;
	}

	private function executeContactUs(){
		$this->getResponse()->setTitle('Contact Us');
		$this->ActiveMenu = "Contact Us";
		$this->setTemplate('ContactUs');
		return '_Success';exit;
	}

	private function executeReports() {
		$this->CheckAuthentication();

		$ACCESS_KEY		= 'v5826jkhnAUIGjhgv89612BiohJKuigb1578jJKgma89671283AQILHKJGmnah231a';
		// First, do a UserData call to get the ammsauth user name
		$url1			= "http://sso.ammscore.com/Signon/UserData?APIKEY={$ACCESS_KEY}&sf_guard_user_id={$this->CurrentUserId}";

		$response1		= $this->curlGet($url1);
		$userdata1		= json_decode($response1, true);

		$arrayUrl		= explode('.', $_SERVER["HTTP_HOST"]);
		if (count($arrayUrl) == 3) {
			$url			= "{$arrayUrl[0]}.ilomlive.com";
		} else {
			$url			= "asbury.ilomlive.com";
		}

		if (($userdata1['status'] == 'success') && !empty($userdata1['data']['ammsauth_username'])) {
			$arrayExtra		= array("uri"			=> "http://{$url}/Reports",
									"customer_id"	=> CLIENT_ID,
									"mailer_id"		=> $this->CurrentCustomerId
							);
			$extra_data		= json_encode($arrayExtra);

			$url2 = "http://sso.ammscore.com/Signon?action=get-sso-key&key={$ACCESS_KEY}&type=1&username={$userdata1['data']['ammsauth_username']}&data={$extra_data}";
			$response2		= $this->curlGet($url2);
			$userdata2		= json_decode($response2, true);

			if ($userdata2['response']) {
				$url3			= "http://{$url}/?token={$userdata2['access_key']}";

				$this->redirect($url3); exit;
			}
		}

		$this->redirect ("/");
	}


	private function executeExtraParamsXml() {
		$this->CheckAuthentication();

		$Clear					= $this->getRequestParameter('Clear', 0);
		$OrderProductId			= $this->getRequestParameter('OrderProductId');
		if (empty($Clear)) {
			$MarketEvalRequestId	= $this->getRequestParameter('MarketEvalRequestId');
			$CountOptionDms			= $this->getRequestParameter('count_option_dms');
			$CountDms				= $this->getRequestParameter('count_dms');
			$ZipCodeDms				= $this->getRequestParameter('zipcode_dms');
			$CountOptionConquest	= $this->getRequestParameter('count_option_conquest');
			$CountConquest			= $this->getRequestParameter('count_conquest');
			$ZipCodeConquest		= $this->getRequestParameter('zipcode_conquest');

			$ExtraParams			= array("OrderProductId"			=> $OrderProductId,
											"MarketEvalRequestId"		=> $MarketEvalRequestId,
											"CountOptionDms"			=> $CountOptionDms,
											"CountDms"					=> $CountDms,
											"ZipCodeDms"				=> $ZipCodeDms,
											"CountOptionConquest"		=> $CountOptionConquest,
											"CountConquest"				=> $CountConquest,
											"ZipCodeConquest"			=> $ZipCodeConquest
											);

			$OrderProduct			= Us2OrderProductPeer::retrieveByPk($OrderProductId);
			$OrderProduct->setExtraParamsXml(json_encode($ExtraParams));
			$OrderProduct->save();
		} else {
			$OrderProduct			= Us2OrderProductPeer::retrieveByPk($OrderProductId);
			$OrderProduct->setExtraParamsXml(null);
			$OrderProduct->save();
		}
		exit;
	}


	private function executeGetUploadStatus() {
		$this->CheckAuthentication();

		$this->setLayout(false);

		$ch = new CyberHackney();

		$uploads = $ch->get("Uploads", array(
			"customer_id" => $this->clientID,
			"mailer_id" => $this->customerID,
			"user_id" => $this->userID,
			"upload_master_id" => $this->UploadMasterId
		));

		return $this->renderText(json_encode($uploads));
	}

	private function executeCreatePull() {
		$this->CheckAuthentication();

		$customerID			= intval($this->CurrentCustomerId);
		$clientID			= intval(CustomerPeer::GetClientByCustomer($customerID));

		$UploadMasterId		= $this->getRequestParameter('UploadMasterId');
		$UploadId			= $this->getRequestParameter('UploadId');
		$OrderProductId		= $this->getRequestParameter('OrderProductId');

		$Us2OrderProduct	= Us2OrderProductPeer::retrieveByPk($OrderProductId);
		$OrderNotes			= $Us2OrderProduct->getOrderNotes();
		$ExtraParamsXml		= $Us2OrderProduct->getExtraParamsXml();
		$ExtraParams		= json_decode($ExtraParamsXml, true);

		$Limit				= intval($ExtraParams['CountDms']) + intval($ExtraParams['CountConquest']);

		$this->setLayout(false);
		$ch = new CyberHackney();

		$pull		= $ch->CreatePull($clientID,
									$customerID,
									$OrderNotes,
									null,
									'Pending',
									'New',
									$Limit);

		if (is_array($pull) && array_key_exists('pull_id', $pull)) {

			$result		= $ch->CreatePullUnit($clientID,
											$customerID,
											$pull['pull_id'],
											'INCLUDE',
											'UPLOAD',
											$UploadId,
											$Limit);

			if ($result) {
				$pull1 = $ch->get("Pulls", array("pull_master_id" => $pull['pull_master_id']));
				$PullData = reset($pull1['results']);
				$Us2OrderProduct->setRecipientListId($PullData['pull_master_id']);
				$Us2OrderProduct->setTotalQuan($PullData['net_records']);
				$Us2OrderProduct->setRecipientTypeId(5);		// CyberHackney
				$Us2OrderProduct->save();
			}

			return $this->renderText(json_encode($pull));

		} else {

			return $this->renderText(json_encode(false));

		}
	}

	private function executeGetPullInfo() {
		$this->CheckAuthentication();

		$PullMasterId	= $this->getRequestParameter('PullMasterId');

		$this->setLayout(false);
		$ch = new CyberHackney();

		$results	= $ch->get("Pulls", array("pull_master_id" => $PullMasterId));

		return $this->renderText(json_encode($results));
	}

	private function executeOrderReviewNonMailable() {
		$this->CheckAuthentication();

		$qty = intval($this->getRequestParameter('qty', 0));

		$Us2OrderProduct = Us2OrderProductPeer::retrieveByPk($this->OrderProductId);
		if (empty($qty)){
			$loc = "/?token=".  Convert::EncodeURL("Page=CustomizeOrder&OrderProductId=".$this->OrderProductId);
			error_log($loc);
			header("Location: {$loc}");
			exit;
		}
		$this->getResponse()->setTitle('Order Review');
		$this->setTemplate("OrderReviewNonMailable");
		$Us2OrderProduct->setTotalQuan($qty);
		$totalPrice = self::GetPrice($this->CurrentCustomerId, $Us2OrderProduct->getProductId(), $qty);
		$Us2OrderProduct->setTotalPrice($totalPrice);
		$Us2OrderProduct->save();
		return "_Success";exit;
	}


	public function executeEvalOrder()
	{
		$this->updateOrderProductId = $this->getRequestParameter("updateOpId");
		//$this->updateOrderProductId	= $_REQUEST['updateOpId'];	# Just in case we have an order product
		$this->setLayout("smanager");
		$this->getResponse()->setTitle('Market Eval');
		$this->userId = $this->getUser()->GetUserId($this);

		//if($_REQUEST['agent']) $this->setLayout($_REQUEST['agent']);
		return '_Success'; exit;
	}

	public function curlGet($url)
	{

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
		curl_setopt($ch, CURLOPT_TIMEOUT, 300);
		curl_setopt($ch, CURLOPT_URL, $url);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
		$response = curl_exec($ch);
		if (!$response) {
			$error = curl_error($ch);
			echo $error;exit;
		}

		return $response;
	}

	public function executeUploadConsumers(){
		$this->CheckAuthentication();
		$this->getResponse()->setTitle('Upload Consumers');
		$this->ActiveMenu = "Admin";
		$this->setTemplate('UploadConsumers');

		#Get the mappings
		#If not mappings send to mapping page so they can add one
		$mappings = array();
		$ci = $_GET["ci"];


		$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$q = "SELECT * FROM `us2_file_map` WHERE `active_yn` = 'Y' AND `client_id` = :clientId AND `customer_id` IN (0,:customerId) ORDER BY `customer_id` DESC, `us2_file_map_id` DESC";
		$stmt = $conn->prepare($q);
		$stmt->bindValue(":clientId",SF_CLIENT_ID,PDO::PARAM_INT);
		$stmt->bindValue(":customerId",$ci,PDO::PARAM_INT);
		try{
			$stmt->execute();
			while(($row = $stmt->fetch(PDO::FETCH_ASSOC))!== false){

				$mappings[$row['us2_file_map_id']]= array("name"=>$row['us2_file_map_name'],"type"=>$row['data_type']);
			}
			$stmt->closeCursor();
		} catch (Exception $ex) {
			error_log($ex->getMessage());
		}




		if(isset($_POST['add_customers'])){
			$importType = $_POST["import_type"];
			if(!$ci){
				error_log("Missing CustomerId");

					$result = array("ReturnMessage", "Oops, something went wrong, it appears that the customer id is missing");
					return $this->renderText(json_encode($result));
					exit;
			}

			if(!$importType){
				error_log("Import Type Missing");

					$result = array("ReturnMessage", "Oops, something went wrong, it appears that the import type is missing");
					return $this->renderText(json_encode($result));
					exit;
			}

			$dataType = $mappings[$_POST['selected_map']]["type"];
			$importType = ($importType == "historical")?"_HIST":"";
			// If we are in the Asbury or CE store
			if (in_array(STORE_ID, array(ASBURY_STORE_ID, CE_STORE_ID))) {
				//require_once(SF_ROOT_DIR . '/apps/' . SF_APP . '/lib/AsburyImportShim.php');
				require_once(SF_ROOT_DIR."/lib/AsburyImportShim.php");
				$templatePath = SF_ROOT_DIR . "/data/asbury/";
				$destinationPath = SF_ROOT_DIR."/data/asbury/authenticom/";
				$templateDataType = "";
				$q = "SELECT * FROM `us2_upload_data_types` WHERE `us2_data_type` = :datatype";
				$tstmt = $conn->prepare($q);
				$tstmt->bindValue(":datatype",$dataType,PDO::PARAM_STR);
				try{
					$tstmt->execute();
					while(($row = $tstmt->fetch()) !== false){
						$templateName = $row['us2_data_type_template'];
						$templateDataType = $row['us2_authenticom_data_type'];
					}
					$templatePath .= $templateName;
				} catch (Exception $ex) {
					error_log($ex->getMessage());
				}
				/*
				switch ($dataType) {
					case"service":
						$templatePath .= "template_service.txt";
						$templateDataType = "SV";
						break;
					case "sale":
						$templatePath .= "template_sale.txt";
						$templateDataType = "SL";
						break;
					case "parts":
						$templatePath .= "template_parts.txt";
						$templateDataType = "PT";
						break;
					case "inventory":
						$templatePath .= "template_inventory.txt";
						$templateDataType = "INV";
						break;
					case "prospects":
						$templatePath .= "template_prospects.txt";
						$templateDataType = "PR";
						break;
					case "hvac_service_contract":
						$templatePath .= "template_hvac_service_contract.txt";
						$templateDataType = "HSC";
						break;
					case "test":
						$templatePath .= "template_test.txt";
						$templateDataType = "TST";
						break;
				}
				 *
				 */
				$destinationPath .= "{$ci}_{$templateDataType}_".date("Ymd_Gi")."{$importType}.txt";
				try {
					$shim = new AsburyImportShim($templatePath, $_FILES['source_file']['tmp_name'],$destinationPath);
					$this->TemplateLine = array();
					$this->FileHeaders = $shim->GetFileHeaders();#Move the cursor to the next line
					$this->TemplateHeaders = $shim->GetTemplateHeaders();
					$shim->WriteNextLine($this->TemplateHeaders);
				} catch (Exception $ex) {
					error_log($ex->getMessage());
					$result = array("ReturnMessage", $ex->getMessage());
					return $this->renderText(json_encode($result));
					exit;
				}

				if(!$this->TemplateHeaders){
					error_log("Missing File headers");
					$result = array("ReturnMessage", "Oops, something went wrong, it appears that the template file is missing");
					return $this->renderText(json_encode($result));
					exit;
				}




				$conn = new PDO("mysql:host=wilma;dbname=datawarehouse", "totouser", "leash4all");
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$q = "INSERT INTO `us2_customer_upload` "
					. "(`us2_customer_upload_user_id`,"
						. "`us2_customer_upload_type`,"
						. "`us2_customer_upload_date`,"
						. "`us2_customer_upload_approved_yn`,"
						. "`us2_customer_upload_file_location`,"
						. "`us2_customer_upload_stage_id`,"
						. "`us2_file_map_id`,"
						. "`us2_customer_upload_import_type`,`customer_id`) "
						. "VALUES (:userId,:customerType,NOW(),'N',:fileLoc,0,:mapId,:importType,:customer_id)";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":userId",$this->CurrentUserId,PDO::PARAM_INT);
				$stmt->bindValue(":customerType",$dataType,PDO::PARAM_STR);
				$stmt->bindValue(":fileLoc",$destinationPath,PDO::PARAM_STR);
				$stmt->bindValue(":mapId", $_POST['selected_map'],PDO::PARAM_INT);
				$stmt->bindValue(":importType",  strtoupper($_POST["import_type"]),PDO::PARAM_STR);
				$stmt->bindValue(":customer_id",$ci, PDO::PARAM_INT);
				$Us2CustomerUploadId = 0;
				try{
					$stmt->execute();
					$Us2CustomerUploadId = $conn->lastInsertId();
				} catch (Exception $ex) {
					error_log($ex->getMessage());
					$result = array("success"=>false,"ReturnMessage"=>"Oops, something went wrong while initiating file update.");
					return $this->renderText(json_encode($result));
					exit;
				}
				$stmt->closeCursor();
				$q = "SELECT `us2_source_field_name`, `us2_dest_field_name` "
					. "FROM `us2_file_map_fields` "
					. "JOIN `us2_file_map` ON `us2_file_map_fields`.`us2_file_map_id` = `us2_file_map`.`us2_file_map_id` "
					. "WHERE `us2_file_map`.`us2_file_map_id` = :mapId";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":mapId",$_POST['selected_map'],PDO::PARAM_INT);
				try{
					$stmt->execute();
				} catch (Exception $ex) {
					error_log($ex->getMessage());

					$q = "UPDATE `us2_customer_upload` SET `us2_customer_upload_stage_id` = 4 WHERE `us2_customer_upload_id` = :id";
					$stmt = $conn->prepare($q);
					$stmt->bindValue(":id",$Us2CustomerUploadId,PDO::PARAM_INT);
					$stmt->execute();

					$result = array("ReturnMessage" => "Oops, something went wrong while collecting the map information");
					return $this->renderText(json_encode($result));
					exit;
				}
				$destSource = array();
				while(($row = $stmt->fetch(PDO::FETCH_ASSOC))!== false){

					$destSource[$row['us2_dest_field_name']] = $row['us2_source_field_name'];
				}


				#Before we do anything else we will make sure that the required fields are in the files.
				$unmappedEntries = array();
				$totalRequiredFields = array();
				foreach($destSource as $dest => $source){

					if(in_array($dest, $this->requiredFields($dataType))){
						$totalRequiredFields[] = $source;
						if(!in_array($source, $this->FileHeaders)){
							#So if by any chance we do not get first or last name but we get the name column, uhg then we split the name column and populate it gere
							if(($dest == "CustomerFirstName" || $dest == "CustomerLastName") && in_array($destSource["CustomerName"],$this->FileHeaders)){
								#So it appears that the CustomerName field is mapped so we will try to get the first and last name from the customer name;
							}
							else{
								$unmappedEntries[] = $source;
							}

						}
					}

					#We now have to check for indexes.
					#If the index is provided in the mapped file, then it has to be provided here.
					#Otherwise, if it is not provided then we autogenerate it

					switch($dest){
						case "CustomerNumber":
						case "DealNumber":
						case "RONumber":
						case "ProspectNumber":
						case "SystemUnitId":
							if(!empty($source)){
								if(!in_array($source, $this->FileHeaders)){
									$unmappedEntries[] = $source;
								}
								$totalRequiredFields[] = $source;
							}

						break;
					}

				}

				if(count($unmappedEntries) > 0){
					error_log("The following required fields where not found in the provided file.<br/>".implode("<br/>",$unmappedEntries));
					$q = "UPDATE `us2_customer_upload` SET `us2_customer_upload_stage_id` = 4 WHERE `us2_customer_upload_id` = :id";
					$stmt = $conn->prepare($q);
					$stmt->bindValue(":id",$Us2CustomerUploadId,PDO::PARAM_INT);
					$stmt->execute();
					$c = Count($unmappedEntries);
					$rc = Count($totalRequiredFields);
					$uhe = implode("<br/>",$unmappedEntries);
					$trh = implode("<br/>",$totalRequiredFields);
					$msg = <<<HTML
<a tabindex="0" role="button" data-toggle="popover" data-trigger="focus" title="Missing Fields" data-content="$uhe">$c</a> out of $rc <a tabindex="0" role="button" data-toggle="popover" data-trigger="focus" title="Required Fields" data-content="$trh">required fields</a> not found.<br/>$uhe<br/>Please upload a file that contains those fields
HTML;
					$result = array("ReturnMessage" => $msg);
					return $this->renderText(json_encode($result));
					exit;
				}

				$initialDate = "";
				$endingDate = "";
				$lineNumber = 0;

				#service
				$invoiceTotal = 0;
				$warrantyTotal = 0;
				try {
					while (($line = $shim->GetNextFileLine()) !== false) {
						$lineNumber++;
						$authenticomLine = array();
						#crm specific values ughhhhh I see my self doing one of these for every new CRM
						if ($_POST['selected_map'] == 3 || $_POST['selected_map'] == 4) {
							#We need to get the warranty field if it has it
							if ($dataType == "service") {
								$wi = array_search("Warranty", $this->FileHeaders);
								$w = $line[$wi];
								$ai = array_search($destSource["ROAmount"], $this->FileHeaders);
								$a = $line[$ai];
								switch ($w) {
									case "Warranty":
										$warrantyTotal = $a;
										$invoiceTotal = 0;
										break;
									case "CustPay":
										$invoiceTotal = $a;
										$warrantyTotal = 0;
										break;
									default:
										$warrantyTotal = 0;
										$invoiceTotal = 0;
								}
							}
						}
						foreach ($this->TemplateHeaders as $index => $th) {
							if (AsburyImportShimUtilities::isAutogenField($th,$dataType,$ci)) {
								$authenticomLine[$index] = AsburyImportShimUtilities::getAutogenValue($th, $dataType, $ci);
								continue;
							}



							if (isset($destSource[$th]) && !empty($destSource[$th])) {
								$fileIndex = array_search($destSource[$th], $this->FileHeaders);
								if ($fileIndex !== false) {
									$authenticomLine[$index] = $line[$fileIndex] ? trim($line[$fileIndex]) : "";
								} else {
									$authenticomLine[$index] = "";
								}
							} else {
								$authenticomLine[$index] = "";
							}



							#Special settings for the file
							switch($th){
								case "CustomerNumber":
									if(empty($authenticomLine[$index])){
										$f = $destSource["CustomerFirstName"];
										$fi = array_search($f, $this->FileHeaders);
										$f = strtoupper($line[$fi]);
										$li = array_search($destSource["CustomerLastName"],$this->FileHeaders);
										$l = strtoupper($line[$li]);
										$ai = array_search($destSource["CustomerAddress"],$this->FileHeaders);
										$a = strtoupper($line[$ai]);
										$authenticomLine[$index] = md5("$f$l$a");
									}
									break;
								case "DealNumber":
									if(empty($authenticomLine[$index])){
										$f = $destSource["CustomerFirstName"];
										$fi = array_search($f, $this->FileHeaders);
										$f = strtoupper($line[$fi]);
										$li = array_search($destSource["CustomerLastName"],$this->FileHeaders);
										$l = strtoupper($line[$li]);
										$ai = array_search($destSource["CustomerAddress"],$this->FileHeaders);
										$a = strtoupper($line[$ai]);
										$authenticomLine[$index] = md5("$f$l$a");
									}
									break;
								case "RONumber":
									if(empty($authenticomLine[$index])){
										$ri = array_search($destSource["ClosedDate"],$this->FileHeaders);
										$r = strtotime($line[$ri]);
										$vi = array_search($destSource["VehicleVin"],$this->FileHeaders);
										$v = strtoupper($line[$vi]);
										$authenticomLine[$index] = md5("$r$v");
									}
									break;
								case "ProspectNumber":
									if(empty($authenticomLine[$index])){
										$fi = array_search($destSource["CustomerFirstName"],$this->FileHeaders);
										$f = strtoupper($line[$fi]);
										$li = array_search($destSource["CustomerLastName"],$this->FileHeaders);
										$l = strtoupper($line[$li]);
										$di = array_search($destSource["DateIn"],$this->FileHeaders);
										$d = strtotime($line[$di]);
										$authenticomLine[$index] = md5("{$f}{$l}{$d}Prospects");
									}
									break;
								case "SystemUnitId":
									if(empty($authenticomLine[$index])){
										$sii = array_search($destSource["SystemId"], $this->FileHeaders);
										$si = trim($line[$sii]);
										$authenticomLine[$index] = "$si-".microtime(true);
									}
									break;
								case "DealType":
									$enumValue = "Cash";
									if(preg_match("/lease/i",$line[$fileIndex])){
										$enumValue = "Lease";
									}
									elseif(preg_match("/(purch|loan)/i",$line[$fileIndex])){
										$enumValue = "Loan";
									}
									$authenticomLine[$index] = $enumValue;
									break;
								case "ContractDate":
								case "ClosedDate":
								case "DateIn":
								case "ContractStart":
									if(!$initialDate){
										$initialDate = date("Y-m-d",strtotime($authenticomLine[$index]));
									}
									else{
										$initialDate = min($initialDate, date("Y-m-d",strtotime($authenticomLine[$index])));
									}

									if(!$endingDate){
										$endingDate = date("Y-m-d",  strtotime($authenticomLine[$index]));
									}
									else{
										$endingDate = max($endingDate,date("Y-m-d",  strtotime($authenticomLine[$index])));
									}
									break;
								case "CustomerName":
									if(empty($authenticomLine[$index])){
										$fi = array_search($destSource["CustomerFirstName"],$this->FileHeaders);
										$li = array_search($destSource["CustomerLastName"],$this->FileHeaders);
										$authenticomLine[$index] = "{$line[$fi]} {$line[$li]}";
									}
									break;
								case "TradeVehicle":
									if(empty($authenticomLine[$index])){
										$tmakei = array_search($destSource["TradeVehicleMake"],$this->FileHeaders);
										$tmake = $line[$tmakei];
										$tmodeli = array_search($destSource["TradeVehicleModel"], $this->FileHeaders);
										$tmodel = $line[$tmodel];
										$tti = array_search($destSource["TradeVehicleTrim"],$this->FileHeaders);
										$tt = $line[$tti];
										$tmake = $tmake?$tmake:"";
										$tmodel = $tmodel?$tmodel:"";
										$tt = $tt?$tt:"";
										$authenticomLine[$index] = "$tmake $tmodel $tt";
									}
									break;
								case "ROAmount":
								case "CustomerPayRepairOrderTotal":
									$authenticomLine[$index] = $invoiceTotal;
									break;
								case "WarrantyRepairOrderTotal":
									$authenticomLine[$index] = $warrantyTotal;
									break;
								case "CustomerFirstName":
								case "CustomerLastName":
									if(empty($authenticomLine[$index])){
										$cni = array_search($destSource['CustomerName'], $this->FileHeaders);
										if(!empty($line[$cni])){
											$name = AsburyImportShimUtilities::getFirstAndLast($line[$cni]);
											$authenticomLine[$index]	= ($th == "CustomerFirstName")?$name[0]:$name[1];
										}
									}
									break;
								case "VehicleMileage":
									if(empty($authenticomLine[$index])){
										$authenticomLine[$index] = 0;
									}
									break;
							}


						}

						$shim->WriteNextLine($authenticomLine);
						foreach ($this->fileHeader as $i => $h) {
							if (!in_array($h, $destSource)) {
								$unmappedEntries[$lineNumber] = array($h => $line[$i]);
							}
						}
					}
				} catch (Exception $ex) {
					error_log($ex->getMessage());
					$q = "UPDATE `us2_customer_upload` SET `us2_customer_upload_stage_id` = 4 WHERE `us2_customer_upload_id` = :id";
					$stmt = $conn->prepare($q);
					$stmt->bindValue(":id",$Us2CustomerUploadId,PDO::PARAM_INT);
					$stmt->execute();
					$result = array("success"=>false,"ReturnMessage"=>"Oops, something went wrong while creating new file, please try again");
					return $this->renderText(json_encode($result));
					exit;
				}

				$q = "UPDATE `us2_customer_upload` "
					. "SET "
					. "`us2_customer_upload_stage_id` = 1 , "
					. "`us2_row_count` = :rowCount, "
					. "`us2_initial_date` = :initialDate, "
					. "`us2_ending_date` = :endingDate "
					. "WHERE `us2_customer_upload_id` = :id";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":id",$Us2CustomerUploadId,PDO::PARAM_INT);
				$stmt->bindValue(":rowCount",$shim->GetLinesWritten(),PDO::PARAM_INT);
				$stmt->bindValue(":initialDate",$initialDate, PDO::PARAM_STR);
				$stmt->bindValue(":endingDate", $endingDate, PDO::PARAM_STR);
				try{
					$stmt->execute();
				} catch (Exception $ex) {
					error_log($ex->getMessage());
					error_log($shim->GetLinesWritten());
					error_log($initialDate);
					error_log($endingDate);
					$q = "UPDATE `us2_customer_upload` SET `us2_customer_upload_stage_id` = 4 WHERE `us2_customer_upload_id` = :id";
					$stmt = $conn->prepare($q);
					$stmt->bindValue(":id",$Us2CustomerUploadId,PDO::PARAM_INT);
					$stmt->execute();
					$result = array("success"=>false,"ReturnMessage"=>"Oops, something went wrong while saving upload file, please try again.");
					return $this->renderText(json_encode($result));
					exit;
				}


				$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"] . "/?token=" . Convert::EncodeURL('Page=ConsumerUploads');
				$result = array("success"=>true,"url"=>$url);
				return $this->renderText(json_encode($result));
				exit;

			}
		}

		if(empty($mappings)){
			error_log("No mappings found - UploadCustomers");
			$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=CustomerMapping')."&ci={$ci}&action=add";
			$this->redirect($url);
			exit;
		}

		$this->CustomerId = $ci;
		$this->mappings = $mappings;

		return '_Success';exit;
	}
	public function executeCustomerMapping() {
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));
		$ci = $_GET["ci"]?$_GET['ci']:0;

		if (isset($_POST['add_new_map'])) {
			/*if(empty($ci)){
				error_log("Missing CustomerId");
				$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=Customers')." ";
				$result = array("success" => true, "url" => $url);
				return $this->renderText(json_encode($result));
				exit;
			}*/


			$File = $_FILES['source_file'];
			$pathinfo = pathinfo($File['name']);
			$extension = $pathinfo['extension'];

			$targetPath = SF_ROOT_DIR . '/web/files/';
			$targetPath .= time() . '_' . md5($File['name']) . ".$extension";

			if (move_uploaded_file($File['tmp_name'], $targetPath)) {

				$Us2Upload = new Us2Upload();
				$Us2Upload->setCustomerId(UPLOAD_CUSTOMER_ID);
				$Us2Upload->setFullpath($targetPath);
				$Us2Upload->setFilename($File['name']);
				$Us2Upload->setFiletype($File['type']);
				$Us2Upload->setFilesize($File['size']);
				$Us2Upload->setCreatedDate(date('Y-m-d H:i:s'));
				$Us2Upload->setCreatedByUserId($this->AccessControl->AmmsAuthUserId);
				$Us2Upload->setActiveYn('Y');
				$Us2Upload->save();

				$conn = new PDO("mysql:host=wilma;dbname=datawarehouse", "totouser", "leash4all");
				$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$q = "INSERT INTO `us2_file_map`(`us2_file_map_name`,`client_id`, `customer_id`, `data_type`, `added_by_user_id`, `added_date`, `active_yn`,`us2_upload_id`) "
						. "VALUES (:mapname,:clientId,:customerId,:dataType,:userId,NOW(),'Y', :uploadId)";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":mapname", $_POST['mapping_name'], PDO::PARAM_STR);
				$stmt->bindValue(":clientId", SF_CLIENT_ID, PDO::PARAM_INT);
				$stmt->bindValue(":customerId", $_POST['map_customer_id'], PDO::PARAM_INT);
				$stmt->bindValue(":dataType", $_POST['data_type'], PDO::PARAM_STR);
				$stmt->bindValue(":userId", $this->AccessControl->AmmsAuthUserId, PDO::PARAM_INT);
				$stmt->bindValue(":uploadId",$Us2Upload->getUs2UploadId(),PDO::PARAM_INT);
				try{
					$stmt->execute();
					$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"] . "/?token=" . Convert::EncodeURL('Page=MapFields') . "&ci={$ci}&mi={$conn->lastInsertId()}";
					$result = array("success" => true, "url" => $url);
					return $this->renderText(json_encode($result));
					exit;
				}
				catch(Exception $e){
					error_log($e->getMessage());
					$result = array("success"=>false);
					return $this->renderText(json_encode($result));
					exit;
				}
			}
			$result = array("success" => false);
			return $this->renderText(json_encode($result));
			exit;
		}
		elseif(isset($_POST['edit_map'])){
			/*if(empty($ci)){
				error_log("Missing CustomerId");
				$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=Customers')." ";
				$result = array("success" => true, "url" => $url);
				return $this->renderText(json_encode($result));
				exit;
			}*/
			if(empty($_GET['mi'])){
				error_log("Missing Map Id");
				$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=Customers')." ";
				$result = array("success" => true, "url" => $url);
				return $this->renderText(json_encode($result));
				exit;
			}
			$mi = $_GET['mi'];
			$conn = new PDO("mysql:host=wilma;dbname=datawarehouse", "totouser", "leash4all");
			$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$q = "SELECT `us2_file_map`.*,`filename` "
					. "FROM `us2_file_map` "
					. "LEFT JOIN `us2_upload` ON `us2_file_map`.`us2_upload_id` = `us2_upload`.`us2_upload_id` "
					. "WHERE `us2_file_map_id` = :id";
			$stmt= $conn->prepare($q);
			$stmt->bindValue(":id",$mi,PDO::PARAM_INT);
			try{
				$stmt->execute();
			} catch (Exception $ex) {
				error_log($ex->getMessage());
				$result = array("success" => false, "url" => $url);
				return $this->renderText(json_encode($result));
				exit;
			}

			while(($row = $stmt->fetch(PDO::FETCH_ASSOC))!== false){
				$oldname = $row['us2_file_map_name'];
				$oldtype = $row['data_type'];
				$oldfilename = $row['filename'];
				$oldclientId = $row['client_id'];
				$oldcustomerId = $row['customer_id'];
				$olduploadId = $row['us2_upload_id'];
				$oldactiveYn = $row['active_yn'];
			}
			$sets = array();
			$bv = array();
			$File = $_FILES['source_file'];
			if($File['name'] != $oldfilename){
				$pathinfo = pathinfo($File['name']);
				$extension = $pathinfo['extension'];
				$targetPath = SF_ROOT_DIR . '/web/files/';
				$targetPath .= time() . '_' . md5($File['name']) . ".$extension";
				if (move_uploaded_file($File['tmp_name'], $targetPath)) {

					$Us2Upload = new Us2Upload();
					$Us2Upload->setCustomerId(UPLOAD_CUSTOMER_ID);
					$Us2Upload->setFullpath($targetPath);
					$Us2Upload->setFilename($File['name']);
					$Us2Upload->setFiletype($File['type']);
					$Us2Upload->setFilesize($File['size']);
					$Us2Upload->setCreatedDate(date('Y-m-d H:i:s'));
					$Us2Upload->setCreatedByUserId($this->AccessControl->AmmsAuthUserId);
					$Us2Upload->setActiveYn('Y');
					$Us2Upload->save();
					$sets[] = "`us2_upload_id` = :uploadId";
					$bv[":uploadId"] = $Us2Upload->getUs2UploadId();
				}
			}
			if($oldname != $_POST['mapping_name']){
				$sets[] = "`us2_file_map_name` = :mapname";
				$bv[":mapname"] = $_POST['mapping_name'];
			}
			if($oldtype != $_POST['data_type']){
				$sets[] = "`data_type` = :datatype";
				$bv[":datatype"] = $_POST['data_type'];
			}
			if(!isset($_POST['active_yn']) || $_POST['active_yn'] != $oldactiveYn){
				$sets[] = "`active_yn` = :activeyn";
				$bv[":activeyn"] = ($_POST['active_yn'] == "Y")?"Y":"N";
			}
			if($oldcustomerId != $_POST['map_customer_id']){
				$sets[] = "`customer_id` = :mapCustomerId";
				$bv[":mapCustomerId"] =  $_POST['map_customer_id'];
			}
			if(!empty($sets)){
				$q = "UPDATE `us2_file_map` SET ".implode(" , ", $sets)." WHERE `us2_file_map_id` = :filemapId";
				$stmt = $conn->prepare($q);
				foreach($bv as $k => $v){
					$stmt->bindValue($k,$v);
				}
				$stmt->bindValue(":filemapId",$mi,PDO::PARAM_INT);
				try{
					$stmt->execute();
				} catch (Exception $ex) {
					error_log($ex->getMessage());
					error_log($q);
					$result = array("success" => false, "url" => $url);
					return $this->renderText(json_encode($result));
					exit;
				}

				$q = "INSERT INTO `us2_file_map_history` (`us2_file_map_id`, `us2_file_map_name`, `client_id`, `customer_id`, `data_type`, `changed_by_id`, `changed_date`, `us2_upload_id`) "
					. "VALUES (:mi, :name, :clientId, :ci, :type, :changedId, NOW(), :uploadId) ";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":mi", $mi, PDO::PARAM_INT);
				$stmt->bindValue(":name", $oldname, PDO::PARAM_STR);
				$stmt->bindValue(":clientId", SF_CLIENT_ID, PDO::PARAM_INT);
				$stmt->bindValue(":ci", $ci, PDO::PARAM_INT);
				$stmt->bindValue(":type", $oldtype, PDO::PARAM_STR);
				$stmt->bindValue(":changedId", $this->AccessControl->AmmsAuthUserId, PDO::PARAM_INT);
				$stmt->bindValue(":uploadId", $olduploadId, PDO::PARAM_INT);
				try{
					$stmt->execute();
					 $url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=CustomerMapping')."&ci={$ci}";
					$result = array("success"=>true, "url"=>$url);
					return $this->renderText(json_encode($result));
					exit;
				} catch (Exception $ex) {
					error_log($ex->getMessage());
					$result = array("success" => false, "url" => $url);
					return $this->renderText(json_encode($result));
					exit;
				}
			}


		}
		/*
		if(empty($ci)){
				error_log("Missing CustomerId");
				$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=Customers')." ";
				return $this->redirect($url);
				exit;
		}
		*/

		$this->getResponse()->setTitle('Customer Maps');
		$this->ActiveMenu = "Admin";
		$this->setTemplate('CustomerMapping');
		$this->CustomerId = $ci;




		if (@$_GET['action'] == "add") {
			return '_Add';
			exit;
		}
		elseif(@$_GET['action'] == "EditMap"){


			$mi = $_GET['mi'];
			if(empty($mi)){
				error_log("Map Id");
				$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=Customer');
				return $this->redirect($url);
				exit;
			}
			$conn = new PDO("mysql:host=wilma;dbname=datawarehouse", "totouser", "leash4all");
			$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$q = "SELECT `us2_file_map`.*,`filename` "
					. "FROM `us2_file_map` "
					. "LEFT JOIN `us2_upload` ON `us2_file_map`.`us2_upload_id` = `us2_upload`.`us2_upload_id` "
					. "WHERE `us2_file_map_id` = :id";
			$stmt= $conn->prepare($q);
			$stmt->bindValue(":id",$mi,PDO::PARAM_INT);
			try{
				$stmt->execute();
				while(($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false){

					$this->activeYn = $row['active_yn'];
					$this->name = $row['us2_file_map_name'];
					$this->filename = $row['filename'];
					$this->type = $row['data_type'];
					$this->mapCustomerId = $row['customer_id'];
				}
			}
			catch(Exception $ex){
				error_log($ex->getMessage());
			}

			$this->mapId = $mi;


			return '_EditMap';
			exit;
		}

		$mappings = array();
		$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$q = "SELECT * FROM `us2_file_map` WHERE `active_yn` = 'Y' AND `client_id` = :clientId AND `customer_id` IN (0,:customerId) ORDER BY `customer_id` DESC, `us2_file_map_id` DESC";
		$stmt = $conn->prepare($q);
		$stmt->bindValue(":clientId",SF_CLIENT_ID,PDO::PARAM_INT);
		$stmt->bindValue(":customerId",$ci,PDO::PARAM_INT);
		try{
			$stmt->execute();
			while(($row = $stmt->fetch(PDO::FETCH_ASSOC))!== false){
				$mappings[$row['us2_file_map_id']] = array("name"=>$row['us2_file_map_name'],"type"=>$row['data_type'], "mapCustomerId"=>$row['customer_id']);
			}
			$stmt->closeCursor();
		} catch (Exception $ex) {
			error_log($ex->getMessage());
		}


		if(empty($mappings)){
			$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"]."/?token=".Convert::EncodeURL('Page=CustomerMapping')."&ci={$ci}&action=add";
			$this->redirect($url);
			exit;
		}
		$this->mappings = $mappings;
		$this->CustomerId = $ci;
		return '_Success';
		exit;
	}

	public function executeMapFields() {
		$this->CheckAuthentication();
		$ci = $_GET["ci"]?$_GET['ci']:0;
		$mi = $_GET["mi"];

		/*if (empty($ci)) {
			error_log("Missing CustomerId MapFields");
			$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"] . "/?token=" . Convert::EncodeURL('Page=CustomerMapping') . "";
			return $this->redirect($url);
			exit;
		}*/

		if (empty($mi)) {
			error_log("Missing Map Id MapFields");
			$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"] . "/?token=" . Convert::EncodeURL('Page=CustomerMapping') . "&ci={$ci}";
			return $this->redirect($url);
			exit;
		}



		$conn = new PDO("mysql:host=wilma;dbname=datawarehouse", "totouser", "leash4all");
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


		$q = "SELECT `fullpath`,`data_type` FROM `us2_upload` "
				. "LEFT JOIN `us2_file_map` ON `us2_upload`.`us2_upload_id` = `us2_file_map`.`us2_upload_id` "
				. "WHERE `us2_file_map_id` = :mapId AND `us2_file_map`.`active_yn` = 'Y'";
		$stmt = $conn->prepare($q);
		$stmt->bindValue(":mapId", $mi, PDO::PARAM_INT);
		try {
			$stmt->execute();
		} catch (Exception $ex) {
			error_log($ex->getMessage());
		}

		while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
			$filePath = $row['fullpath'];
			$dataType = $row['data_type'];
		}



		$this->filepath = $filePath;
		if ($filePath) {
			$shim;
			// If we are in the Asbury or CE store
			if (in_array(STORE_ID, array(ASBURY_STORE_ID, CE_STORE_ID))) {
				//require_once(SF_ROOT_DIR . '/apps/' . SF_APP . '/lib/AsburyImportShim.php');
				require_once(SF_ROOT_DIR."/lib/AsburyImportShim.php");
				$templatePath = SF_ROOT_DIR . "/data/asbury/";
				$q = "SELECT `us2_data_type_template` FROM `us2_upload_data_types` WHERE `us2_data_type` = :datatype";
				$tstmt = $conn->prepare($q);
				$tstmt->bindValue(":datatype",$dataType,PDO::PARAM_STR);
				try{
					$tstmt->execute();
					while(($row = $tstmt->fetch()) !== false){
						$templateName = $row['us2_data_type_template'];
					}
					$templatePath .= $templateName;
				} catch (Exception $ex) {
					error_log($ex->getMessage());
				}
				/*
				switch ($dataType) {
					case"service":
						$templatePath .= "template_service.txt";
						break;
					case "sale":
						$templatePath .= "template_sale.txt";
						break;
					case "parts":
						$templatePath .= "template_parts.txt";
						break;
					case "inventory":
						$templatePath .= "template_inventory.txt";
						break;
					case "prospects":
						$templatePath .= "template_prospects.txt";
						break;
					case "hvac_service_contract":
						$templatePath .= "template_hvac_service_contract.txt";
						break;
					case "test":
						$templatePath .= "template_test.txt";
						break;
				}
				 * */
				try {
					$shim = new AsburyImportShim($templatePath, $filePath);
					$this->TemplateLine = array();
					$this->FileHeaders = $shim->GetFileHeaders();
					$this->TemplateHeaders = $shim->GetTemplateHeaders();
					$templateLine = $shim->GetNextTemplateLine();

					foreach ($this->TemplateHeaders as $k => $header) {
						if(AsburyImportShimUtilities::isAutogenField($header,$dataType,0)){
							unset($this->TemplateHeaders[$k]);
						}
						$this->TemplateLine[$header] = $templateLine[$k];
					}
				} catch (Exception $ex) {
					error_log($ex->getMessage());
				}
			}
		}
		$this->MappedFields = array();
		$q = "SELECT `us2_source_field_name`, `us2_dest_field_name` FROM `us2_file_map_fields` WHERE `us2_file_map_id` = :mapId AND `active_yn` = 'Y'";
		$stmt = $conn->prepare($q);
		$stmt->bindValue(":mapId", $mi, PDO::PARAM_INT);
		$stmt->execute();
		while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
			if (AsburyImportShimUtilities::isAutogenField($row['us2_dest_field_name'],$dataType,0)){continue;}
			$this->MappedFields[$row['us2_dest_field_name']] = $row['us2_source_field_name'];
		}

		$changedItems = array();
		$firstInsert = empty($this->MappedFields);

		if (isset($_POST['save_fields'])) {

			foreach ($_POST['fields'] as $templateHeader => $fileHeader) {
				$templateHeader = htmlentities($templateHeader);
				$fileHeader = htmlentities($fileHeader);
				if ($this->MappedFields[$templateHeader] !== $fileHeader) {
					$changedItems[] = $templateHeader;
				}
				$this->MappedFields[$templateHeader] = $fileHeader;
			}

			if ($changedItems && !$firstInsert) {

				$where = array();
				foreach ($changedItems as $dest) {
					$where[] = "`us2_dest_field_name` = '$dest'";
				}

				$q = "INSERT INTO `us2_file_map_fields_history` (`us2_file_map_field_id`, `us2_file_map_id`, `us2_source_field_name`, `us2_dest_field_name` , `added_by_user_id`, `added_date`) "
						. "SELECT `us2_file_map_field_id`, `us2_file_map_id`, `us2_source_field_name`, `us2_dest_field_name`, `added_by_user_id`, `added_date`  FROM `us2_file_map_fields` WHERE `us2_file_map_id` = :mi AND ((" . implode(") OR (", $where) . "))";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":mi",$mi,PDO::PARAM_INT);

				try {
					$stmt->execute();
				} catch (Exception $ex) {
					error_log($ex->getMessage() . PHP_EOL);
					//error_log($q . PHP_EOL);
				}
			}

			if ($firstInsert || $changedItems) {

				$values = array();
				$bindings = array();
				$count = 0;
				foreach ($this->MappedFields as $dest => $source) {
					if (!in_array($dest, $this->TemplateHeaders)) {
						$values[] = "(:id, :source{$count}, :dest{$count}, {$this->AccessControl->AmmsAuthUserId}, NOW(), 'N')";
					} else {
						$values[] = "(:id, :source{$count}, :dest{$count}, {$this->AccessControl->AmmsAuthUserId}, NOW(), 'Y')";
					}
					$bindings[":source{$count}"] = $source;
					$bindings[":dest{$count}"] = $dest;
					$count++;
				}
				$q = "INSERT INTO `us2_file_map_fields` (`us2_file_map_id`, `us2_source_field_name`, `us2_dest_field_name`, `added_by_user_id`, `added_date`,`active_yn`) "
						. "VALUES " . implode(",", $values) . " ON DUPLICATE KEY UPDATE "
						. "`us2_source_field_name` = VALUES(`us2_source_field_name`), `added_by_user_id` = VALUES(`added_by_user_id`), `added_date` = VALUES(`added_date`), active_yn = VALUES(`active_yn`)";
				$stmt = $conn->prepare($q);
				$stmt->bindValue(":id", $mi, PDO::PARAM_INT);
				foreach ($bindings as $k => $v) {
					$stmt->bindValue($k, $v);
				}
				try {
					$stmt->execute();
					$url = ( USE_HTTPS ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"] . "/?token=" . Convert::EncodeURL('Page=CustomerMapping') . "&ci={$ci}";
					$this->redirect($url);
					exit;
				} catch (Exception $ex) {
					error_log($ex->getMessage() . PHP_EOL);
					//error_log($q . PHP_EOL);
				}
			}
		}
		$this->ImportantFields = $this->importantFields($dataType);
		$this->RequiredFields = $this->requiredFields($dataType);
		$this->mapId = $mi;
		$this->getResponse()->setTitle('Map Fields');
		$this->ActiveMenu = "Admin";
		$this->setTemplate('MapFields');
		$this->CustomerId = $ci;

		return "_Success";
		exit;
	}

	public function executeConsumerUploads(){
		// TODO: $this->CheckAuthentication();
		$this->CheckAuthentication(array(SF_GUARD_GROUP_PREFIX.'ADMIN',SF_GUARD_GROUP_PREFIX.'CORP',SF_GUARD_GROUP_PREFIX.'DIST'));

		$this->DisplayCEClientSelector = true;

		$this->getResponse()->setTitle("Consumer Uploads");
		$this->setTemplate("ConsumerUploads");
		$this->ActiveMenu = "Admin";
		$this->ActiveTab = "WaitingApproval";
		return "_Success";exit;

	}

	public function executeDownloadCustomerUploadFile(){
		//So fputcsv in all its infinite wisdom decided to use \n instead of \r\n
		//so if the file is a txt then I have to converted over to csv at the last min so windows (the majority) can read it.

		$id = $_GET['file_id'];
		$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$q = "SELECT `us2_customer_upload_file_location` FROM `us2_customer_upload` WHERE `us2_customer_upload_id` = :id";
		$stmt = $conn->prepare($q);
		$stmt->bindValue(":id",$id,PDO::PARAM_INT);
		try {
			$stmt->execute();
		} catch (Exception $ex) {
			error_log($ex->getMessage());
			exit;
		}
		while(($row = $stmt->fetch(PDO::FETCH_ASSOC))!==false){
			$file = $row['us2_customer_upload_file_location'];
		}

		header('Content-Description: File Transfer');
		header('Content-Type: text/csv');
		header('Content-Disposition: attachment; filename="'.basename($file).'"');
		header('Expires: 0');
		header('Cache-Control: must-revalidate');
		header('Pragma: public');
		header('Content-Length: ' . filesize($file));
		readfile($file);
		exit;
	}

	public function executeFancyProductDesigner() {
		$this->CheckAuthentication();
		$this->hasAccess			= $this->AccessControl->hasGroup( array('ADMIN', 'STORE ADMIN', SF_GUARD_GROUP_PREFIX.'ADMIN' ));
		$this->getResponse()->setTitle("Product Designer");
		// $this->setLayout('dynamic'); $this->dynamic = true;
		$this->setTemplate("FancyProductDesigner");
/*
		$conn = new PDO("mysql:host=wilma;dbname=datawarehouse","totouser","leash4all");
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		// Products
		$Query	= "SELECT product_id, us2_product.name, small.preview_url AS small_image, large.preview_url AS large_image "
				. "FROM us2_product "
				. "LEFT JOIN us2_image AS small ON us2_product.small_image_id = small.us2_image_id "
				. "LEFT JOIN us2_image AS large ON us2_product.small_image_id = large.us2_image_id "
				. "WHERE us2_product.store_id = :store_id "
				. "AND us2_product.product_type_id IN (1,6) "
				. "AND us2_product.active_yn = 'Y' "
				. "AND us2_product.status_id = '2'";

		$stmt	= $conn->prepare($Query);
		$stmt->bindValue(":store_id", STORE_ID, PDO::PARAM_INT);
		$products	= array();

		try{
			$stmt->execute();
		} catch (Exception $ex) {
			error_log($ex->getMessage());
			exit;
		}
		while (($row = $stmt->fetch(PDO::FETCH_ASSOC))!==false) {
			$products[$row['product_id']]	= $row;
		}

		$this->arrayProduct = $products;
*/

		// Products
		$product_dir_name	= SF_ROOT_DIR."/web/images/amms_store/fancy_products";
		$product_dir_url		= "/images/amms_store/fancy_products/";
		$product_dir			= opendir($product_dir_name);
		$arrayProduct			= array();
		$arrayNo				= array(".", "..");
		while (false !== ($entry = readdir($product_dir))) {
			if (!in_array($entry, $arrayNo)) {
				$src				= "{$product_dir_url}{$entry}";
				$product			= array("name" => $entry, "small_image" => $src);
				$arrayProduct[]		= $product;
			}
		}
		$this->arrayProduct		= $arrayProduct;


		// die("<pre>".print_r($this->arrayProduct,true));

		// Designs
		$design_dir_name	= SF_ROOT_DIR."/web/images/amms_store/fancy_designs";
		$design_dir_url		= "/images/amms_store/fancy_designs/";
		$design_dir			= opendir($design_dir_name);
		$arrayDesign		= array();
		$arrayNo			= array(".", "..");
		while (false !== ($entry = readdir($design_dir))) {
			if (!in_array($entry, $arrayNo)) {
				$realpath			= "{$design_dir_name}/{$entry}";
				$src				= "{$design_dir_url}{$entry}";
				$title				= $entry;
				$size				= getimagesize($realpath);
				$x					= $size[0];
				$y					= $size[1];
				$colors				= "#000000";
				$html				= "<img src=\"{$src}\" title=\"{$title}\" data-parameters='\{\"x\": {$x}, \"y\": {$y}, \"colors\": \"{$colors}\", \"removable\": true, \"draggable\": true, \"rotatable\": true, \"resizable\": true, \"price\": 10 \}\' />";
				$arrayDesign[]		= $html;
			}
		}
		$this->arrayDesign		= $arrayDesign;

		return "_Success";exit;
	}

	private function AutogenFields($dt,$ci){
		$fields = array();
		$fields["ClientId"] = SF_CLIENT_ID;
		$fields["ClientDealerID"] = ($ci)?$ci:"N/A";


		switch($dt){
			case "service":
				$fields["FileType"] = "SV";
				break;
			case "sale":
				$fields["FileType"] = "SL";
				break;
			case "parts":
				$fields["FileType"] = "PT";
				break;
			case "inventory":
				$fields["FileType"] = "INV";
				break;
			case "prospects":
				$fields["FileType"] = "PR";
				break;
			case "hvac_service_contract":
				$fields["FileType"] = "HSC";
				$fields["ContractYn"] = "Y";
				break;
			case "test":
			default:
				$fields["DataType"] = "TEST";
				$fields["FileType"] = "TEST";
				break;
		}
		$fields["DMSType"] = "ADP";
		$fields["DataType"] = $dt;
		return $fields;
	}




	private function isAutogenField($field,$DataType,$CustomerId){
		$fields = self::AutogenFields($DataType,$CustomerId);
		return array_key_exists(trim($field), $fields);
	}

	private function getAutogenValue($field, $DataType, $CustomerId){
		$autogen = self::AutogenFields($DataType, $CustomerId);
		return $autogen[$field];
	}



	private function getRequiredFieldValue($field,$inVal,$DataType,$CustomerId){
		if($inVal){
			return $inVal;
		}
		$fields = self::RequiredFields($DataType,$CustomerId);
		return $fields[$field];
	}

	private function requiredFields($dataType){
		switch ($dataType) {
			case "service":
				$RequiredFields = array(
					"CustomerFirstName",
					"CustomerLastName",
					"CustomerAddress",
					"VehicleVin",
					"VehicleYear",
					"ClosedDate"
				);
				break;
			case "sale":
				$RequiredFields = array(
					"CustomerFirstName",
					"CustomerLastName",
					"CustomerAddress",
					"VehicleVin",
					"VehicleYear",
					"ContractDate",
					"FinalPaymentDate",
					"DealType",
					"VehicleType"
				);
				break;
			case "prospects":
				$RequiredFields = array(
					"CustomerFirstName",
					"CustomerLastName",
					"CustomerAddress"
				);
				break;
			case "hvac_service_contract":
				$RequiredFields = array(
					"CustomerFirstName",
					"CustomerLastName",
					"CustomerAddress",
					"ContractStart",
					"ContractExpire",
					"SystemId"
				);
				break;
			default:
				$RequiredFields = array();
				break;
		}
		return $RequiredFields;
	}

	private function importantFields($dataType){
		switch ($dataType) {
			case "service":
				$ImportantFields = array(
					"ROAmount", "CustomerPayRepairOrderTotal", "WarrantyRepairOrderTotal", "RONumber", "CustomerNumber"
				);
				break;
			case "sale":
				$ImportantFields = array(
					"DealNumber", "CashPrice", "InvoiceAmount", "Invoice Price","FrontGross","BackGross"
				);
				break;
			case "prospects":
				$ImportantFields = array(
					"ProspectNumber"
				);
				break;
			default:
				$ImportantFields = array();
				break;
		}
		return $ImportantFields;
	}

	private function getFirstAndLast($name){
		$cleanName = array();
		if(strpos($name,",") !== false){
			$name = explode(",",$name);
			$cleanName = array_reverse(array_map("trim",$name));
		}
		else{
			$name = explode(" ",$name);
			if(count($name)>1){
				$cleanName = array_map("trim",$name);
			}
			else{
				$cleanName = array("No First Name", "No Last Name");
			}
		}
		return $cleanName;
	}
}
