<?php
require_once(SF_ROOT_DIR . "/lib/checkAuth.class.php");
require_once(SF_ROOT_DIR . DIRECTORY_SEPARATOR.'classes'. DIRECTORY_SEPARATOR.'class.dmsd.php');
require_once(SF_ROOT_DIR . DIRECTORY_SEPARATOR.'classes'. DIRECTORY_SEPARATOR.'class.dms_functions.php');
require_once(SF_ROOT_DIR . DIRECTORY_SEPARATOR.'classes'. DIRECTORY_SEPARATOR.'class.customer_profile.php');
require_once(SF_ROOT_DIR . DIRECTORY_SEPARATOR.'classes'. DIRECTORY_SEPARATOR.'class.trigger_definitions.php');






class TriggerControllerAction extends sfActions
{
	protected static $NEW_HVAC_TRIGGERS = array(48, 49, 50, 51);

	public function Get($name)
	{
		return $this->GetRequestParameter($name);
	}


	public function preExecute()
	{
		$this->AccessControl = new AccessControl($this);
		$this->DisablePrototype=true;
		$this->UpdateJQuery='
		<link rel="stylesheet" href="/css/ui/1.10.3/themes/smoothness/jquery-ui.css" />
		<script src="/js/jquery-1.9.1.js"></script>
		<script src="/js/ui/1.10.3/jquery-ui.js"></script>';

		$this->dmstrigconn = Propel::GetConnection('dms_main');
		$this->dmstrigsqlconn = $this->dmstrigconn->getResource();
	}

	private function DoLog($message) {
		error_log(date('Y-m-d H:i:s ').$message."\n", 3, SF_ROOT_DIR."/log/TriggerControllerAction.log");
	}

	public function execute()
	{
		$Auth = new checkAuth();
		$Auth->_groups = array('Admin');
		$Auth->_permissions	= array();
		$Auth->_user = $this->getUser();
		if (!$Auth->isAuthenticated()) {
			return $this->forward('default', 'NoAccess');
		}
		if ($this->getUser()->getGuardUser()) {
			$this->curuser = $this->getUser()->getGuardUser()->getId();
		}
		if ($this->getUser()->getGuardUser()) {
			$this->curgroups = $this->getUser()->getGuardUser()->getGroups();
		}

		if (!$this->getUser()->hasAttribute('customer_id')) {
			$this->redirect('TrigCustomer/TriggerSelectCustomer');
		} else {
			$this->customer_id = $this->getUser()->getAttribute('customer_id');
		}
		$this->customer_name = $this->getUser()->getAttribute('customer_name');

		$this->title = $this->customer_name . " Trigger Campaign Controller";
		$this->subtitle = "";

		// echo "<pre>_POST = " . print_r($_POST, true) . "</pre><br />";
		// echo "<pre>_GET = " . print_r($_GET, true) . "</pre><br />";

		# Check Auth

//		$arrayTriggerInVersion2 = array(1,5,14,20,32,19,31,33,9,8,7,12,6,15,34,16);
		$this->PageVersion = 2;

		//$this->title = 'Trigger Campaign Controller';

		//If no customer ID in session, then the only place to go is the customer selection view.
		//Otherwise, get and store the customer ID.

		// Adding / removing brand overrides from trigger
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		if ($this->GetRequestParameter('AddBrand') || $this->GetRequestParameter('RemoveBrand')) {
			$this->forward('TrigCustomer', 'TriggerAddBrand'); exit;
		}

		// Save settings
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		if ($this->GetRequestParameter('SaveSettings')) {
			$TriggerId  = $this->getRequestParameter('form');
			$Brand		= $this->getRequestParameter('brand');
			$Contract	= $this->getRequestParameter('contract');
			$this->SaveForm($TriggerId);

			if (!empty($Contract)) {
				$Contract = "/contract/".urlencode($Contract);
			} else {
				$Contract = '';
			}
			// die("SaveSettings - Aborting\n");
			$this->redirect("/TrigCustomer/TriggerController/form/$TriggerId/brand/$Brand".$Contract);
			exit;
		}


		//If the form parameter is set, we're going to build a settings form.
		//Get basic config and filter info using the trigger_name_id passed in the form parameter.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

		if ($this->getRequestParameter('forcedsave') == "true") {
			$theform = $this->getRequestParameter('form');
			$this->{"saveForm" . $theform}();
			$this->redirect("/TrigCustomer/TriggerController/form/$theform");
		}
		if ($this->getRequest()->getParameterHolder()->has('form'))
		{
			$form 			= intval($this->getRequestParameter('form'));
			$this->form 	= intval($this->getRequestParameter('form'));
			$this->level 	= intval($this->getRequestParameter('level'));

			define("FORM", $this->form);
			//This variable is used in views for backlinking.
			$this->id = intval($this->getRequestParameter('form'));

			//This query gets all the basic trigger and filter info for the trigger id given in the form parameter.
			$sql = "
					SELECT		trigger_name.name,
								trigger_name.vehicle_filter_type_id,
								trigger_name.trigger_parameter_filter_1,
								trigger_name.trigger_parameter_filter_2,
								trigger_name.trigger_parameter_filter_3,
								trigger_name.trigger_parameter_filter_4,
								trigger_name.trigger_parameter_filter_5,
								trigger_name.trigger_parameter_filter_6,
								trigger_name.level_count, trigger_name.backend_class,
								trigger_filter_config.TRIGGER_FILTER_CONFIG_ID,
								trigger_filter_config.PARTIAL_PATH AS filters
					FROM		trigger_name
					LEFT JOIN	trigger_filter_config
					ON			(
									trigger_name.VEHICLE_FILTER_TYPE_ID     = trigger_filter_config.TRIGGER_FILTER_CONFIG_ID OR
									trigger_name.TRIGGER_PARAMETER_FILTER_1 = trigger_filter_config.TRIGGER_FILTER_CONFIG_ID OR
									trigger_name.TRIGGER_PARAMETER_FILTER_2 = trigger_filter_config.TRIGGER_FILTER_CONFIG_ID OR
									trigger_name.TRIGGER_PARAMETER_FILTER_3 = trigger_filter_config.TRIGGER_FILTER_CONFIG_ID OR
									trigger_name.TRIGGER_PARAMETER_FILTER_4 = trigger_filter_config.TRIGGER_FILTER_CONFIG_ID OR
									trigger_name.TRIGGER_PARAMETER_FILTER_5 = trigger_filter_config.TRIGGER_FILTER_CONFIG_ID OR
									trigger_name.TRIGGER_PARAMETER_FILTER_6 = trigger_filter_config.TRIGGER_FILTER_CONFIG_ID
								)
					WHERE		trigger_name.TRIGGER_NAME_ID=$form";

			$result = mysql_query($sql, $this->dmstrigsqlconn) or die($sql . "\r\n" . mysql_error($this->dmstrigsqlconn) );
			$partials = array();
			while ($row = mysql_fetch_array($result))
			{
				//Set some basic variables for use in titles and subtitles.
				$this->title = $this->customer_name . " Trigger Campaign Controller | " . $row["name"] . " Trigger";
				$this->subtitle = $row["name"];
				//Get the filter name strings in the GROUP_CONCAT field.
				//$this->filters = explode(',',$row["filters"]);
				$this->vFilterId = $row["vehicle_filter_type_id"];
				$this->FilterId1 = $row["trigger_parameter_filter_1"];
				$this->FilterId2 = $row["trigger_parameter_filter_2"];
				$this->FilterId3 = $row["trigger_parameter_filter_3"];
				$this->FilterId4 = $row["trigger_parameter_filter_4"];
				$this->FilterId5 = $row["trigger_parameter_filter_5"];
				$this->FilterId6 = $row["trigger_parameter_filter_6"];
				$partials[(string)$row["TRIGGER_FILTER_CONFIG_ID"]] = $row["filters"];
			}

			$this->vehiclefilter = $partials[$this->vFilterId];
			$this->filters = array();
			foreach ($partials as $index => $value)
			{
				if ($index != 0 && $value != "" && $index != $this->vFilterId)
				$this->filters[] = $value;
			}

			$this->arrayFilterName = array();
			$C = new Criteria;
			$C->addSelectColumn(TriggerFilterConfigPeer::NAME);
			$C->addSelectColumn(TriggerFilterConfigPeer::PARTIAL_PATH);
			$C->addAnd(TriggerFilterConfigPeer::NAME, '', Criteria::NOT_EQUAL);
			$Rs = TriggerFilterConfigPeer::doSelectRs($C, $this->dmstrigconn);
			while ($Rs->next()) {
				$this->arrayFilterName[$Rs->get(2)] = $Rs->get(1);
			}

			//die(print_r($this->filters));
		}

		//If the nav parameter is set, we're displaying the control navigation page.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		elseif ($this->getRequest()->getParameterHolder()->has('nav'))
		{
			$form = intval($this->getRequestParameter('nav'));
			//This variable is used in views for backlinking.
			$this->id = intval($this->getRequestParameter('nav'));
			//For the basic navigation page for each trigger, we only need the trigger name for titles.
			$sql = "SELECT trigger_name.name FROM trigger_name WHERE trigger_name.TRIGGER_NAME_ID=$form ORDER BY display_order_id";
			$result = mysql_query($sql, $this->dmstrigsqlconn) or die($sql . "\r\n" . mysql_error($this->dmstrigsqlconn) );
			$row = mysql_fetch_array($result);
			$this->title = $this->customer_name . " Trigger Campaign Controller | " . $row["name"] . " Trigger";
			$this->subtitle = $row["name"];
		}

		//If the history parameter is set, we're looking for the update history of a trigger.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		elseif ($this->getRequest()->getParameterHolder()->has('uhistory'))
		{
			require_once("TriggerEmailDrop.php");
			$this->uhistorySettings = array();
			$this->uhistorySettings["mailSelect"] = $this->mailSelect;
			//This variable is used in views for backlinking.
			$this->id = intval($this->getRequestParameter('uhistory'));
			$form = $this->id;
			$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, $this->getRequestParameter('uhistory'), $this->dmstrigconn);
			$this->uhistorySettings["trigger_id"] = $this->TriggerSettingId;
			//This query gets all the basic trigger and filter info for the trigger id given in the form parameter.
			$sql = "SELECT name FROM trigger_name WHERE trigger_name_id=$form";
			$result = mysql_query($sql, $this->dmstrigsqlconn) or die($sql . "\r\n" . mysql_error($this->dmstrigsqlconn) );
			$row = mysql_fetch_array($result);
			//Set some basic variables for use in titles and subtitles.
			$this->title = $this->customer_name . " Trigger Campaign Controller | " . $row["name"] . " Trigger";
			$this->subtitle = $row["name"] . " Trigger Update History";

			$sql = "SELECT * FROM trigger_setting_log WHERE trigger_name_id=$form AND customer_id = " . $this->customer_id;
			$result = mysql_query($sql, $this->dmstrigsqlconn) or die($sql . "\r\n" . mysql_error($this->dmstrigsqlconn) );
			$this->uhistorySettings["result"] = $result;
		}

		//If the deactivate parameter is set, we're deactivating a trigger.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		elseif ($this->getRequest()->getParameterHolder()->has('deactivate'))
		{
			$this->TriggerSetting = TriggerSettingPeer::retrieveByPK(intval($this->getRequestParameter('deactivate')),$this->dmstrigconn);
			$this->TriggerSetting->setEnabledYn("N");
			$this->TriggerSetting->save($this->dmstrigconn);

			if ($this->getRequestParameter('redirect')==2)
				$this->redirect('TrigCustomer/TriggerController?form=' . intval($this->getRequestParameter('trigname')));
			else
				$this->redirect('TrigCustomer/TriggerController?nav=' . intval($this->getRequestParameter('trigname')));

		}

		//If the activate parameter is set, we're activating a trigger.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		elseif ($this->getRequest()->getParameterHolder()->has('activate'))
		{
			$this->TriggerSetting = TriggerSettingPeer::retrieveByPK(intval($this->getRequestParameter('activate')),$this->dmstrigconn);
			$this->TriggerSetting->setEnabledYn("Y");
			$this->TriggerSetting->save($this->dmstrigconn);

			if ($this->getRequestParameter('redirect')==2)
				$this->redirect('TrigCustomer/TriggerController?form=' . intval($this->getRequestParameter('trigname')));
			else
				$this->redirect('TrigCustomer/TriggerController?nav=' . intval($this->getRequestParameter('trigname')));
		}

		//If the approval parameter is set, we're going to display the approval queue for a trigger.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		elseif ($this->getRequest()->getParameterHolder()->has('approval'))
		{
			if ($this->hasRequestParameter("customer_id")) {
				$this->customer_id = $this->getRequestParameter("customer_id");
				$this->getUser()->setAttribute('customer_id', $this->customer_id);
			} else {
				$this->customer_id = $this->getUser()->getAttribute('customer_id');
			}

			//This variable is used in views for backlinking.
			$this->id = intval($this->getRequestParameter('approval'));
			$form = $this->id;
			$this->approvalSettings = array();
			$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, $this->getRequestParameter('approval'), $this->dmstrigconn);
			$this->approvalSettings["trigger_id"] = $this->TriggerSettingId;
			//This query gets all the basic trigger and filter info for the trigger id given in the form parameter.
			$sql = "SELECT name FROM trigger_name WHERE trigger_name_id=$form";
			$result = mysql_query($sql, $this->dmstrigsqlconn) or die($sql . "\r\n" . mysql_error($this->dmstrigsqlconn) );
			$row = mysql_fetch_array($result);
			//Set some basic variables for use in titles and subtitles.
			$this->title = $this->customer_name . " Trigger Campaign Controller | " . $row["name"] . " Trigger";
			#$this->subtitle = $row["name"] . " Trigger Approval Queue";
			$this->subtitle = $row["name"];
			$this->approvalSettings["customer_id"] = $this->customer_id;
			$this->approvalSettings['query1'] = "";
			$this->approvalSettings["curuser"] = $this->curuser;
			$this->approvalSettings["curgroups"] = $this->curgroups;

			//$arrayBatches		= array();

			if ($this->customer_id > 0)
			{
				$databaseManager = new sfDatabaseManager();
				$databaseManager->initialize();

				$CDmsd = new Dmsd();
				$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);
				$this->dms_master_conn = $dms_master_conn;

				$arrayId		= array();
				$arrayBatches	= array();
				$query 			= "SELECT trigger_batch_id FROM trigger_batch WHERE trigger_name_id='$this->id' ORDER BY DATE(created_date) DESC, level DESC LIMIT 1000 ";
				$this->approvalSettings['query1'] = $query;
				$rs				= $this->dms_master_conn->executeQuery($query);
				while ($rs->next())
					$arrayBatches[] = TriggerBatchPeer::retrieveByPk($rs->get('trigger_batch_id'), $dms_master_conn);



//				$C = new Criteria();
//				$C->add(TriggerBatchPeer::TRIGGER_NAME_ID,$this->getRequestParameter('approval'));
//				$C->addDescendingOrderByColumn(TriggerBatchPeer::CREATED_DATE);
//				$C->addDescendingOrderByColumn(TriggerBatchPeer::LEVEL);
//				$this->batchList = TriggerBatchPeer::doSelect($C,$dms_master_conn);
//				$this->approvalSettings["batchList"] = $this->batchList;

				$this->approvalSettings["batchList"] = $arrayBatches;
				$this->loadNav($this->id);
			}
		}

		//If the edit parameter is set, we're going to edit a trigger batch.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		elseif ($this->getRequest()->getParameterHolder()->has('edit'))
		{
			$this->editSettings = array();

			//This variable is used in views for backlinking.
			$this->id = intval($this->getRequestParameter('nameid'));
			$this->editid = intval($this->getRequestParameter('edit'));
			$form = $this->id;
			$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, $this->getRequestParameter('nameid'), $this->dmstrigconn);
			$this->nameid = $this->getRequestParameter('nameid');
			$this->editSettings["trigger_id"] = $this->TriggerSettingId;
			$this->editSettings["id"] = $this->editid;
			$this->editSettings["nameid"] = $this->nameid;
			//This query gets all the basic trigger and filter info for the trigger id given in the form parameter.
			$sql = "SELECT name FROM trigger_name WHERE trigger_name_id=$form";
			$result = mysql_query($sql, $this->dmstrigsqlconn) or die($sql . "\r\n" . mysql_error($this->dmstrigsqlconn) );
			$row = mysql_fetch_array($result);
			//Set some basic variables for use in titles and subtitles.
			$this->title = $this->customer_name . " Trigger Campaign Controller | " . $row["name"] . " Trigger Batch Criteria Edit";
			$this->subtitle = $row["name"] . " Batch Criteria Edit";

			if ($this->customer_id > 0)
			{
				$databaseManager = new sfDatabaseManager();
				$databaseManager->initialize();

				$CDmsd = new Dmsd();
				$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);

				$C = new Criteria();
				$C->add(TriggerBatchPeer::TRIGGER_BATCH_ID,$this->getRequestParameter('edit'));
				$this->batch = TriggerBatchPeer::doSelectOne($C,$dms_master_conn);
				$this->editSettings["batch"] = $this->batch->getTriggerCriteria();
			}
		}

		//If the proof parameter is set, we're going to display criteria for a batch, and why the batch names met said criteria.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		elseif ($this->getRequest()->getParameterHolder()->has('proof'))
		{
			//This variable is used in views for backlinking.
			$this->id = intval($this->getRequestParameter('nameid'));
			$this->detailsid = intval($this->getRequestParameter('proof'));
			$form = $this->id;
			$this->proofSettings = array();

			$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, $this->getRequestParameter('nameid'), $this->dmstrigconn);
			$this->nameid = $this->getRequestParameter('nameid');
			$this->proofSettings["trigger_id"] = $this->TriggerSettingId;
			$this->proofSettings["id"] = $this->detailsid;
			$this->proofSettings["nameid"] = $this->nameid;
			//This query gets all the basic trigger and filter info for the trigger id given in the form parameter.
			$sql = "SELECT name FROM trigger_name WHERE trigger_name_id=$form";

			$result = mysql_query($sql, $this->dmstrigsqlconn) or die($sql . "\r\n" . mysql_error($this->dmstrigsqlconn) );
			$row = mysql_fetch_array($result);
			//Set some basic variables for use in titles and subtitles.
			$this->title = $this->customer_name . " Trigger Campaign Controller | " . $row["name"] . " Trigger";
			$this->subtitle = $row["name"] . " Batch Proof";

			if ($this->customer_id > 0)
			{
				//$databaseManager = new sfDatabaseManager();
				//$databaseManager->initialize();

				$this->theconn = Propel::GetConnection('dms_main');
				$CDmsd = new Dmsd();
				$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);

				$Wilma = Propel::GetConnection();
				$sql = "SELECT client_id FROM customer WHERE customer_id = '{$this->customer_id}'";
				$Rs = $Wilma->executeQuery($sql);
				while ($Rs->next())
				{
					$this->client_id = $Rs->get('client_id');
				}

				$C = new Criteria();
				$C->add(TriggerBatchPeer::TRIGGER_BATCH_ID,$this->getRequestParameter('proof'));
				$this->batch = TriggerBatchPeer::doSelectOne($C,$dms_master_conn);
				$this->proofSettings["batch"] = $this->batch;
				$this->createdDate = $this->proofSettings["batch"]->getCreatedDate();
				$this->createdDateYmd = date('Y-m-d',strtotime($this->createdDate));

				$C = new Criteria();
				$C->add(TriggerBatchListPeer::TRIGGER_BATCH_ID,$this->getRequestParameter('proof'));
				$C->addAscendingOrderByColumn(TriggerBatchListPeer::LAST);
				$C->addAscendingOrderByColumn(TriggerBatchListPeer::FIRST);
				$C->addAscendingOrderByColumn(TriggerBatchListPeer::FULL_NAME);
				$this->batchList = TriggerBatchListPeer::doSelect($C,$dms_master_conn);
				$this->proofSettings["batchList"] = $this->batchList;

				$this->proofSettings["crit"] = unserialize($this->proofSettings["batch"]->getTriggerCriteria());
				$this->proofSettings["level"] = $this->proofSettings["batch"]->getLevel();
				//die(print_r($this->proofSettings));
				$filterList = implode(',',array_keys($this->proofSettings["crit"]["filters"]));

				$this->proofSettings["filterList"] = array();
				$this->proofSettings["filterList"]["Run Date"] = date('Y-m-d',strtotime($this->proofSettings["crit"]["rundate"]));

				$sql = "SELECT trigger_filter_config_id,name FROM dms.trigger_filter_config WHERE trigger_filter_config_id IN (" . $filterList . ")";

				$result = mysql_query($sql, $this->dmstrigsqlconn) or die($sql . "\r\n" . mysql_error($this->dmstrigsqlconn));

				while ($row = mysql_fetch_array($result))
				{
					$temp = array();
					$temp = $this->proofSettings["crit"]["filters"][$row["trigger_filter_config_id"]][$this->proofSettings["level"]];
					$this->proofSettings["filterList"][$row["name"]] = $temp;
				}
				//die(print_r($this->proofSettings));
				//$custids = array();
				$this->extInfo = array();
				//foreach ($this->proofSettings["batchList"] as $batch)
				//$vins[$batch->getExternalCustomerId()] = $batch->getVin();

				foreach ($this->proofSettings["batchList"] as $batch)
				{
					$vins[$batch->getExternalCustomerId()] = $batch->getDmsVehicleId();
					$id = $batch->getTriggerBatchListId();
					if ($batch->getLast() == "")	$name = $batch->getFullName();
					else
					{
						$name = $batch->getLast();
						if ($batch->getFirst() != "") $name .= ", " . $batch->getFirst();
						if ($batch->getMiddle() != "") $name .= " " . $batch->getMiddle();
					}
					$temp = array();
					$temp["name"] = $name;
					$temp["phone"] = $batch->getVoicePhone();
					$temp["sms"] = $batch->getSmsPhone();
					$temp["email"] = $batch->getEmailAddress();
					$temp["address"] = $batch->getAddress() . " " . $batch->getCity() . ", " . $batch->getState() . " " . $batch->getZip();
					$temp["birthday"]	= $this->getBirthday($batch->getExternalCustomerId(),$dms_master_conn);

					$this->extInfo[$batch->getExternalCustomerId()]["customer"] = $temp;
				}

				// If this is HVAC
				if ($this->client_id == 509)
				{
					// HVAC
					$CDmsd = new Dmsd();
					$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);

					$sql	= "SELECT * FROM "
								. "(SELECT external_customer_id, dms_vehicle_id, external_systemunit_id, contract_name, contract_start, contract_expire "
								. "FROM amms_system_detail ORDER BY external_systemunit_id DESC) AS a "
							. "GROUP BY dms_vehicle_id, external_customer_id";

					$Rs		= $dms_master_conn->executeQuery($sql);
					$arrayContract = array();
					while ($Rs->next())
					{
						$arrayContract[$Rs->get('dms_vehicle_id')]	= $Rs->getRow();
					}

					$this->proofSettings["arrayContract"] = $arrayContract;

					foreach ($vins as $custid => $id)
					{
						$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);

						$sql	= "SELECT dms_vehicle.*, amms_system_detail.contract_name, amms_system_detail.contract_start, amms_system_detail.contract_expire "
								. "FROM dms_vehicle LEFT JOIN amms_system_detail ON dms_vehicle.dms_vehicle_id = amms_system_detail.dms_vehicle_id "
								. "WHERE dms_vehicle.dms_vehicle_id = '{$id}'";

						$this->vehicles = $dms_master_conn->executeQuery($sql);
						if ($this->vehicles->next())
						{
							$temp1 = array();
							$dms_vehicle_id = $this->vehicles->getString('dms_vehicle_id');
							$temp1["dms_vehicle_id"] = $this->vehicles->getString('dms_vehicle_id');
							$temp1["contract_name"] = $this->vehicles->getString('contract_name');
							$temp1["contract_start"] = $this->vehicles->getString('contract_start');
							$temp1["contract_expire"] = $this->vehicles->getString('contract_expire');
							$temp1["make"] = $this->vehicles->getString('vehicle_make');
							$temp1["external_customer_id"] = $this->vehicles->getString('external_customer_id');
							$this->extInfo[$custid]["vehicle"] = $temp1;

							$sql = "SELECT * FROM dms_ro WHERE dms_customer_id = '{$custid}' AND dms_vehicle_id = '{$dms_vehicle_id}' AND DATE(open_date) <= '{$this->createdDateYmd}' ORDER BY open_date DESC";

							$statement = $dms_master_conn->prepareStatement($sql);
							$ros = $statement->executeQuery();

							while ($ros->next())
							{
								$temp2 = array();
								$temp2["dms_vehicle_id"] = $ros->getString('dms_vehicle_id');
								$temp2["open_date"] = $ros->getString('open_date');
								$temp2["op_codes"] = $ros->getString('op_codes');
								$this->extInfo[$custid]["ros"][$ros->getString('repair_order_id')] = $temp2;
							}

							$sql = "SELECT * FROM dms_deal WHERE dms_customer_id = '{$custid}' AND dms_vehicle_id = '{$dms_vehicle_id}' AND sold_date <= '{$this->createdDate}' ORDER BY sold_date DESC";

							$statement = $dms_master_conn->prepareStatement($sql);
							$deals = $statement->executeQuery();
							while ($deals->next())
							{
								$temp3 = array();
								$temp3["dms_vehicle_id"] = $deals->getString('dms_vehicle_id');
								$temp3["sold_date"] = $deals->getString('sold_date');
								$this->extInfo[$custid]["deals"][$deals->getString('dms_deal_id')] = $temp3;
							}
						}
					}
				}
				else
				{
					// Automotive, etc.
					foreach ($vins as $custid => $id)
					{
						//$sql = "SELECT * FROM dms_vehicle WHERE vin = '" . $id . "' AND external_customer_id = '" . $custid . "'";
						$CDmsd = new Dmsd();
						$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);
						$sql = "SELECT * FROM dms_vehicle WHERE dms_vehicle_id = '" . $id . "'";

						$statement = $dms_master_conn->prepareStatement($sql);
						$this->vehicles = $statement->executeQuery();
						//die(print_r($this->vehicles));
						if ($this->vehicles->next())
						{
							$temp1 = array();
							$dms_vehicle_id = $this->vehicles->getString('dms_vehicle_id');
							$temp1["dms_vehicle_id"] = $this->vehicles->get('dms_vehicle_id');
							$temp1["year"] = $this->vehicles->getString('vehicle_year');
							$temp1["make"] = $this->vehicles->getString('vehicle_make');
							$temp1["model"] = $this->vehicles->getString('vehicle_model');
							$temp1["vin"] = $this->vehicles->getString('vin');
							$temp1["owned"] = $this->vehicles->getString('currently_owned');
							$temp1["external_customer_id"] = $this->vehicles->getString('external_customer_id');
							$temp1["mileage"] = $this->vehicles->getString('mileage');
							$this->extInfo[$custid]["vehicle"] = $temp1;

							$sql = "SELECT * FROM dms_ro WHERE dms_customer_id = '{$custid}' AND dms_vehicle_id = '{$dms_vehicle_id}' AND DATE(open_date) <= '{$this->createdDateYmd}' ORDER BY open_date DESC";

							//echo $sql . "<br>";
							$statement = $dms_master_conn->prepareStatement($sql);
							$ros = $statement->executeQuery();
							//die(print_r($ros));
							while ($ros->next())
							{
								$temp2 = array();
								$temp2["dms_vehicle_id"] = $ros->getString('dms_vehicle_id');
								$temp2["open_date"] = $ros->getString('open_date');
								$temp2["op_codes"] = $ros->getString('op_codes');
								$temp2["mileage"] = $ros->getString('mileage');
								$temp2["warranty_expiration_miles"] = $ros->getString('warranty_expiration_miles');
								$temp2["warranty_expiration_date"] = $ros->getString('warranty_expiration_date');
								//$goo = print_r($temp2, true);
								//echo nl2br($goo);
								//die();
								$this->extInfo[$custid]["ros"][$ros->getString('repair_order_id')] = $temp2;
							}

							$sql = "SELECT * FROM dms_deal WHERE dms_customer_id = '{$custid}' AND dms_vehicle_id = '{$dms_vehicle_id}' AND sold_date <= '{$this->createdDate}' ORDER BY sold_date DESC";

							$statement = $dms_master_conn->prepareStatement($sql);
							$deals = $statement->executeQuery();
							while ($deals->next())
							{
								$temp3 = array();
								$temp3["dms_vehicle_id"] = $deals->getString('dms_vehicle_id');
								$temp3["sold_date"] = $deals->getString('sold_date');
								$temp3["term_months"] = $deals->getString('term_months');
								$temp3["mileage"] = $deals->getString('mileage');
								$temp3["equity_balance"] = $deals->getString('equity_balance');
								$temp3["new_used_type_id"] = $deals->getString('new_used_type_id');
								$temp3["warranty_expiration_miles"] = $deals->getString('warranty_expiration_miles');
								$temp3["warranty_expiration_date"] = $deals->getString('warranty_expiration_date');
								$temp3["salesmen"] = $this->findSalesman($deals->getString('loop_sales_person_id'));
								if (!$temp3["salesmen"]) { $temp3["salesmen"] = "UNKNOWN"; }
								$this->extInfo[$custid]["deals"][$deals->getString('dms_deal_id')] = $temp3;
							}
						}
					}
				}

				$this->proofSettings["extInfo"] = $this->extInfo;

				$this->setLayout(false);
			}
		}

		//If the export parameter is set, we're going to spit out a csv name list for a batch.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		elseif ($this->getRequest()->getParameterHolder()->has('export'))
		{
			if ($this->customer_id > 0)
			{
				$databaseManager = new sfDatabaseManager();
				$databaseManager->initialize();

				$CDmsd = new Dmsd();
				$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);
				$sqlconn = $dms_master_conn->getResource();

				$sql = "SELECT full_name,last,first,middle,address,suite,city,state,zip,voice_phone,sms_phone,email_address FROM trigger_batch_list WHERE trigger_batch_id= " . $this->getRequestParameter('export');
				$result = mysql_query($sql, $sqlconn) or die($sql . "\r\n" . mysql_error($sqlconn) );

				$out = '';
				//$fields = mysql_list_fields('database','table',$db);
				$columns = mysql_num_fields($result);

				// Put the name of all fields
				for ($i = 0; $i < $columns; $i++) {
					$row=mysql_field_name($result, $i);
					$out .= '"'.$row.'",';
				}
				$out .="\n";

				// Add all values in the table
				while ($row = mysql_fetch_array($result)) {
					for ($i = 0; $i < $columns; $i++) {
						$out .='"'.$row["$i"].'",';
					}
					$out .="\n";
				}
				// Output to browser with appropriate mime type, you choose ;)
				header("Content-type: text/x-csv");
				//header("Content-type: text/csv");
				//header("Content-type: application/csv");
				header("Content-Disposition: attachment; filename=trigger_batch_export.csv");
				echo $out;
				exit;
			}
		}

		//If the details parameter is set, we're going to display the approval queue details for a batch.
		//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		elseif ($this->getRequest()->getParameterHolder()->has('details'))
		{
			//This variable is used in views for backlinking.
			$this->id = intval($this->getRequestParameter('nameid'));
			$this->detailsid = intval($this->getRequestParameter('details'));
			$form = $this->id;
			$this->detailSettings = array();
			$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, $this->getRequestParameter('nameid'), $this->dmstrigconn);
			$this->nameid = $this->getRequestParameter('nameid');
			$this->detailSettings["trigger_id"] = $this->TriggerSettingId;
			$this->detailSettings["id"] = $this->detailsid;
			$this->detailSettings["nameid"] = $this->nameid;
			$this->detailSettings["customer_id"] = $this->customer_id;
			//This query gets all the basic trigger and filter info for the trigger id given in the form parameter.
			$sql = "SELECT name FROM trigger_name WHERE trigger_name_id=$form";
			$result = mysql_query($sql, $this->dmstrigsqlconn) or die($sql . "\r\n" . mysql_error($this->dmstrigsqlconn) );
			$row = mysql_fetch_array($result);
			//Set some basic variables for use in titles and subtitles.
			$this->title = $this->customer_name . " Trigger Campaign Controller | " . $row["name"] . " Trigger";
			$this->subtitle = $row["name"] . " Batch Detail";

			if ($this->customer_id > 0)
			{
				$databaseManager = new sfDatabaseManager();
				$databaseManager->initialize();

				$Wilma = Propel::GetConnection();
				$sql = "SELECT client_id FROM customer WHERE customer_id = '{$this->customer_id}'";
				$Rs = $Wilma->executeQuery($sql);
				while ($Rs->next())
				{
					$this->client_id = $Rs->get('client_id');
				}

				$CDmsd = new Dmsd();
				$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);
				$this->dms_master_conn = $dms_master_conn;

				// If this is HVAC
				if ($this->client_id == 509)
				{
					$sql	= "SELECT * FROM "
								. "(SELECT external_customer_id, dms_vehicle_id, external_systemunit_id, contract_name, contract_start, contract_expire "
								. "FROM amms_system_detail ORDER BY external_systemunit_id DESC) AS a "
							. "GROUP BY dms_vehicle_id, external_customer_id";

					$Rs		= $dms_master_conn->executeQuery($sql);
					$arrayContract = array();
					while ($Rs->next())
					{
						$arrayContract[$Rs->get('dms_vehicle_id')]	= $Rs->getRow();
					}

					$this->detailSettings["arrayContract"] = $arrayContract;

					$C = new Criteria();
					$C->add(TriggerBatchPeer::TRIGGER_BATCH_ID,$this->getRequestParameter('details'));
					$this->batch = TriggerBatchPeer::doSelectOne($C,$dms_master_conn);
					$this->detailSettings["batch"] = $this->batch;

					$C = new Criteria();
					$C->add(TriggerBatchListPeer::TRIGGER_BATCH_ID,$this->getRequestParameter('details'));
					$C->addAscendingOrderByColumn(TriggerBatchListPeer::LAST);
					$C->addAscendingOrderByColumn(TriggerBatchListPeer::FIRST);
					$C->addAscendingOrderByColumn(TriggerBatchListPeer::FULL_NAME);
					$this->batchList = TriggerBatchListPeer::doSelect($C,$dms_master_conn);
					$this->detailSettings["batchList"] = $this->batchList;
				} else {
					$C = new Criteria();
					$C->add(TriggerBatchPeer::TRIGGER_BATCH_ID,$this->getRequestParameter('details'));
					$this->batch = TriggerBatchPeer::doSelectOne($C,$dms_master_conn);
					$this->detailSettings["batch"] = $this->batch;

					$C = new Criteria();
					$C->add(TriggerBatchListPeer::TRIGGER_BATCH_ID,$this->getRequestParameter('details'));
					$C->addAscendingOrderByColumn(TriggerBatchListPeer::LAST);
					$C->addAscendingOrderByColumn(TriggerBatchListPeer::FIRST);
					$C->addAscendingOrderByColumn(TriggerBatchListPeer::FULL_NAME);
					$this->batchList = TriggerBatchListPeer::doSelect($C,$dms_master_conn);
					$this->detailSettings["batchList"] = $this->batchList;
				}
			}
		}

		if ($this->getRequestParameter('commitedit') == "Submit")
		{
			if ($this->customer_id > 0)
			{
				$databaseManager = new sfDatabaseManager();
				$databaseManager->initialize();

				$CDmsd = new Dmsd();
				$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);

				$C = new Criteria();
				$C->add(TriggerBatchPeer::TRIGGER_BATCH_ID,$this->getRequestParameter('editid'));
				$this->batch = TriggerBatchPeer::doSelectOne($C,$dms_master_conn);

				$temp = unserialize($this->batch->getTriggerCriteria());
				//die(print_r($temp));
				$curfilter = 0;
				foreach ($_POST as $key => $value)
				{
					//echo "<span style='text-decoration:underline;'>|----" . $key . " = " . $value . "----|</span><br>";
					if ($key != "commitedit" && $key != "nameid" && $key != "editid" && strpos($key,'filter_') === false)
					{
/*						echo "set" . str_replace(' ','',ucwords(str_replace('_',' ',$key))) . "(";
						echo is_numeric($value) ?  $value : "'" . $value . "'";
						echo ")<br>";*/
						$editfunc = "set" . str_replace(' ','',ucwords(str_replace('_',' ',$key)));
						$temp["setting"]->$editfunc($value);
					}
					if (strpos($key,'filter_') !== false)
					{
						if (strpos($key,'filter_id') !== false)
						{
							$curfilter = intval(str_replace('filter_id','',$key));
						}
						else
						{
							if (strpos($key,'filter_brand') !== false)
							{
								$tstr = str_replace('filter_brand_','',$key);
								$tstr2 = explode('|',$tstr);
								$temp["filters"][$curfilter][1][$tstr2[0]][$tstr2[1]] = $value;
							}
							else $temp["filters"][$curfilter][1][str_replace('filter_','',$key)] = $value;
						}
					}
				}
				// $tempsetting =  new TriggerSetting;
				// $tempsetting = $temp["setting"];
				//die(print_r($temp));
				$this->batch->setTriggerCriteria(serialize($temp));
				$this->batch->save($dms_master_conn);
				$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
			}
		}

		$this->getResponse()->setTitle($this->title);
		//Call the control function that loads data for each view depending upon the request parameters.
		$this->load();

		//Detect form submit
		if ($this->getRequestParameter('commit') == "Save " . trim($this->subtitle) . " Trigger Settings" )
		{
			switch($this->getRequestParameter('form'))
			{
				case 1: $this->saveForm1();break;
				case 2: $this->saveForm2();break;
				case 3: $this->saveForm3();break;
				case 4: $this->saveForm4();break;
				case 5: $this->saveForm5();break;
				case 6: $this->saveForm6();break;
				case 7: $this->saveForm7();break;
				case 8: $this->saveForm8();break;
				case 9: $this->saveForm9();break;
				case 12: $this->saveForm12();break;
				case 14: $this->saveForm14();break;
				case 15: $this->saveForm15();break;
				case 18: $this->saveForm18();break;
				case 19: $this->saveForm19();break;
				case 20: $this->saveForm20();break;
				case 31: $this->saveForm31();break;
			}
		}


		return 'Success2';

		#if ($this->curuser==3) return 'Success2';
		#if (in_array($this->getRequestParameter('form'), $arrayTriggerInVersion2)) return 'Success2';
		#if (in_array($this->getRequestParameter('approval'), $arrayTriggerInVersion2)) return 'Success2';
	}


	//This function will determine the variables needed to populate various items in the various views,
	//then create those variables and load them into arrays to be passed to the partials.
	public function load()
	{
		// Load the customer profile
		$CustomerProfile 			= new CustomerProfile(false, $this->customer_id);
		$ProfileId					= $CustomerProfile->GetDefaultProfile();
		$this->CustomerProfileData	= $CustomerProfile->GetProfileData($ProfileId);

		if (trim($this->CustomerProfileData['default_email_delay_days'])==='')
			$this->CustomerProfileData['default_email_delay_days'] = 7;

		$this->CustomerProfileData['default_email_delay_days'] = intval($this->CustomerProfileData['default_email_delay_days']);

		//If none of the specific form/page parameters are set, we'll need the data for the main navigation links.
		if (!$this->getRequest()->getParameterHolder()->has('form') && !$this->getRequest()->getParameterHolder()->has('nav') && !$this->getRequest()->getParameterHolder()->has('approval'))
		{
			$exclude = array(2,3,4,10,11,13,16,17);

			$C = new Criteria();
			$C->addSelectColumn(TriggerNamePeer::TRIGGER_NAME_ID);
			$C->addSelectColumn(TriggerNamePeer::NAME);
			$C->addDescendingOrderByColumn(TriggerNamePeer::CATEGORY_NAME);
			$C->addAscendingOrderByColumn(TriggerNamePeer::DISPLAY_ORDER_ID);
			$crit1 = $C->getNewCriterion(TriggerNamePeer::TRIGGER_NAME_ID,$exclude, Criteria::NOT_IN);
			$C->addAnd($crit1);
			$C->add(TriggerNamePeer::CATEGORY_NAME,"SERVICE");
			$servicenav = TriggerNamePeer::doSelectRs($C,$this->dmstrigconn);
			$servicenav->setFetchMode( ResultSet::FETCHMODE_ASSOC );

			$this->servicenav = array();
			while ($servicenav->next())
			{
				$row = $servicenav->getRow();
				$this->servicenav[$row['TRIGGER_NAME_ID']] = $row['NAME'];
			}

			$C = new Criteria();
			$C->addSelectColumn(TriggerNamePeer::TRIGGER_NAME_ID);
			$C->addSelectColumn(TriggerNamePeer::NAME);
			$C->addDescendingOrderByColumn(TriggerNamePeer::CATEGORY_NAME);
			$C->addAscendingOrderByColumn(TriggerNamePeer::DISPLAY_ORDER_ID);
			$crit1 = $C->getNewCriterion(TriggerNamePeer::TRIGGER_NAME_ID,$exclude, Criteria::NOT_IN);
			$C->addAnd($crit1);
			$C->add(TriggerNamePeer::CATEGORY_NAME,"SALE");
			$salesnav = TriggerNamePeer::doSelectRs($C,$this->dmstrigconn);
			$salesnav->setFetchMode( ResultSet::FETCHMODE_ASSOC );

			$this->salesnav = array();
			while ($salesnav->next())
			{
				$row = $salesnav->getRow();
				$this->salesnav[$row['TRIGGER_NAME_ID']] = $row['NAME'];
			}
		}

		//If a form has been requested, build the common data array and then call the appropriate form loader.
		if ($this->getRequest()->getParameterHolder()->has('form'))
		{
			$this->loadCommon();


			switch(intval($this->getRequestParameter('form')))
			{
				case 1: $this->LoadForm(1); break;
				case 2: $this->loadForm2(); break;
				case 3: $this->loadForm3(); break;
				case 4: $this->loadForm4(); break;
				case 5: $this->LoadForm(5); break;
				case 6: $this->LoadForm(6); break;
				case 7: $this->LoadForm(7); break;
				case 8:
					$this->DisablePrototype = true;
					$this->LoadForm(8);
				break;
				case 9:  $this->LoadForm(9); break;
				case 12: $this->LoadForm(12); break;
				case 14: $this->LoadForm(14); break;

				case 15: $this->LoadForm(15); break;
				case 16: $this->LoadForm(16); break;
				case 18: $this->loadForm18(); break;
				case 19: $this->LoadForm(19); break;
				case 20: $this->loadForm20(); break;
				case 31: $this->LoadForm(31); break;
				case 32: $this->LoadForm(32); break;
				case 33: $this->LoadForm(33); break;
				case 34: $this->LoadForm(34); break;
				case 35: $this->LoadForm(35); break;
				case 36: $this->LoadForm(36); break;
				case 37: $this->LoadForm(37); break;
				case 38: $this->LoadForm(38); break;
				case 39: $this->LoadForm(39); break;
				case 40: $this->LoadForm(40); break;
				case 41: $this->LoadForm(41); break;
				case 42: $this->LoadForm(42); break;
				case 43: $this->LoadForm(43); break;
				case 45: $this->LoadForm(45); break;
				case 46: $this->LoadForm(46); break;
				case 44: $this->LoadForm(44); break;
				case 47: $this->LoadForm(47); break;
				case 48: $this->LoadForm(48); break;
				case 49: $this->LoadForm(49); break;
				case 50: $this->LoadForm(50); break;
				case 51: $this->LoadForm(51); break;
				case 52: $this->LoadForm(52); break;
				case 53: $this->LoadForm(53); break;
				case 54: $this->LoadForm(54); break;
				case 55: $this->LoadForm(55); break;
				case 56: $this->LoadForm(56); break;
			}
		}

		$this->commonSettings["hourSelect"] = array('1', '2', '3','4','5','6','7','8','9','10','11','12');
		$this->commonSettings["minuteSelect"] = array('00', '15', '30','45');
		$this->commonSettings["ampmSelect"] = array('AM', 'PM');

		//If the control navigation page has been requested, load the data for it.
		if ($this->getRequest()->getParameterHolder()->has('nav') || $this->getRequest()->getParameterHolder()->has('form'))
		{
			$this->loadNav($this->getRequestParameter('form'));
		}
	}


	//Build data array to be used in the _Control partial.
	public function loadNav($trigger_id=0)
	{
		$this->controlSettings = array();
		$this->controlSettings["trigger_id"] = $trigger_id ? $trigger_id : intval($this->getRequestParameter('nav'));
		$this->controlSettings["subtitle"] = $this->subtitle;
		$this->TriggerSetting = TriggerSettingPeer::retrieveByCustomerTrigger($this->customer_id, $this->controlSettings["trigger_id"], false, $this->dmstrigconn);
		if ($this->TriggerSetting->getEnabledYn() == "N") $this->active = false;
		else $this->active = true;
		$this->TriggerSettingId = $this->TriggerSetting->getTriggerSettingId();

		$activityData = array();
		$activityData["contacts"] = array('7','5','21','32');
		$activityData["voicemail"] = array('3','7','15','20');
		$activityData["transfers"] = array('4','9','13','18');
		$activityData["emails"] = array('2','6','44','22');
		$activityData["sms"] = array('11','16','35','51');
		$this->controlSettings["activity"] = $activityData;
		$this->controlSettings["active"] = $this->active;
		$this->controlSettings["trigid"] = $this->TriggerSettingId;
	}


	public function saveCommon()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, $this->form, $this->dmstrigconn);

		$filterid = $this->getFilterId($this->TriggerSettingId,1);

		$this->commonSettings = array();
		$this->commonSettings["hourSelect"] = array('1', '2', '3','4','5','6','7','8','9','10','11','12');
		$this->commonSettings["minuteSelect"] = array('00', '15', '30','45');
		$this->commonSettings["ampmSelect"] = array('AM', 'PM');

		$this->TriggerSetting = TriggerSettingPeer::retrieveByCustomerTrigger($this->customer_id,$this->form, false, $this->dmstrigconn);


		$this->TriggerSetting->setPriorityMail($this->getRequestParameter('mailPriority'));

		if ($this->getRequestParameter('mail') == 1)
		{
			$this->TriggerSetting->setSendMailYn("Y");
		}
		else $this->TriggerSetting->setSendMailYn("N");


		$this->TriggerSetting->setPriorityLivecall($this->getRequestParameter('livecallPriority'));

		if ($this->getRequestParameter('livecall') == 1)
		{
			$this->TriggerSetting->setSendLivecallYn("Y");
		}
		else $this->TriggerSetting->setSendLivecallYn("N");

		/*
		   Temporary hack to ensure that Service Follow-Up Triggers set an emailPriority of 1 or Greater
		   10/21/2010
		*/
		$epri = $this->getRequestParameter('emailPriority');
		if ($epri < 1 && $this->form == 6 ) { $epri = 1;}
		$this->TriggerSetting->setPriorityEmail($epri);

		if ($this->getRequestParameter('email') == 1)
		{
			$this->TriggerSetting->setSendEmailYn('Y');
		}
		else $this->TriggerSetting->setSendEmailYn("N");



		$this->TriggerSetting->setPriorityVoice($this->getRequestParameter('phonePriority'));
		if ($this->getRequestParameter('phone') == 1)
		{
			$this->TriggerSetting->setSendVoiceYn("Y");
		}
		else $this->TriggerSetting->setSendVoiceYn("N");

		$this->TriggerSetting->setPrioritySms($this->getRequestParameter('textPriority'));
		if ($this->getRequestParameter('text') == 1)
		{
			$this->TriggerSetting->setSendSmsYn("Y");
		}
		else $this->TriggerSetting->setSendSmsYn("N");

		$this->TriggerSetting->setCallerIdNumber($this->getRequestParameter('callerid'));
		$this->TriggerSetting->setAreaCode($this->getRequestParameter('areacode'));
		$this->TriggerSetting->setCallTransferNumber($this->getRequestParameter('transfernumber'));
		$this->TriggerSetting->setCallTransferNumberExt($this->getRequestParameter('transferext'));

		if ($this->getRequestParameter('transferannouncement') == 1)
		$this->TriggerSetting->setTransferAnnouncementYn("Y");
		else $this->TriggerSetting->setTransferAnnouncementYn("N");

		$this->TriggerSetting->setCsrCallBackNumber($this->getRequestParameter('csrcallback'));
		$this->TriggerSetting->setCsrCallBackNumberExt($this->getRequestParameter('csrext'));
		$this->TriggerSetting->setCsrEmail($this->getRequestParameter('csremail'));

		if ($this->getRequestParameter('batchnotification') == 1)
		$this->TriggerSetting->setSendEmailBatchCompleteYn("Y");
		else $this->TriggerSetting->setSendEmailBatchCompleteYn("N");

		if ($this->getRequestParameter('retries') == 1)
		$this->TriggerSetting->setRetryEnabledYn("Y");
		else $this->TriggerSetting->setRetryEnabledYn("N");

		$this->TriggerSetting->setRetryCountCount($this->getRequestParameter('retriesnumber'));
		$this->TriggerSetting->setRetryDelayMinute($this->getRequestParameter('retriesfrequency'));

		if ($this->getRequestParameter('messages') == 1)
		$this->TriggerSetting->setLeaveMessageYn("Y");
		else $this->TriggerSetting->setLeaveMessageYn("N");

		if ($this->getRequestParameter('stopaftermessages') == 1)
		$this->TriggerSetting->setStopCallsAfterRetryYn("Y");
		else $this->TriggerSetting->setStopCallsAfterRetryYn("N");

		if ($this->getRequestParameter('callwindows') == 1)
		$this->TriggerSetting->setCallWindowEnabledYn("Y");
		else $this->TriggerSetting->setCallWindowEnabledYn("N");

		if ($this->getRequestParameter('satcalls') == 1)
		$this->TriggerSetting->setCallWindowSatYn("Y");
		else $this->TriggerSetting->setCallWindowSatYn("N");

		if ($this->getRequestParameter('suncalls') == 1)
		$this->TriggerSetting->setCallWindowSunYn("Y");
		else $this->TriggerSetting->setCallWindowSunYn("N");

		$this->TriggerSetting->setCallWindowMfStart($this->commonSettings["hourSelect"][$this->getRequestParameter('mfnotbeforehour')] . ":" . $this->commonSettings["minuteSelect"][$this->getRequestParameter('mfnotbeforeminute')] . " " . $this->commonSettings["ampmSelect"][$this->getRequestParameter('mfnotbeforeampm')]);
		$this->TriggerSetting->setCallWindowMfEnd($this->commonSettings["hourSelect"][$this->getRequestParameter('mfnotafterhour')] . ":" . $this->commonSettings["minuteSelect"][$this->getRequestParameter('mfnotafterminute')] . " " . $this->commonSettings["ampmSelect"][$this->getRequestParameter('mfnotafterampm')]);
		$this->TriggerSetting->setCallWindowSsStart($this->commonSettings["hourSelect"][$this->getRequestParameter('ssnotbeforehour')] . ":" . $this->commonSettings["minuteSelect"][$this->getRequestParameter('ssnotbeforeminute')] . " " . $this->commonSettings["ampmSelect"][$this->getRequestParameter('ssnotbeforeampm')]);
		$this->TriggerSetting->setCallWindowSsEnd($this->commonSettings["hourSelect"][$this->getRequestParameter('ssnotafterhour')] . ":" . $this->commonSettings["minuteSelect"][$this->getRequestParameter('ssnotafterminute')] . " " . $this->commonSettings["ampmSelect"][$this->getRequestParameter('ssnotafterampm')]);

		if ($this->getRequestParameter('approvalqueue') == 1)
		$this->TriggerSetting->setApprovalQueueYn("Y");
		else $this->TriggerSetting->setApprovalQueueYn("N");

		$this->TriggerSetting->setApprovalEmail($this->getRequestParameter('approvalereminderemail'));
		$this->TriggerSetting->setEmailFromName($this->getRequestParameter('emailfrom'));
		$this->TriggerSetting->setEmailFromAddress($this->getRequestParameter('emailforward'));
		$this->TriggerSetting->setEmailSubject($this->getRequestParameter('emailsubject'));
		$this->TriggerSetting->setEmailContactName($this->getRequestParameter('contactname'));

		if ($this->getRequestParameter('greeting') == "fullname")
		$this->TriggerSetting->setEmailGreetPreference("U");
		else $this->TriggerSetting->setEmailGreetPreference("I");

		$this->TriggerSetting->setCallTrackingCode($this->getRequestParameter('trackingcode'));
		$this->setCoupons();

		$this->TriggerSetting->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = " . $this->form . ", trigger_filter_id = 0, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSetting)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	public function setCoupons()
	{
		$params = array();
		$params["coupon2_1"] = $this->getRequestParameter("coupon2_1_service_reminder");
		$params["coupon2_2"] = $this->getRequestParameter("coupon2_2_service_reminder");
		$params["coupon1_1"] = $this->getRequestParameter("coupon1_1_return_reminder");
		$params["coupon1_2"] = $this->getRequestParameter("coupon1_2_return_reminder");
		if ($params["coupon2_1"]) {$this->TriggerSettingFilter->setCoupon21($params["coupon2_1"]);}
		if ($params["coupon2_2"]) {$this->TriggerSettingFilter->setCoupon22($params["coupon2_2"]);}
		if ($params["coupon1_1"]) {$this->TriggerSettingFilter->setCoupon11($params["coupon1_1"]);}
		if ($params["coupon1_2"]) {$this->TriggerSettingFilter->setCoupon12($params["coupon1_2"]);}

	}


	public function loadMakes()
	{
		$C = new Criteria();
		$C->addSelectColumn(ChromeMakePeer::MAKE);
		$C->addAscendingOrderByColumn(ChromeMakePeer::MAKE);
		$makedrop = ChromeMakePeer::doSelectRs($C);
		$makedrop->setFetchMode( ResultSet::FETCHMODE_ASSOC );

		$this->makedrop = array();
		while ($makedrop->next())
		{
			$row = $makedrop->getRow();
			$this->makedrop[$row['MAKE']] = $row['MAKE'];
		}
	}


	public function loadHVACMakes()
	{
		$conn = Propel::GetConnection();
		$sqlconn = $conn->getResource();

		$sql = "SELECT brand FROM hvac_brands ORDER BY brand";
		$result = mysql_query($sql, $sqlconn) or die($sql . "\r\n" .mysql_error($sqlconn));
		$this->hvacdrop = array();
		while ($row = mysql_fetch_assoc($result))
		{
			$this->hvacdrop[$row['brand']] = $row['brand'];
		}
	}


	/**
	*
	******************************************************************************************/
	public function loadHVACCustomerContractTypes000($CustomerId, $ProfileName='DEFAULT')
	{
		$CONTRACT_MIN = 1;
		$CONTRACT_MAX = 4;

		$Query1				= "SELECT customer_profile_id FROM dms.customer_profile WHERE customer_id='{$CustomerId}' AND profile_name='{$ProfileName}'";
		$Rs1				= $this->dmstrigconn->executeQuery($Query1);

		while ($Rs1->next()) {
			$CustomerProfileId	= $Rs1->get('customer_profile_id');
		}

		$profile_data		= array();

		if (!empty($CustomerProfileId)) {
			$Query2				= "SELECT field_name, field_value FROM dms.customer_profile_data WHERE customer_profile_id='{$CustomerProfileId}' AND field_name LIKE 'hvac_contract%'";
			$Rs2				= $this->dmstrigconn->executeQuery($Query2);

			while ($Rs2->next()) {
				$profile_data[$Rs2->get('field_name')]		= $Rs2->get('field_value');
			}
		}

		$result				= array();

		if (empty($profile_data)) {
			return $result;
		}

		for ($i = $CONTRACT_MIN; $i <= $CONTRACT_MAX; $i++) {
			$code		= "hvac_contract{$i}_code";
			$name		= "hvac_contract{$i}_name";
			$term		= "hvac_contract{$i}_term";

			if (array_key_exists($code, $profile_data)) {
				$result[$profile_data[$code]]	= array(
					"code"			=> @$profile_data[$code],
					"name"			=> @$profile_data[$name],
					"term"			=> @$profile_data[$term]
					);
			}
		}

		$this->hvacContracts = $result;
	}


	/**
	*
	******************************************************************************************/
	public function loadHVACCustomerContractTypes($CustomerId, $ProfileName='DEFAULT')
	{
		$database			= sprintf("dms_%05d", $CustomerId);
		$Query1				= "SELECT DISTINCT contract_name FROM {$database}.amms_system_detail";
		$Rs1				= $this->dmstrigconn->executeQuery($Query1);

		$result				= array();

		while ($Rs1->next()) {
			$contract_name				= strtoupper($Rs1->get('contract_name'));
			$result[$contract_name]		= array(
				"code"				=> $contract_name,
				"name"				=> $contract_name,
				"term"				=> $contract_name
				);
		}

		$this->hvacContracts = $result;
	}


	public function loadCommon()
	{
		$this->loadMakes();
		$this->loadHVACMakes();
		$this->commonSettings = array();
		$this->TriggerSetting = TriggerSettingPeer::retrieveByCustomerTrigger($this->customer_id, $this->getRequestParameter('form'), false, $this->dmstrigconn);
		if ($this->TriggerSetting->getSendVoiceYn() == "Y") $this->commonSettings["voice"] = 1;
		else $this->commonSettings["voice"] = 0;
		if ($this->TriggerSetting->getSendLivecallYn() == "Y") $this->commonSettings["livecall"] = 1;
		else $this->commonSettings["livecall"] = 0;
		if ($this->TriggerSetting->getSendEmailYn() == "Y") $this->commonSettings["email"] = 1;
		else $this->commonSettings["email"] = 0;
		if ($this->TriggerSetting->getSendSmsYn() == "Y") $this->commonSettings["text"] = 1;
		else $this->commonSettings["text"] = 0;
		if ($this->TriggerSetting->getSendMailYn() == "Y") $this->commonSettings["mail"] = 1;
		else $this->commonSettings["mail"] = 0;
		if ($this->TriggerSetting->getSendFacebookYn() == "Y") $this->commonSettings["facebook"] = 1;
		else $this->commonSettings["facebook"] = 0;
		$this->commonSettings["phonePriority"] = $this->TriggerSetting->getPriorityVoice();
		$this->commonSettings["livecallPriority"] = $this->TriggerSetting->getPriorityLivecall();
		$this->commonSettings["emailPriority"] = $this->TriggerSetting->getPriorityEmail();
		$this->commonSettings["textPriority"] = $this->TriggerSetting->getPrioritySms();
		$this->commonSettings["mailPriority"] = $this->TriggerSetting->getPriorityMail();
		$this->commonSettings["facebookPriority"] = $this->TriggerSetting->getPriorityFacebook();
		$this->commonSettings["callerid"] = $this->TriggerSetting->getCallerIdNumber();
		$this->commonSettings["areacode"] = $this->TriggerSetting->getAreaCode();
		$this->commonSettings["transfer"] = $this->TriggerSetting->getCallTransferNumber();
		$this->commonSettings["ext"] = $this->TriggerSetting->getCallTransferNumberExt();
		if ($this->TriggerSetting->getTransferAnnouncementYn() == "Y") $this->commonSettings["announce"] = 1;
		else $this->commonSettings["announce"] = 0;
		$this->commonSettings["csrcallback"] = $this->TriggerSetting->getCsrCallBackNumber();
		$this->commonSettings["csrext"] = $this->TriggerSetting->getCsrCallBackNumberExt();
		$this->commonSettings["csremail"] = $this->TriggerSetting->getCsrEmail();
		if ($this->TriggerSetting->getSendEmailBatchCompleteYn() == "Y") $this->commonSettings["batchnotification"] = 1;
		else $this->commonSettings["batchnotification"] = 0;
		if ($this->TriggerSetting->getRetryEnabledYn() == "Y") $this->commonSettings["retries"] = 1;
		else $this->commonSettings["retries"] = 0;
		$this->commonSettings["retriesnumber"] = $this->TriggerSetting->getRetryCountCount();
		$this->commonSettings["retriesfrequency"] = $this->TriggerSetting->getRetryDelayMinute();
		if ($this->TriggerSetting->getLeaveMessageYn() == "Y") $this->commonSettings["messages"] = 1;
		else $this->commonSettings["messages"] = 0;
		if ($this->TriggerSetting->getStopCallsAfterRetryYn() == "Y") $this->commonSettings["stopaftermessage"] = 1;
		else $this->commonSettings["stopaftermessage"] = 0;
		if ($this->TriggerSetting->getCallWindowEnabledYn() == "Y") $this->commonSettings["callwindows"] = 1;
		else $this->commonSettings["callwindows"] = 0;
		if ($this->TriggerSetting->getCallWindowSatYn() == "Y") $this->commonSettings["satcalls"] = 1;
		else $this->commonSettings["satcalls"] = 0;
		if ($this->TriggerSetting->getCallWindowSunYn() == "Y") $this->commonSettings["suncalls"] = 1;
		else $this->commonSettings["suncalls"] = 0;
		$mfbefore = $this->TriggerSetting->getCallWindowMfStart();
		$mfafter = $this->TriggerSetting->getCallWindowMfEnd();
		$ssbefore = $this->TriggerSetting->getCallWindowSsStart();
		$ssafter = $this->TriggerSetting->getCallWindowSsEnd();
		$this->commonSettings["mfnotbeforehour"] = substr($mfbefore,0,strpos($mfbefore,':')) - 1;
		$this->commonSettings["mfnotbeforeminute"] = substr($mfbefore,strpos($mfbefore,':')+1,strpos($mfbefore,' ') - strpos($mfbefore,':'));
		switch($this->commonSettings["mfnotbeforeminute"])
		{
			case 00 : $this->commonSettings["mfnotbeforeminute"] = 0;break;
			case 15 : $this->commonSettings["mfnotbeforeminute"] = 1;break;
			case 30 : $this->commonSettings["mfnotbeforeminute"] = 2;break;
			case 45 : $this->commonSettings["mfnotbeforeminute"] = 3;break;
		}

		$this->commonSettings["mfnotbeforeampm"] = substr($mfbefore,strpos($mfbefore,' ')+1);
		switch($this->commonSettings["mfnotbeforeampm"])
		{
			case "AM" : $this->commonSettings["mfnotbeforeampm"] = 0;break;
			case "PM" : $this->commonSettings["mfnotbeforeampm"] = 1;break;
		}

		$this->commonSettings["mfnotafterhour"] = substr($mfafter,0,strpos($mfafter,':')) - 1;
		$this->commonSettings["mfnotafterminute"] = substr($mfafter,strpos($mfafter,':')+1,strpos($mfafter,' ') - strpos($mfafter,':'));
		switch($this->commonSettings["mfnotafterminute"])
		{
			case 00 : $this->commonSettings["mfnotafterminute"] = 0;break;
			case 15 : $this->commonSettings["mfnotafterminute"] = 1;break;
			case 30 : $this->commonSettings["mfnotafterminute"] = 2;break;
			case 45 : $this->commonSettings["mfnotafterminute"] = 3;break;
		}
		$this->commonSettings["mfnotafterampm"] = substr($mfafter,strpos($mfafter,' ')+1);
		switch($this->commonSettings["mfnotafterampm"])
		{
			case "AM" : $this->commonSettings["mfnotafterampm"] = 0;break;
			case "PM" : $this->commonSettings["mfnotafterampm"] = 1;break;
		}

		$this->commonSettings["ssnotbeforehour"] = substr($ssbefore,0,strpos($ssbefore,':')) - 1;
		$this->commonSettings["ssnotbeforeminute"] = substr($ssbefore,strpos($ssbefore,':')+1,strpos($ssbefore,' ') - strpos($ssbefore,':'));
		switch($this->commonSettings["ssnotbeforeminute"])
		{
			case 00 : $this->commonSettings["ssnotbeforeminute"] = 0;break;
			case 15 : $this->commonSettings["ssfnotbeforeminute"] = 1;break;
			case 30 : $this->commonSettings["ssnotbeforeminute"] = 2;break;
			case 45 : $this->commonSettings["ssnotbeforeminute"] = 3;break;
		}

		$this->commonSettings["ssnotbeforeampm"] = substr($ssbefore,strpos($ssbefore,' ')+1);
		switch($this->commonSettings["ssnotbeforeampm"])
		{
			case "AM" : $this->commonSettings["ssnotbeforeampm"] = 0;break;
			case "PM" : $this->commonSettings["ssnotbeforeampm"] = 1;break;
		}

		$this->commonSettings["ssnotafterhour"] = substr($ssafter,0,strpos($ssafter,':')) - 1;
		$this->commonSettings["ssnotafterminute"] = substr($ssafter,strpos($ssafter,':')+1,strpos($ssafter,' ') - strpos($ssafter,':'));
		switch($this->commonSettings["ssnotafterminute"])
		{
			case 00 : $this->commonSettings["ssnotafterminute"] = 0;break;
			case 15 : $this->commonSettings["ssnotafterminute"] = 1;break;
			case 30 : $this->commonSettings["ssnotafterminute"] = 2;break;
			case 45 : $this->commonSettings["ssnotafterminute"] = 3;break;
		}
		$this->commonSettings["ssnotafterampm"] = substr($ssafter,strpos($ssafter,' ')+1);
		switch($this->commonSettings["ssnotafterampm"])
		{
			case "AM" : $this->commonSettings["ssnotafterampm"] = 0;break;
			case "PM" : $this->commonSettings["ssnotafterampm"] = 1;break;
		}

		//Set the variables array to be passed to the common partial view for the edit forms.
		$this->commonSettings["subtitle"] = $this->subtitle;
		$this->commonSettings["customer_id"] = $this->customer_id;
		$this->commonSettings["form"] = $this->form;
		$this->commonSettings["level"] = $this->level;

		if ($this->TriggerSetting->getApprovalQueueYn() == "Y") $this->commonSettings["approvalqueue"] = 1;
		else $this->commonSettings["approvalqueue"] = 0;
		$this->commonSettings["approvalereminderemail"] = $this->TriggerSetting->getApprovalEmail();
		$this->commonSettings["emailfrom"] = $this->TriggerSetting->getEmailFromName();
		$this->commonSettings["emailforward"] = $this->TriggerSetting->getEmailFromAddress();
		$this->commonSettings["emailsubject"] = $this->TriggerSetting->getEmailSubject();
		$this->commonSettings["contactname"] = $this->TriggerSetting->getEmailContactName();
		$this->commonSettings["greeting"] = $this->TriggerSetting->getEmailGreetPreference();
		$this->commonSettings["trackingcode"] = $this->TriggerSetting->getCallTrackingCode();

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 0 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->commonSettings["change_date"] = $row["change_date"];
			$this->commonSettings["user_id"] = $row["user_id"];
		}
		else
		{
			$this->commonSettings["change_date"] = '0000-00-00 00:00:00';
			$this->commonSettings["user_id"] = 0;
		}
	}


	/***
	`*
	`* Load Trigger Options
	`*
	`************************************************************************************************/
	public function LoadTriggerOptions($TriggerNameId)
	{
		//These arrays are used to populate the Sceduled Maintenance vehicle filter dropdowns
		$this->vehicleNotificationTiming = array('Disable Notifications',
			3=>'3 Months', 4=>'4 Months', 5=>'5 Months', 6=>'6 Months', 7=>'7 Months', 8=>'8 Months', 9=>'9 Months', 10=>'10 Months', 11=>'11 Months', 12=>'12 Months',
			13=>'13 Months', 14=>'14 Months', 15=>'15 Months'
		);

		$this->delaySelect 	= array(-1=>'Never', 0=>'No Delay','1 Day','2 Days','3 Days','4 Days','5 Days');
		$this->couponSelect	= array('N/A','Repair Special','Brake Special','Tire Special','Oil Change','Deluxe Wash!','40 Point Safety Inspection');
		$this->hourSelect	= array(-1=>'Never', 0=>'No Delay', 1=>'1 Hour', 2=>'2 Hours', 3=>'3 Hours', 6=>'6 Hours', 24=>'1 Day', 48=>'2 Days', 72=>'3 Days', 168=>'7 Days');
		$this->customer_id 	= $this->getUser()->getAttribute('customer_id');


		//$store_id = Us2CustStorePeer::GetStoreByCustomer($this->customer_id);
		//$layouts = Us2ProductPeer::GetProductByStore($store_id);
		//$layouts->setFetchMode( ResultSet::FETCHMODE_ASSOC );

		$conn = Propel::GetConnection();
		$sqlconn = $conn->getResource();

		$sql 		= "select us2_product_customer_dial.us2_product_id,us2_product.name "
					. "FROM us2_product_customer_dial "
					. "JOIN us2_product ON us2_product_customer_dial.us2_product_id = us2_product.product_id "
					. "WHERE us2_product_customer_dial.customer_id = " . intval($this->getUser()->getAttribute('customer_id')) . " "
					. "ORDER BY us2_product.name ";
		$result = mysql_query($sql, $sqlconn) or die($sql . "\r\n" .mysql_error($sqlconn));

		$this->mailSelect = array();
		$this->emailSelect = array('-1' => 'Do not send mail');
		$this->mailSelect[-1] = 'Do not send mail';
		while ($row = mysql_fetch_array($result))
		{
			$this->mailSelect[$row['us2_product_id']] = $row['name'] . " (id:{$row['us2_product_id']}) ";
		}

		# ========== Load the email templates ==========
		$DmsMain 		= Propel::GetConnection('dms_main');
		$sql 	= "select product_id, name "
				. "FROM email_template "
				. "WHERE product_id > 0 "
				. "AND active_yn = 'Y' "
				. "ORDER by name, product_id ";
		$Rs 	= $DmsMain->executeQuery($sql);
		while($Rs->next())
		{
			$row 	= $Rs->getRow();
			$this->emailSelect[$row['product_id']] = $row['name'];
		}
	}


	/***
	`*
	`* Load Trigger Levels
	`*
	`************************************************************************************************/
	public function LoadTriggerLevels($TriggerNameId, $TriggerSettingId, $brand, $contract=false)
	{
		$this->existingFilters 	= array();
		$VehicleFilterId		= TriggerSettingFilterPeer::GetTriggerVehicleFilterId($TriggerNameId,$this->dmstrigconn);

		$C = new Criteria();
		$C->addAnd(TriggerSettingFilterPeer::FILTER_ID, $VehicleFilterId);
		$C->addAnd(TriggerSettingFilterPeer::BRAND, "$brand");
		if ($contract !== false) {
			$C->addAnd(TriggerSettingFilterPeer::SETTING_1, "$contract");
		}
		$C->addAnd(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->addAnd(TriggerSettingFilterPeer::CUSTOMER_ID, $this->CustomerId);
		$C->addAnd(TriggerSettingFilterPeer::ACTIVE_YN, 'Y');
		$C->addAscendingOrderByColumn(TriggerSettingFilterPeer::BRAND);

		$arrayFilter = TriggerSettingFilterPeer::doSelect($C, $this->dmstrigconn);

		foreach ($arrayFilter as $filter)
		{
			$this->existingFilters[] = array(
				'id' 						=> $filter->getTriggerSettingFilterId(),
				'enabled' 					=> $filter->getEnabledYn(),
				'level' 					=> $filter->getLevel(),
				'make' 						=> $filter->getBrand(),
				'returnmail' 				=> $filter->getMail11(),
				'salesmail' 				=> $filter->getMail21(),
				'mail_yn'					=> $filter->getMailYn(),
				'email_yn' 					=> $filter->getEmailYn(),
				'livecall_yn'				=> $filter->getLivecallYn(),
				'voice_yn'					=> $filter->getVoiceYn(),
				'sms_yn'					=> $filter->getSmsYn(),
				'facebook_yn'				=> $filter->getFacebookYn(),
				'coupon1_1' 				=> $filter->getCoupon11(),
				'coupon1_2' 				=> $filter->getCoupon12(),
				'coupon2_1' 				=> $filter->getCoupon21(),
				'coupon2_2' 				=> $filter->getCoupon22(),
				'email_chase_days_1' 		=> $filter->getEmailChaseDays1(),
				'email_chase_days_2'		=> $filter->getEmailChaseDays2(),
				'email_chase_days_3' 		=> $filter->getEmailChaseDays3(),
				'email_chase_days_4' 		=> $filter->getEmailChaseDays4(),
				'email_chase_days_5' 		=> $filter->getEmailChaseDays5(),
				'setting_1' 				=> $filter->getSetting1(),
				'setting_2' 				=> $filter->getSetting2(),
				'setting_3' 				=> $filter->getSetting3(),
				'setting_4' 				=> $filter->getSetting4(),
				'setting_5' 				=> $filter->getSetting5(),
				'setting_6' 				=> $filter->getSetting6(),
				'setting_7' 				=> $filter->getSetting7(),
				'setting_8' 				=> $filter->getSetting8(),
				'setting_9' 				=> $filter->getSetting9(),
				'setting_10' 				=> $filter->getSetting10(),
				'opcodes'					=> $filter->getOpcodes(),
				'parts_filter_customers'	=> unserialize($filter->getPartsFilterCustomers()),
				'notification_period'		=> $filter->getNotificationPeriod(),
				'warranty_expiration_mileage_zero_yn' => $filter->getWarrantyExpirationMileageZeroYn()
				#'timing' 				=> $filter->getNotificationPeriod() . " " . ucwords(strtolower($filter->getNotificationPeriodType())) . "s",
				#$temp["timing"] = $row['NOTIFICATION_PERIOD'];
			);
		}
	}


	/***
	`*
	`* Load Trigger Form
	`*
	`************************************************************************************************/
	public function LoadForm($TriggerNameId)
	{
		$this->CustomerId				= $this->customer_id;
		$this->TriggerSettingId 		= TriggerSettingPeer::GetSettingId($this->CustomerId, $TriggerNameId, $this->dmstrigconn);
		$this->Brands					= self::GetTriggerBrandLevels($TriggerNameId, $this->TriggerSettingId);
		$this->ProductConfiguredStats 	= $this->GetProductConfiguredStats($this->CustomerId);
		$this->OverviewStats			= $this->GetOverviewStats($this->CustomerId, $TriggerNameId);


		$this->TriggerLevel 	= intval($this->Get('level')) > 0 ? intval($this->Get('level')) : 1;
		$this->brand 			= $this->Get('brand') ? $this->Get('brand') : 'DEFAULT';
		// If this is one of the new HVAC triggers
		$this->DoLog(__LINE__ . ": TriggerNameId: {$TriggerNameId}");
		if (in_array($TriggerNameId, self::$NEW_HVAC_TRIGGERS)) {
			$this->loadHVACCustomerContractTypes($this->CustomerId);
			$this->contract			= $this->Get('contract') ? $this->Get('contract') : 'DEFAULT';
			$this->DoLog(__LINE__ . ": contract: {$this->contract}");
		} else {
			$this->contract			= false;
		}

		$this->LoadMakes();
		$this->LoadTriggerOptions($TriggerNameId);
		$this->DoLog(__LINE__.": LoadTriggerLevels({$TriggerNameId}, {$this->TriggerSettingId}, {$this->brand}, {$this->contract})");
		$this->LoadTriggerLevels($TriggerNameId, $this->TriggerSettingId, $this->brand, $this->contract);


		$this->DoLog(__LINE__.": LoadForm() existingFilters = " . print_r($this->existingFilters, true) );




		$this->vehicleFilterData = array();
		//$this->vehicleFilterData["vehicleEmail"] = $this->vehicleEmail;
		//$this->vehicleFilterData["couponSelect"] = $this->couponSelect;
		$this->vehicleFilterData['makedrop'] 		= $this->makedrop;
		$this->vehicleFilterData['hvacdrop']		= $this->hvacdrop;
		$this->vehicleFilterData['hvacContracts']	= $this->hvacContracts;
		$this->vehicleFilterData['mail']			= $this->mailSelect;
		$this->vehicleFilterData['email']			= $this->emailSelect;
		$this->vehicleFilterData['existingFilters'] = $this->existingFilters;
		$this->vehicleFilterData['delaySelect']		= $this->delaySelect;
		$this->vehicleFilterData['hourSelect']		= $this->hourSelect;
		$this->vehicleFilterData['vehicleNotificationTiming'] = $this->vehicleNotificationTiming;


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

		if ($TriggerNameId==1) {
			$this->filterSettings = array();

			$C = new Criteria();
			$C->addSelectColumn(TriggerSettingFilterPeer::TIME_MILEAGE_TYPE);
			$C->add(TriggerSettingFilterPeer::CUSTOMER_ID, $this->CustomerId);
			$C->add(TriggerSettingFilterPeer::FILTER_ID, 1);
			$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID, $this->TriggerSettingId);
			// adding the brand to the query - Rick 2018-08-28
			$C->add(TriggerSettingFilterPeer::BRAND, $this->brand);
			$filterrs = TriggerSettingFilterPeer::doSelectRs($C, $this->dmstrigconn);



			$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
			$filterrs->next();
			$row = $filterrs->getRow();
			$this->filterSettings["TimeAndMileage"] = $row["TIME_MILEAGE_TYPE"];

			$C = new Criteria();
			$C->addSelectColumn(TriggerSettingFilterPeer::OPCODES);
			$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);

			$C->add(TriggerSettingFilterPeer::FILTER_ID,2);
			$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
			// adding the brand to the query - Rick 2018-08-28
			$C->add(TriggerSettingFilterPeer::BRAND, $this->brand);

			$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);

		$this->DoLog(__LINE__.": LoadTriggerLevels() filterrs = " . print_r($filterrs, true) . "");

			$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
			$filterrs->next();
			$row = $filterrs->getRow();
			$this->filterSettings["OilChangeOpCodes"] = $row["OPCODES"];
			// echo "TriggerController:: TriggerNameId={$TriggerNameId}<br />";
			// echo "row = <pre>" . print_r($row, true) . "</pre><br />";
			// echo "this->brand = {$this->brand}<br />";
			// $this->filterSettings = $row["OPCODES"];

			// echo "this->filterSettings = <pre>" . print_r($this->filterSettings, true)  . "</pre><br />";

		}

		if ($TriggerNameId == CUSTOMER_RECOVERY) {
			$this->filterSettings = array();

			$C = new Criteria();
			$C->addSelectColumn(TriggerSettingFilterPeer::RECOVERY_STATE_ONLY);
			$C->addSelectColumn(TriggerSettingFilterPeer::RECOVERY_OLDEST_YEAR);
			$C->addSelectColumn(TriggerSettingFilterPeer::RECOVERY_MAX_MONTHS);
			$C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_INCLUDE);
			$C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_EXCLUDE);
			$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
			$C->add(TriggerSettingFilterPeer::FILTER_ID,19);
			$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
			$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);


			$this->DoLog(__LINE__.": LoadForm() CUSTOMER_RECOVERY - filterrs = " . print_r($filterrs, true) );

			$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
			$filterrs->next();
			$row = $filterrs->getRow();

			$this->temp = array();
			if ($row["RECOVERY_STATE_ONLY"] == "Y")
			$this->temp["instate"] = true;
			else $this->temp["instate"] = false;
			$this->temp["oldestyear"] = $row["RECOVERY_OLDEST_YEAR"];
			$this->temp["maxmonths"] = $row["RECOVERY_MAX_MONTHS"];
			$this->temp["includemakes"] = $row["VEHICLE_MAKES_INCLUDE"];
			$this->temp["excludemakes"] = $row["VEHICLE_MAKES_EXCLUDE"];
			$this->filterSettings["Recovery"] = $this->temp;

			$this->DoLog(__LINE__.": LoadForm() CUSTOMER_RECOVERY this->filterSettings = " . print_r($this->filterSettings, true) );
		}

		if ($TriggerNameId == STATE_INSPECTION_REMINDER)
		{
			//Array to pass to vehicle filter partials for populating drop boxes.
			$this->filterSettings = array();
			#$this->filterSettings["StateInspection"]["inspections"] = $this->inspections;

			$C = new Criteria();
			$C->addSelectColumn(TriggerSettingFilterPeer::STATE_INSPECTION_REQUIRED);
			$C->addSelectColumn(TriggerSettingFilterPeer::OPCODES);
			$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
			$C->add(TriggerSettingFilterPeer::FILTER_ID,21);
			$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
			$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
			$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
			$filterrs->next();
			$row = $filterrs->getRow();
			#$temp = array_keys($this->inspections,$row['STATE_INSPECTION_REQUIRED']);
			#$this->filterSettings["StateInspection"]["inspection"] = $temp[0];
			$this->filterSettings["StateInspection"]["opcodes"] = $row["OPCODES"];
		}

		if ($TriggerNameId==12)
		{
				$this->filterSettings = array();

				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_CUST_PROMPT_ENABLED_YN);
				$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_CUST_PROMPT_GREETING);
				$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_CUST_PROMPT_VOICEMAIL);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,11);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();
				$this->temp = array();
				if ($row["FOLLOWUP_CUST_PROMPT_ENABLED_YN"] == "Y")
				{
					$this->temp["enablecustom"] = true;
					$this->temp["greetingprompt"] = $row["FOLLOWUP_CUST_PROMPT_GREETING"];
					$this->temp["voiceprompt"] = $row["FOLLOWUP_CUST_PROMPT_VOICEMAIL"];
				}
				else $this->temp["enablecustom"] = false;
				$this->filterSettings["FollowUpCustomGreetingPrompt"] = $this->temp;

				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_VEHICLE_TYPE);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,28);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();
				$this->filterSettings["SalesVehicleType"] = $row["FOLLOWUP_VEHICLE_TYPE"];
		}

		if ($TriggerNameId == 7)
		{
				$this->filterSettings = array();

				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::ASR_PRO_ENABLED_YN);
				$C->addSelectColumn(TriggerSettingFilterPeer::ASR_RED_REQUIRED_YN);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,16);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();
				$this->temp = array();
				if ($row["ASR_PRO_ENABLED_YN"] == "Y")
				$this->temp["asrenabled"] = true;
				else $this->temp["asrenabled"] = false;
				if ($row["ASR_RED_REQUIRED_YN"] == "Y")
				$this->temp["requireasr"] = true;
				else $this->temp["requireasr"] = false;
				$this->filterSettings["AsrProIntegration"] = $this->temp;

				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_INCLUDE);
				$C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_EXCLUDE);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,27);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();
				$this->temp = array();
				$this->temp["includemakes"] = $row["VEHICLE_MAKES_INCLUDE"];
				$this->temp["excludemakes"] = $row["VEHICLE_MAKES_EXCLUDE"];
				$this->filterSettings["MakeIncludeExclude"] = $this->temp;

				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::RECOMMENDATIONS_ENABLED_YN);
				$C->addSelectColumn(TriggerSettingFilterPeer::RECOMMENDATIONS_AFTER_DATE);
				$C->addSelectColumn(TriggerSettingFilterPeer::RECOMMENDATIONS_INCLUDE_TEXT);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,17);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();
				$this->temp = array();
				if ($row["RECOMMENDATIONS_ENABLED_YN"] == "Y")
				$this->temp["processrecommends"] = true;
				else $this->temp["processrecommends"] = false;
				$this->temp["emailrecommends"] = $row["RECOMMENDATIONS_INCLUDE_TEXT"];
				$this->temp["donotprocessbefore"] = date('n/j/y',strtotime($row["RECOMMENDATIONS_AFTER_DATE"]));
				$this->filterSettings["Recommendations"] = $this->temp;

		}

        // HVAC forms start here.
		if ($TriggerNameId == HVAC_CUSTOMER_RECOVERY)
		{
			$this->filterSettings = array();

            $C = new Criteria();
            $C->addSelectColumn(TriggerSettingFilterPeer::RECOVERY_STATE_ONLY);
            $C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_INCLUDE);
            $C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_EXCLUDE);
            $C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
            $C->add(TriggerSettingFilterPeer::FILTER_ID,39);
            $C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
            $filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
            $filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
            $filterrs->next();
            $row = $filterrs->getRow();

            $this->temp = array();
            if ($row["RECOVERY_STATE_ONLY"] == "Y") {
                $this->temp["instate"] = true;
            } else {
                $this->temp["instate"] = false;
            }
            $this->temp["includemakes"] = $row["VEHICLE_MAKES_INCLUDE"];
            $this->temp["excludemakes"] = $row["VEHICLE_MAKES_EXCLUDE"];
            $this->filterSettings["HVACRecovery"] = $this->temp;
		}

		if ($TriggerNameId == HVAC_DECLINED_SERVICES)
		{
    		$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array();

            /**`
            *` Loop through each level and create the trigger filters
            *` for the selected brand
            *````````````````````````````````````````````````````````````````*/
            for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
            {
                $C = new Criteria();
                $C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
                $C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
                $C->addSelectColumn(TriggerSettingFilterPeer::OPCODES);
                $C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
                $C->add(TriggerSettingFilterPeer::FILTER_ID,40);
                $C->add(TriggerSettingFilterPeer::LEVEL, $level);
                $C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
                $filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
                $filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
                $filterrs->next();
                $row = $filterrs->getRow();

                $this->temp = array();
                $this->temp["delay"] = $row["NOTIFICATION_PERIOD"];
                $this->temp["delay_type"] = $row["NOTIFICATION_PERIOD_TYPE"];
                $this->temp["opcodes"] = unserialize($row["OPCODES"]);
                $this->filterSettings["HVACDeclinedServicesVehicleFilter"][] = $this->temp;
            }
		}

		if ($TriggerNameId == HVAC_ANNUAL_MAINTENANCE)
		{
    		$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array();

            /**`
            *` Loop through each level and create the trigger filters
            *` for the selected brand
            *````````````````````````````````````````````````````````````````*/
            for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
            {
                $C = new Criteria();
                $C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
                $C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
                $C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
                $C->add(TriggerSettingFilterPeer::FILTER_ID,41);
                $C->add(TriggerSettingFilterPeer::LEVEL, $level);
                $C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
                $filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
                $filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
                $filterrs->next();
                $row = $filterrs->getRow();

                $this->temp = array();
                $this->temp["delay"] = $row["NOTIFICATION_PERIOD"];
                $this->temp["delay_type"] = $row["NOTIFICATION_PERIOD_TYPE"];
                $this->filterSettings["HVACAnnualMaintenanceVehicleFilter"][] = $this->temp;
            }
		}

		if ($TriggerNameId == HIJACK) {
			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array();

			/**`
			*` Loop through each level and create the trigger filters
			*` for the selected brand
			*````````````````````````````````````````````````````````````````*/
			for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
			{
				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,49);
				$C->add(TriggerSettingFilterPeer::LEVEL, $level);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();

				$this->temp = array();
				$this->temp["delay"] = $row["NOTIFICATION_PERIOD"];
				$this->temp["delay_type"] = $row["NOTIFICATION_PERIOD_TYPE"];
				$this->filterSettings["HijackVehicleFilter"][] = $this->temp;
			}
		}

		if ($TriggerNameId == INMARKET_SHOPPER) {
			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array();

			/**`
			*` Loop through each level and create the trigger filters
			*` for the selected brand
			*````````````````````````````````````````````````````````````````*/
			for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
			{
				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,50);
				$C->add(TriggerSettingFilterPeer::LEVEL, $level);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();

				$this->temp = array();
				$this->temp["delay"] = $row["NOTIFICATION_PERIOD"];
				$this->temp["delay_type"] = $row["NOTIFICATION_PERIOD_TYPE"];
				$this->filterSettings["InMarketVehicleFilter"][] = $this->temp;
			}
		}

		if ($TriggerNameId == HVAC_THANK_YOU) {
			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array();

			/**`
			*` Loop through each level and create the trigger filters
			*` for the selected brand
			*````````````````````````````````````````````````````````````````*/
			for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
			{
				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
				$C->addSelectColumn(TriggerSettingFilterPeer::SETTING_1);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,53);
				$C->add(TriggerSettingFilterPeer::LEVEL, $level);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$this->doLog(__LINE__.": this->brand: {$this->brand}");
				$C->add(TriggerSettingFilterPeer::BRAND,$this->brand);
				$this->doLog(__LINE__.": this->contract: {$this->contract}");
				if (!empty($this->contract)) {
					$C->add(TriggerSettingFilterPeer::SETTING_1,$this->contract);
				}
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();

				$this->temp = array();
				// echo "<pre>brand: {$this->brand}, row: " . print_r($row, true); exit;
				$this->temp["delay"] = $row["NOTIFICATION_PERIOD"];
				$this->temp["delay_type"] = $row["NOTIFICATION_PERIOD_TYPE"];
				$this->temp["contract"] = $row["SETTING_1"];
				$this->filterSettings["HVACThankYouWelcomeVehicleFilter"][] = $this->temp;
			}
		}

		if ($TriggerNameId == HVAC_SERVICE_REMINDER) {
			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array();

			/**`
			*` Loop through each level and create the trigger filters
			*` for the selected brand
			*````````````````````````````````````````````````````````````````*/
			for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
			{
				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
				$C->addSelectColumn(TriggerSettingFilterPeer::SETTING_1);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,54);
				$C->add(TriggerSettingFilterPeer::LEVEL, $level);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$C->add(TriggerSettingFilterPeer::BRAND,$this->brand);
				if (!empty($this->contract)) {
					$C->add(TriggerSettingFilterPeer::SETTING_1,$this->contract);
				}
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();

				$this->temp = array();
				$this->temp["delay"] = $row["NOTIFICATION_PERIOD"];
				$this->temp["delay_type"] = $row["NOTIFICATION_PERIOD_TYPE"];
				$this->temp["contract"] = $row["SETTING_1"];
				$this->filterSettings["HVACPreServiceEventVehicleFilter"][] = $this->temp;
			}
		}

		if ($TriggerNameId == HVAC_PRE_RENEWAL) {
			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array();

			/**`
			*` Loop through each level and create the trigger filters
			*` for the selected brand
			*````````````````````````````````````````````````````````````````*/
			for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
			{
				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
				$C->addSelectColumn(TriggerSettingFilterPeer::SETTING_1);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,55);
				$C->add(TriggerSettingFilterPeer::LEVEL, $level);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$C->add(TriggerSettingFilterPeer::BRAND,$this->brand);
				if (!empty($this->contract)) {
					$C->add(TriggerSettingFilterPeer::SETTING_1,$this->contract);
				}
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();

				$this->temp = array();
				$this->temp["timing"] = $row["NOTIFICATION_PERIOD"];
				$this->temp["timing_type"] = $row["NOTIFICATION_PERIOD_TYPE"];
				$this->temp["contract"] = $row["SETTING_1"];
				$this->filterSettings["HVACPreRenewalVehicleFilter"][] = $this->temp;
			}
		}

		if ($TriggerNameId == HVAC_SERVICE_CONTRACT_EXPIRATION) {
			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array();

			/**`
			*` Loop through each level and create the trigger filters
			*` for the selected brand
			*````````````````````````````````````````````````````````````````*/
			for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
			{
				$C = new Criteria();
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
				$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
				$C->addSelectColumn(TriggerSettingFilterPeer::SETTING_1);
				$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->CustomerId);
				$C->add(TriggerSettingFilterPeer::FILTER_ID,56);
				$C->add(TriggerSettingFilterPeer::LEVEL, $level);
				$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$this->TriggerSettingId);
				$C->add(TriggerSettingFilterPeer::BRAND,$this->brand);
				if (!empty($this->contract)) {
					$C->add(TriggerSettingFilterPeer::SETTING_1,$this->contract);
				}
				$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
				$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
				$filterrs->next();
				$row = $filterrs->getRow();

				$this->temp = array();
				$this->temp["delay"] = $row["NOTIFICATION_PERIOD"];
				$this->temp["delay_type"] = $row["NOTIFICATION_PERIOD_TYPE"];
				$this->temp["contract"] = $row["SETTING_1"];
				$this->filterSettings["HVACServiceContractExpirationVehicleFilter"][] = $this->temp;
			}
		}

		if ( $TriggerNameId == 52 ) 		// Digital Watchdog (aka smartchannel)
		{
			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings 	= array('customer_id' 	=> $this->customer_id,
											'client_id'		=> 0,
											'pixl'			=> array('trig_list' 		=> array(),
																	 'trig_list_detail'	=> array(),
																	 'filters' 			=> array(0 => '-- Select Filter --'),
																	 'postem'				=> $_POST,
																	 'pixl_company_list'		=> array("" => "-- Select Company --")
																	),
											'debug'			=> array()
											);




			$Wilma = Propel::GetConnection();
			$sql = "SELECT client_id FROM customer WHERE customer_id = '{$this->customer_id}'";
			$Rs = $Wilma->executeQuery($sql);
			while ($Rs->next())
			{
				$this->filterSettings['client_id'] = $Rs->get('client_id');
			}

			// append the email status for this cutomer.
			$EmailList 			= array();
			$Query 				= "SELECT product_id, name "
								. "FROM email_template_map, email_layout "
								. "WHERE customer_id = {$this->customer_id} "
								. "AND email_template_map.email_layout_id = email_layout.email_layout_id "
								. "AND active_yn = 'Y' ";
			$Rs 				= $this->dmstrigconn->executeQuery($Query);
			while($Rs->next())
			{
				$EmailList[$Rs->get('product_id')] = $Rs->get('name');
			}

			foreach($this->vehicleFilterData['mail'] as $ProductId => $ProductName)
			{
				$EmailInfo 	= "(email: -- not set -- )";
				if ( isset($EmailList[$ProductId]) )
				{
					$EmailInfo = "(email: {$EmailList[$ProductId]})";
				}
				$this->vehicleFilterData['mail'][$ProductId] = $ProductName . " {$EmailInfo}";
			}

			$Query 				= "SELECT * FROM smartchannel_trigger_name "
								. "WHERE active_yn = 'Y' ";
			$Rs 				= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				$filterTrigRow 			= $Rs->getRow();
				$this->filterSettings['pixl']['filters'][$filterTrigRow['smartchannel_trigger_name_id']] = $filterTrigRow['name'];
			}


			// Move up/down the sequence
			if ( $this->getRequestParameter('move') != "" )
			{
				$DetailId 	= $this->getRequestParameter('detail_id');
				$this->MoveSmartchannelDetail($DetailId, $this->getRequestParameter('move'));

			}



			$TrigIdList 		= array();
			// Get the list of smart channel triggers for this customer
			$Query 				= "SELECT * FROM smartchannel_customer_trigger "
								. "WHERE customer_id = {$this->customer_id} "
								. "AND active_yn = 'Y' ";
			$Rs 				= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				//$this->TrigList[] = $Rs->getRow();
				$smartchannel_customer_trigger_id = $Rs->get('smartchannel_customer_trigger_id');
				$this->filterSettings['pixl']['trig_list'][$smartchannel_customer_trigger_id] 	= $Rs->getRow();
				$TrigIdList[] 	= $Rs->get('smartchannel_customer_trigger_id');
			}

			if ( count($TrigIdList) > 0 )
			{
				$Query 			= "SELECT smartchannel_customer_trigger_detail.*, smartchannel_trigger_name.name as trigger_name "
								. "FROM smartchannel_customer_trigger_detail, smartchannel_trigger_name "
								. "WHERE smartchannel_customer_trigger_detail.smartchannel_customer_trigger_id in (" . join(",", $TrigIdList) . ") "
								. "AND smartchannel_customer_trigger_detail.smartchannel_trigger_name_id = smartchannel_trigger_name.smartchannel_trigger_name_id "
								. "ORDER BY smartchannel_customer_trigger_detail.smartchannel_customer_trigger_id, sequence_pos_id ";
							// echo "Query = {$Query}<br />";
				$Rs 				= $Wilma->executeQuery($Query);
				while($Rs->next())
				{
					$Row 		= $Rs->getRow();
					if ( !is_array($this->filterSettings['pixl']['trig_list_detail'][$Row['smartchannel_customer_trigger_id']]))
					{
						$this->filterSettings['pixl']['trig_list_detail'][$Row['smartchannel_customer_trigger_id']] = array();
					}
					$this->filterSettings['pixl']['trig_list_detail'][$Row['smartchannel_customer_trigger_id']][$Row['sequence_pos_id']] = $Row;
				}

			}
			$Query 				= "SELECT company_id, name "
								. "FROM smartchannel_company "
								. "WHERE active_yn = 'Y' "
								. "ORDER BY name";
			$Rs 				= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				$this->filterSettings['pixl']['pixl_company_list'][$Rs->get('company_id')] = $Rs->get('name');
			}
			$this->filterSettings['pixl']['postem'] = $_POST;





		}

		if ( $TriggerNameId == 53 ) 		// Intelligent Mapping - autodealer
		{
			$BrandType 				= "AUTODEALER";

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

			$AmmsCoreDDS 			= new AmmsCoreDDSApi();

			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array('customer_id' => $this->customer_id);
			if ( isset($this->CustomerProfileData['dds_dealer_id']) && $this->CustomerProfileData['dds_dealer_id'] != "" )
			{
				$this->filterSettings['dds_dealer_id'] = $this->CustomerProfileData['dds_dealer_id'];
			}

			$DealerZip 				= "";
			$Wilma = Propel::GetConnection();
			$sql = "SELECT zip, lat, lon, client_id FROM customer WHERE customer_id = '{$this->customer_id}'";
			$Rs = $Wilma->executeQuery($sql);
			while ($Rs->next())
			{
				$this->filterSettings['client_id'] = $Rs->get('client_id');
				$DealerZip 			= substr($Rs->get('zip'), 0, 5);
				$DealerLat 			= $Rs->get('lat');
				$DealerLon 			= $Rs->get('lon');
			}
			$DdsDealerList 			= array();



			// append the email status for this cutomer.
			$EmailList 			= array();
			$Query 				= "SELECT product_id, name "
								. "FROM email_template_map, email_layout "
								. "WHERE customer_id = {$this->customer_id} "
								. "AND email_template_map.email_layout_id = email_layout.email_layout_id "
								. "AND active_yn = 'Y' ";
			$Rs 				= $this->dmstrigconn->executeQuery($Query);
			while($Rs->next())
			{
				$EmailList[$Rs->get('product_id')] = $Rs->get('name');
			}

			foreach($this->vehicleFilterData['mail'] as $ProductId => $ProductName)
			{
				$EmailInfo 	= "(email: -- not set -- )";
				if ( isset($EamilList[$ProductId]) )
				{
					$EmailInfo = "(email: {$EmailInfo[$ProductId]})";
				}
				$this->vehicleFilterData['mail'][$ProductId] = $ProductName . " {$EmailInfo}";
			}


			$this->filterSettings['sort'] 	= 'name';
			if ( $this->getRequestParameter('sort') == "radius")
			{
				$this->filterSettings['sort'] = 'radius';
			}

			// Move up/down the sequence
			if ( $this->getRequestParameter('move') != "" )
			{
				$DetailId 	= $this->getRequestParameter('detail_id');
				$this->MoveIntelligentMappingDetail($DetailId, $this->getRequestParameter('move'));

			}

			// Delete the element
			if ( $this->getRequestParameter('action'))
			{
				if($this->getRequestParameter('action') == 'delete')
				{
					$DetailId 	= $this->getRequestParameter('detail_id');
					$Query 		= "UPDATE intelligent_mapping_trigger_detail "
								. "SET active_yn = 'N' "
								. "WHERE intelligent_mapping_trigger_detail_id = {$DetailId} "
								. "AND active_yn = 'Y' ";
					$Rs 		= $Wilma->executeQuery($Query);
				}
			}


			// pulse counts
			$Query 					= "SELECT * FROM dds_pulse_count "
									. "WHERE customer_id = {$this->filterSettings['customer_id']} "
									. "AND brand_type = 'AUTODEALER' ";
			$Rs 					= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				$this->filterSettings['pulse_count'] 	= $Rs->getRow();
				if ( substr($this->filterSettings['pulse_count']['pulse_data_json'], 0, 1) == '"')
				{
					$this->filterSettings['pulse_count']['pulse_data_json'] = substr($this->filterSettings['pulse_count']['pulse_data_json'], 1, strlen($this->filterSettings['pulse_count']['pulse_data_json']) - 2 );
				}
				// $PulseCountDealers 	= json_decode($this->filterSettings['pulse_count']['pulse_data_json'], true);
				// foreach($PulseCountDealers as )

				// Add in the radius values
				$DdsDealerData 	= json_decode($this->filterSettings['pulse_count']['pulse_data_json'], true);
				foreach($DdsDealerData as $tempDdsDealerId => $tempRec)
				{
					// $DdsDealerData[$tempDdsDealerId]['dealer_info']['tempRec'] 		= $tempRec;
					// $DdsDealerData[$tempDdsDealerId]['dealer_info']['DealerLat'] 	= $DealerLat;
					// $DdsDealerData[$tempDdsDealerId]['dealer_info']['DealerLon'] 	= $DealerLon;
					$DdsDealerData[$tempDdsDealerId]['dealer_info']['radius']		= ZipcodesPeer::great_circle_distance($DealerLat, $tempRec['dealer_info']['lat'], $DealerLon, $tempRec['dealer_info']['lon']);
				}
				$this->filterSettings['pulse_count']['pulse_data_json'] =json_encode($DdsDealerData);
			}


			// pulse subscrptions
			$Query 					= "SELECT * from dds_subscription "
									. "WHERE customer_id = {$this->filterSettings['customer_id']} "
									. "AND brand_type = 'AUTODEALER' ";
			$Rs 					= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				$this->filterSettings['pulse_subscription'] 	= $Rs->getRow();
			}



			$this->filterSettings['dds_dealer_list'] 	= array();
			$this->filterSettings['dds_dealer_display']	= array();
			//if ( $this->DdsDealerId != "" && $this->Radius )
			if ( $this->filterSettings['dds_dealer_id'] != "" && $this->filterSettings['pulse_subscription']['radius'] )
			{
				//if ( $this->BrandType != "AUTODEALER" ) 
					$this->filterSettings['debug'] = array();
					$this->filterSettings['debug'][] =  "Calling AmmsCoreDDS->GetRadiusDealers({$this->filterSettings['dds_dealer_id']}, {$this->filterSettings['pulse_subscription']['radius']}, 'AUTODEALER')<br />";
				$Result 		= json_decode($AmmsCoreDDS->GetRadiusDealers($this->filterSettings['dds_dealer_id'], $this->filterSettings['pulse_subscription']['radius'], "AUTODEALER"), true);
				// if ( $this->BrandType != "AUTODEALER" ) 
				// echo "GetRadiusDealers = <pre>" . print_r($Result, true) . "</pre><br />";

				if ( $Result['status'] == 'success')
				{				
					$RawDdsDealerList 	= $Result['data'];
					foreach($RawDdsDealerList as $key => $Row)
					{
						//$this->DdsDealerList[$Row['dealerId']] = $Row['dealerName'];
						$this->filterSettings['dds_dealer_list'][$Row['dealerId']] = $Row;
						$DisplayKey 	= sprintf("%s_%s_%d", $Row['dealerName'], $Row['zip'], $Row['dealerId']);
						$this->filterSettings['dds_dealer_display'][$DisplayKey] = $Row['dealerId'];
					}
					//asort($this->DdsDealerList);
					ksort($this->filterSettings['dds_dealer_display']);
					// echo "DdsDealerList = <pre>" . print_r($this->DdsDealerList, true) . "</pre><br />";
					// echo "DealerDisplay = <pre>" . print_r($this->DealerDisplay, true) . "</pre><br />";
				}
			}

			// Get the trigger settings
			if ( intval($this->filterSettings['pulse_subscription']['dds_subscription_id']) > 0 )
			{
				$Query 		= "SELECT * FROM intelligent_mapping_trigger "
							. "WHERE dds_subscription_id = {$this->filterSettings['pulse_subscription']['dds_subscription_id']} ";
				$Rs 		= $Wilma->executeQuery($Query);
				while($Rs->next())
				{
					$ImTrigRec = $Rs->getRow();
					$this->filterSettings['intelligent_mapping_trigger'] = $ImTrigRec;
				}
				if ( $ImTrigRec['intelligent_mapping_trigger_id'] > 0 )
				{
					$this->filterSettings['intelligent_mapping_trigger_detail'] = array();
					$Query 	= "SELECT * FROM intelligent_mapping_trigger_detail "
							. "WHERE intelligent_mapping_trigger_id = {$ImTrigRec['intelligent_mapping_trigger_id']} "
							. "AND active_yn = 'Y' "
							. "ORDER BY sequence_pos_id ";
					$Rs 	= $Wilma->executeQuery($Query);
					while($Rs->next())
					{
						$DetailId 	= $Rs->get('intelligent_mapping_trigger_detail_id');
						$this->filterSettings['intelligent_mapping_trigger_detail'][$DetailId] = $Rs->getRow();
					}

				}

			}

			$this->filterSettings['intelligent_mapping_names'] = array('0' => '-- Select Filter --');


			$Query 	= "SELECT * FROM intelligent_mapping_trigger_name "
					. "WHERE active_yn = 'Y' "
					. "ORDER BY name ";
			$Rs 	= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				$Row 	= $Rs->getRow();
				$this->filterSettings['intelligent_mapping_names'][$Row['intelligent_mapping_trigger_name_id']] = $Row['name'];
			}



			// die("Aborting\n");

		}




		if ( $TriggerNameId == 54 ) 		// Intelligent Mapping - autodealer service
		{
			$BrandType 				= "AUTOSERVICE";

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

			$AmmsCoreDDS 			= new AmmsCoreDDSApi();

			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings = array('customer_id' => $this->customer_id);
			if ( isset($this->CustomerProfileData['dds_dealer_id']) && $this->CustomerProfileData['dds_dealer_id'] != "" )
			{
				$this->filterSettings['dds_dealer_id'] = $this->CustomerProfileData['dds_dealer_id'];
			}


			$Wilma = Propel::GetConnection();
			$sql = "SELECT client_id FROM customer WHERE customer_id = '{$this->customer_id}'";
			$Rs = $Wilma->executeQuery($sql);
			while ($Rs->next())
			{
				$this->filterSettings['client_id'] = $Rs->get('client_id');
			}
			$DdsDealerList 			= array();


			// append the email status for this cutomer.
			$EmailList 			= array();
			$Query 				= "SELECT product_id, name "
								. "FROM email_template_map, email_layout "
								. "WHERE customer_id = {$this->customer_id} "
								. "AND email_template_map.email_layout_id = email_layout.email_layout_id "
								. "AND active_yn = 'Y' ";
			$Rs 				= $this->dmstrigconn->executeQuery($Query);
			while($Rs->next())
			{
				$EmailList[$Rs->get('product_id')] = $Rs->get('name');
			}

			foreach($this->vehicleFilterData['mail'] as $ProductId => $ProductName)
			{
				$EmailInfo 	= "(email: -- not set -- )";
				if ( isset($EamilList[$ProductId]) )
				{
					$EmailInfo = "(email: {$EmailInfo[$ProductId]})";
				}
				$this->vehicleFilterData['mail'][$ProductId] = $ProductName . " {$EmailInfo}";
			}


			// Move up/down the sequence
			if ( $this->getRequestParameter('move') != "" )
			{
				$DetailId 	= $this->getRequestParameter('detail_id');
				$this->MoveIntelligentMappingDetail($DetailId, $this->getRequestParameter('move'));

			}

			// Delete the element
			if ( $this->getRequestParameter('action'))
			{
				if($this->getRequestParameter('action') == 'delete')
				{
					$DetailId 	= $this->getRequestParameter('detail_id');
					$Query 		= "UPDATE intelligent_mapping_trigger_detail "
								. "SET active_yn = 'N' "
								. "WHERE intelligent_mapping_trigger_detail_id = {$DetailId} "
								. "AND active_yn = 'Y' ";
					$Rs 		= $Wilma->executeQuery($Query);
				}
			}


			// pulse counts
			$Query 					= "SELECT * FROM dds_pulse_count "
									. "WHERE customer_id = {$this->filterSettings['customer_id']} "
									. "AND brand_type = 'AUTOSERVICE' ";
			$Rs 					= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				$this->filterSettings['pulse_count'] 	= $Rs->getRow();
				if ( substr($this->filterSettings['pulse_count']['pulse_data_json'], 0, 1) == '"')
				{
					$this->filterSettings['pulse_count']['pulse_data_json'] = substr($this->filterSettings['pulse_count']['pulse_data_json'], 1, strlen($this->filterSettings['pulse_count']['pulse_data_json']) - 2 );
				}
				// $PulseCountDealers 	= json_decode($this->filterSettings['pulse_count']['pulse_data_json'], true);
				// foreach($PulseCountDealers as )
			}


			// pulse subscrptions
			$Query 					= "SELECT * from dds_subscription "
									. "WHERE customer_id = {$this->filterSettings['customer_id']} "
									. "AND brand_type = 'AUTOSERVICE' ";
			$Rs 					= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				$this->filterSettings['pulse_subscription'] 	= $Rs->getRow();
			}



			$this->filterSettings['dds_dealer_list'] 	= array();
			$this->filterSettings['dds_dealer_display']	= array();
			//if ( $this->DdsDealerId != "" && $this->Radius )
			if ( $this->filterSettings['dds_dealer_id'] != "" && $this->filterSettings['pulse_subscription']['radius'] )
			{
				//if ( $this->BrandType != "AUTODEALER" ) 
					$this->filterSettings['debug'] = array();
					$this->filterSettings['debug'][] =  "Calling AmmsCoreDDS->GetRadiusDealers({$this->filterSettings['dds_dealer_id']}, {$this->filterSettings['pulse_subscription']['radius']}, 'AUTOSERVICE')<br />";
				$Result 		= json_decode($AmmsCoreDDS->GetRadiusDealers($this->filterSettings['dds_dealer_id'], $this->filterSettings['pulse_subscription']['radius'], "AUTOSERVICE"), true);
				// if ( $this->BrandType != "AUTODEALER" ) 
				// echo "GetRadiusDealers = <pre>" . print_r($Result, true) . "</pre><br />";

				if ( $Result['status'] == 'success')
				{				
					$RawDdsDealerList 	= $Result['data'];
					foreach($RawDdsDealerList as $key => $Row)
					{
						//$this->DdsDealerList[$Row['dealerId']] = $Row['dealerName'];
						$this->filterSettings['dds_dealer_list'][$Row['dealerId']] = $Row;
						$DisplayKey 	= sprintf("%s_%s_%d", $Row['dealerName'], $Row['zip'], $Row['dealerId']);
						$this->filterSettings['dds_dealer_display'][$DisplayKey] = $Row['dealerId'];
					}
					//asort($this->DdsDealerList);
					ksort($this->filterSettings['dds_dealer_display']);
					// echo "DdsDealerList = <pre>" . print_r($this->DdsDealerList, true) . "</pre><br />";
					// echo "DealerDisplay = <pre>" . print_r($this->DealerDisplay, true) . "</pre><br />";
				}
			}

			// Get the trigger settings
			if ( intval($this->filterSettings['pulse_subscription']['dds_subscription_id']) > 0 )
			{
				$Query 		= "SELECT * FROM intelligent_mapping_trigger "
							. "WHERE dds_subscription_id = {$this->filterSettings['pulse_subscription']['dds_subscription_id']} ";
				$Rs 		= $Wilma->executeQuery($Query);
				while($Rs->next())
				{
					$ImTrigRec = $Rs->getRow();
					$this->filterSettings['intelligent_mapping_trigger'] = $ImTrigRec;
				}
				if ( $ImTrigRec['intelligent_mapping_trigger_id'] > 0 )
				{
					$this->filterSettings['intelligent_mapping_trigger_detail'] = array();
					$Query 	= "SELECT * FROM intelligent_mapping_trigger_detail "
							. "WHERE intelligent_mapping_trigger_id = {$ImTrigRec['intelligent_mapping_trigger_id']} "
							. "AND active_yn = 'Y' "
							. "ORDER BY sequence_pos_id ";
					$Rs 	= $Wilma->executeQuery($Query);
					while($Rs->next())
					{
						$DetailId 	= $Rs->get('intelligent_mapping_trigger_detail_id');
						$this->filterSettings['intelligent_mapping_trigger_detail'][$DetailId] = $Rs->getRow();
					}

				}

			}

			$this->filterSettings['intelligent_mapping_names'] = array('0' => '-- Select Filter --');


			$Query 	= "SELECT * FROM intelligent_mapping_trigger_name "
					. "WHERE active_yn = 'Y' "
					. "ORDER BY name ";
			$Rs 	= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				$Row 	= $Rs->getRow();
				$this->filterSettings['intelligent_mapping_names'][$Row['intelligent_mapping_trigger_name_id']] = $Row['name'];
			}

		}


		if ( $TriggerNameId == 56 ) 		// DealerX
		{
			// $BrandType 				= "AUTODEALER";

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

			// $AmmsCoreDDS 			= new AmmsCoreDDSApi();

			$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerNameId, $this->dmstrigconn);
			$this->filterSettings 	= array('customer_id' => $this->customer_id);
			// if ( isset($this->CustomerProfileData['external_customer_id']) && $this->CustomerProfileData['external_customer_id'] != "" )
			// {
			// 	$this->filterSettings['external_customer_id'] = $this->CustomerProfileData['external_customer_id'];
			// }


			$Wilma 				= Propel::GetConnection();
			$Query 				= "SELECT client_id FROM customer WHERE customer_id = '{$this->customer_id}'";
			$Rs 				= $Wilma->executeQuery($Query);
			while ($Rs->next())
			{
				$this->filterSettings['client_id'] = $Rs->get('client_id');
			}


			// Move up/down the sequence
			if ( $this->getRequestParameter('move') != "" )
			{
				$DetailId 	= $this->getRequestParameter('detail_id');
				//$this->MoveIntelligentMappingDetail($DetailId, $this->getRequestParameter('move'));
				$this->MoveDealerXDetail($DetailId, $this->getRequestParameter('move'));

			}


	
			// Delete the element
			if ( $this->getRequestParameter('doaction'))
			{
				if($this->getRequestParameter('doaction') == 'delete')
				{
					$DetailId 	= $this->getRequestParameter('detail_id');
					$Query 		= "UPDATE dealerx_customer_trigger_detail "
								. "SET active_yn = 'N' "
								. "WHERE dealerx_customer_trigger_detail_id = {$DetailId} "
								. "AND active_yn = 'Y' ";
						//	echo "Query = {$Query}<br />";
					$Rs 		= $Wilma->executeQuery($Query);
				}
			}


			
			// dig out all of the bucket and template info
			$this->filterSettings['buckets'] = array();
			$Query 				= "SELECT * FROM dealerx_customer_trigger "
								. "WHERE customer_id = {$this->customer_id} "
								. "AND active_yn = 'Y' "
								. "ORDER BY name, template_id ";
			$Rs 				= $Wilma->executeQuery($Query);
			while ($Rs->next())
			{
				$this->filterSettings['buckets'][$Rs->get('dealerx_customer_trigger_id')] = $Rs->getRow();
				$this->filterSettings['buckets'][$Rs->get('dealerx_customer_trigger_id')]['details'] = array();
			}

			foreach($this->filterSettings['buckets'] as $DealerXCustomerTriggerId => $Rec)
			{
				$Query 			= "SELECT * FROM dealerx_customer_trigger_detail "
								. "WHERE dealerx_customer_trigger_id = {$DealerXCustomerTriggerId} "
								. "AND active_yn = 'Y' "
								. "ORDER BY sequence_pos_id ";
				$Rs 			= $Wilma->executeQuery($Query);
				while ($Rs->next())
				{
					$Row 		= $Rs->getRow();
					$this->filterSettings['buckets'][$Rs->get('dealerx_customer_trigger_id')]['details'][$Row['sequence_pos_id']] = $Row;
				}
			}


			// append the email status for this cutomer.
			$EmailList 			= array();
			$Query 				= "SELECT product_id, name "
								. "FROM email_template_map, email_layout "
								. "WHERE customer_id = {$this->customer_id} "
								. "AND email_template_map.email_layout_id = email_layout.email_layout_id "
								. "AND active_yn = 'Y' ";
			$Rs 				= $this->dmstrigconn->executeQuery($Query);
			while($Rs->next())
			{
				$EmailList[$Rs->get('product_id')] = $Rs->get('name');
			}

			foreach($this->vehicleFilterData['mail'] as $ProductId => $ProductName)
			{
				$EmailInfo 	= "(email: -- not set -- )";
				if ( isset($EamilList[$ProductId]) )
				{
					$EmailInfo = "(email: {$EmailInfo[$ProductId]})";
				}
				$this->vehicleFilterData['mail'][$ProductId] = $ProductName . " {$EmailInfo}";
			}

			$this->vehicleFilterData['dealerx_template_map'] = array( -1 => '-- Select Mail Format --');
			$Query 				= "SELECT dealerx_template_map_id, name "
								. "FROM dealerx_template_map "
								. "WHERE active_yn = 'Y' "
								. "ORDER BY name ";
			$Rs 				= $Wilma->executeQuery($Query);
			while ($Rs->next())
			{
				$this->vehicleFilterData['dealerx_template_map'][$Rs->get('dealerx_template_map_id')] = $Rs->get('name');
			}





	

			$this->filterSettings['dealerx_mapping_names'] = array('0' => '-- Select Filter --');


			$Query 	= "SELECT * FROM dealerx_trigger_name "
					. "WHERE active_yn = 'Y' "
					. "ORDER BY name ";
			$Rs 	= $Wilma->executeQuery($Query);
			while($Rs->next())
			{
				$Row 	= $Rs->getRow();
				$this->filterSettings['dealerx_mapping_names'][$Row['dealerx_trigger_name_id']] = $Row['name'];
			}

		}

		return true;
	}


	//Build data array to be passed to the partials
	public function LoadForm1()
	{
		if ($this->PageVersion == 2)
		{
			return $this->LoadForm(1);
			die("**");
		}


		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,1, $this->dmstrigconn);

		$this->loadCommon();

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		require_once("TriggerSMVData.php");

		//This file gets existing vehicle filters
		require_once("TriggerSMVehicleFilters.php");

		//Array to pass to vehicle filter partials for populating drop boxes. Will be filled with dummy arrays to start.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["vehicleNotificationTiming"] = $this->vehicleNotificationTiming;
		//$this->vehicleFilterData["vehicleEmail"] = $this->vehicleEmail;
		//$this->vehicleFilterData["couponSelect"] = $this->couponSelect;
		$this->vehicleFilterData["mailSelect"] = $this->mailSelect;
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL2_1);
		//$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON2_1);
				$C->addSelectColumn(TriggerSettingFilterPeer::COUPON1_2);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON2_2);
		//$C->addSelectColumn(TriggerSettingFilterPeer::COUPON3_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_2);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_3);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_4);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_5);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,3);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');

		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$notice = $row["NOTIFICATION_PERIOD"] . " " . ucwords(strtolower($row["NOTIFICATION_PERIOD_TYPE"])) . "s";
		$temp = array_keys($this->vehicleNotificationTiming,$notice);
		$vSettings["defaultNotificationTiming"] = $temp[0];
		$vSettings["defaultReturnReminderMail"] = $row["MAIL1_1"];
		$vSettings["defaultSalesToServiceMail"] = $row["MAIL2_1"];
		$vSettings["email_yn"] = $row["EMAIL_YN"];
		$vSettings["mail_yn"] = $row["MAIL_YN"];
		$vSettings["id"] = $row["TRIGGER_SETTING_FILTER_ID"];
		$vSettings["customer_id"] = $this->customer_id;
		$vSettings["coupon1_1_return_reminder"] = $row["COUPON1_1"];
		$vSettings["coupon1_2_return_reminder"] = $row["COUPON1_2"];
		$vSettings["coupon2_1_service_reminder"] = $row["COUPON2_1"];
		$vSettings["coupon2_2_service_reminder"] = $row["COUPON2_2"];
		$vSettings["coupon2_2_service_reminder"] = $row["COUPON2_2"];
		$vSettings["email_chase_days_1"] = $row["EMAIL_CHASE_DAYS_1"];
		$vSettings["email_chase_days_2"] = $row["EMAIL_CHASE_DAYS_2"];
		$vSettings["email_chase_days_3"] = $row["EMAIL_CHASE_DAYS_3"];
		$vSettings["email_chase_days_4"] = $row["EMAIL_CHASE_DAYS_4"];
		$vSettings["email_chase_days_5"] = $row["EMAIL_CHASE_DAYS_5"];
		$this->vehicleFilterData["defaultFilter"] = $vSettings;

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 3 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}

		$this->filterSettings = array();

		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, 1, $this->dmstrigconn);
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::TIME_MILEAGE_TYPE);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,1);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->filterSettings["TimeAndMileage"] = $row["TIME_MILEAGE_TYPE"];

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::OPCODES);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);

		$C->add(TriggerSettingFilterPeer::FILTER_ID,2);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->filterSettings["OilChangeOpCodes"] = $row["OPCODES"];
	}


	public function LoadForm2()
	{
		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,2, $this->dmstrigconn);

		$this->loadCommon();

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		require_once("TriggerACVData.php");
		//This file gets existing vehicle filters
		include("TriggerACVehicleFilters.php");

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["vehicleEmail"] = $this->mailSelect;
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,5);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$vSettings["defaultNotificationTiming"] = $row["NOTIFICATION_PERIOD"];
		$vSettings["defaultVehicleEmail"] = $row["EMAIL_1"];
		$vSettings["defaultVehicleEnabled"] = $row["ENABLED_YN"];
		$vSettings["customer_id"] = $this->customer_id;
		$this->vehicleFilterData["defaultFilter"] = $vSettings;

		$this->filterSettings = array();

	}


	public function loadForm3()
	{
		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,3, $this->dmstrigconn);

		$this->loadCommon();

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		require_once("TriggerBVData.php");
		//This file gets existing vehicle filters
		include("TriggerBVehicleFilters.php");

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::PARTS_RECALL_DAYS);
		$C->addSelectColumn(TriggerSettingFilterPeer::PARTS_AFTER_SECOND_CALL);
		$C->addSelectColumn(TriggerSettingFilterPeer::PARTS_FILTER_PART_CODES);
		$C->addSelectColumn(TriggerSettingFilterPeer::PARTS_CALL_RO_OPCODE);
		$C->addSelectColumn(TriggerSettingFilterPeer::PARTS_FILTER_COUNTERMEN);
		$C->addSelectColumn(TriggerSettingFilterPeer::PARTS_FILTER_CUSTOMERS);
		$C->addSelectColumn(TriggerSettingFilterPeer::PARTS_SPECIAL_ORDER_RETURN_DAYS);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,6);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$temp = array();
		$temp["parts_recall_days"] = $row["PARTS_RECALL_DAYS"];
		$temp["parts_after_second_call"] = $row["PARTS_AFTER_SECOND_CALL"];
		$temp["parts_filter_part_codes"] = $row["PARTS_FILTER_PART_CODES"];
		$temp["parts_call_ro_opcode"] = $row["PARTS_CALL_RO_OPCODE"];
		$temp["parts_filter_countermen"] = $row["PARTS_FILTER_COUNTERMEN"];
		$temp["parts_filter_customers"] = $row["PARTS_FILTER_CUSTOMERS"];
		$temp["parts_special_order_return_days"] = $row["PARTS_SPECIAL_ORDER_RETURN_DAYS"];
		$this->filterSettings["AdditionalParts"] = $temp;

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,7);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$vSettings["defaultEnabled"] = $row["ENABLED_YN"];
		$vSettings["defaultReturnReminderMail"] = $row["MAIL1_1"];
		$vSettings["customer_id"] = $this->customer_id;
		$this->vehicleFilterData["defaultFilter"] = $vSettings;

		$this->filterSettings = array();

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 7 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}

	}


	public function loadForm5()
	{
		if ($this->PageVersion == 2)
		{
			return $this->LoadForm(5);
			die("**");
		}

		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,5, $this->dmstrigconn);

		$this->loadCommon();

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerCBVData.php";

		//This file gets existing vehicle filters
		include("TriggerCBVehicleFilters.php");

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["vehicleEmail"] = $this->vehicleEmail;
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		$this->vehicleFilterData["couponSelect"] = $this->couponSelect;
		$this->vehicleFilterData["mailSelect"] = $this->mailSelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON2_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON3_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_2);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_3);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_4);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_5);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,26);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$vSettings["defaultReturnReminderMail"] = $row["MAIL1_1"];
		if ($row["ENABLED_YN"] == "Y") $vSettings["defaultEnabled"] = 1;
		else $vSettings["defaultEnabled"] = 0;
		$vSettings["customer_id"] = $this->customer_id;
     	$vSettings['mail_yn'] = $row["MAIL_YN"];
		$vSettings['email_yn'] = $row["EMAIL_YN"];
		$vSettings['id'] = intval($row["TRIGGER_SETTING_FILTER_ID"]);
		$vSettings["email_chase_days_1"] = $row["EMAIL_CHASE_DAYS_1"];
		$vSettings["email_chase_days_2"] = $row["EMAIL_CHASE_DAYS_2"];
		$vSettings["email_chase_days_3"] = $row["EMAIL_CHASE_DAYS_3"];
		$vSettings["email_chase_days_4"] = $row["EMAIL_CHASE_DAYS_4"];
		$vSettings["email_chase_days_5"] = $row["EMAIL_CHASE_DAYS_5"];

		$this->vehicleFilterData["defaultFilter"] = $vSettings;

		$this->filterSettings = array();

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 26 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	public function loadForm6()
	{
		if ($this->PageVersion == 2)
		{
			return $this->LoadForm(6);
			die("**");
		}

		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,6, $this->dmstrigconn);
		$this->form = 6;

		$this->loadMakes();
		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerFUVData.php";

		//This file gets existing vehicle filters
		include "TriggerFUVehicleFilters.php";

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		$this->vehicleFilterData["delay"] = $this->delaySelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,15);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();

		if ($row['NOTIFICATION_PERIOD'] == -1 && $row['NOTIFICATION_PERIOD_TYPE'] == "HOUR")
		$temp1["delay"] = "Never";
		elseif ($row['NOTIFICATION_PERIOD'] == 0 && $row['NOTIFICATION_PERIOD_TYPE'] == "HOUR")
		$temp1["delay"] = "No Delay";
		else
		{
			$temp1["delay"] = $row['NOTIFICATION_PERIOD'] . " " . ucwords(strtolower($row['NOTIFICATION_PERIOD_TYPE']));
			if ($row['NOTIFICATION_PERIOD'] > 1) $temp1["delay"] .= "s";
		}

		$temp = array_keys($this->delaySelect,$temp1["delay"]);
		$vSettings["delay"] = $temp[0];
		$vSettings["mail"] = $row["MAIL1_1"];
		$vSettings["customer_id"] = $this->customer_id;
		$vSettings["mail_yn"] = $row["MAIL_YN"];
		$vSettings["email_yn"] = $row["EMAIL_YN"];
		$vSettings['id'] = $row["TRIGGER_SETTING_FILTER_ID"];
		$vSettings["email_chase_days_1"] = $row["EMAIL_CHASE_DAYS_1"];
		$vSettings["email_chase_days_2"] = $row["EMAIL_CHASE_DAYS_2"];
		$vSettings["email_chase_days_3"] = $row["EMAIL_CHASE_DAYS_3"];
		$vSettings["email_chase_days_4"] = $row["EMAIL_CHASE_DAYS_4"];
		$vSettings["email_chase_days_5"] = $row["EMAIL_CHASE_DAYS_5"];
		$this->surveyQuestions = unserialize($row["PARTS_FILTER_CUSTOMERS"]);
		//$vSettings["email"] = $row["EMAIL_1"];
		$this->vehicleFilterData["defaultFilter"] = $vSettings;

		$this->filterSettings = array();

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_CUST_PROMPT_ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_CUST_PROMPT_GREETING);
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_CUST_PROMPT_VOICEMAIL);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,11);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->temp = array();
		if ($row["FOLLOWUP_CUST_PROMPT_ENABLED_YN"] == "Y")
		{
			$this->temp["enablecustom"] = true;
			$this->temp["greetingprompt"] = $row["FOLLOWUP_CUST_PROMPT_GREETING"];
			$this->temp["voiceprompt"] = $row["FOLLOWUP_CUST_PROMPT_VOICEMAIL"];
		}
		else $this->temp["enablecustom"] = false;
		$this->filterSettings["FollowUpCustomGreetingPrompt"] = $this->temp;

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_SETTINGS_CONTACT);
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_SETTINGS_CUST_PAY);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,13);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->temp = array();
		if ($row["FOLLOWUP_SETTINGS_CONTACT"] == "Y")
		$this->temp["contactadvisor"] = true;
		else $this->temp["contactadvisor"] = false;
		if ($row["FOLLOWUP_SETTINGS_CUST_PAY"] == "Y")
		$this->temp["custpay"] = true;
		else $this->temp["custpay"] = false;
		$this->filterSettings["FollowUpSettings"] = $this->temp;

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_21DAY_ENABLE_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_21DAY_PICKUP_MESSAGE);
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_21DAY_MESSAGE_VOICEMAIL);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,14);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->temp = array();
		if ($row["FOLLOWUP_21DAY_ENABLE_YN"] == "Y")
		{
			$this->temp["active"] = true;
			$this->temp["answermsg"] = $row["FOLLOWUP_21DAY_PICKUP_MESSAGE"];
			$this->temp["voicemailmsg"] = $row["FOLLOWUP_21DAY_MESSAGE_VOICEMAIL"];
		}
		else $this->temp["active"] = false;
		$this->filterSettings["21DayFollowUp"] = $this->temp;

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 15 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}

		//$this->surveyQuestions = $this->getFollowupCalltypeQuestions();
		if (!is_array($this->surveyQuestions)) { $this->surveyQuestions = TriggerSettingFilterPeer::getDefaultSurveyMessages("easycare"); }
 		$this->vehicleFilterData["defaultFilter"]["customer_id"] = $this->customer_id;
		$this->theform = 6;

	}


	public function loadForm7()
	{
		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,7, $this->dmstrigconn);

		$C = new Criteria();
		$C->addSelectColumn(ChromeMakePeer::MAKE);
		$C->addAscendingOrderByColumn(ChromeMakePeer::MAKE);
		$makedrop = ChromeMakePeer::doSelectRs($C);
		$makedrop->setFetchMode( ResultSet::FETCHMODE_ASSOC );

		$this->makedrop = array();
		$this->makedrop["DEFAULT"] = "Default";
		while ($makedrop->next())
		{
			$row = $makedrop->getRow();
			$this->makedrop[$row['MAKE']] = $row['MAKE'];
		}

		//This file holds the arrays used to populate the Declined repairs vehicle filter dropdowns
		include "TriggerDRVData.php";
		//This file gets existing vehicle filters
		include "TriggerDRVehicleFilters.php";

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		$this->vehicleFilterData["delay"] = $this->delaySelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;
		$this->vehicleFilterData["defaultFilter"]["customer_id"] = $this->customer_id;

		$this->filterSettings = array();

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::ASR_PRO_ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::ASR_RED_REQUIRED_YN);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,16);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->temp = array();
		if ($row["ASR_PRO_ENABLED_YN"] == "Y")
		$this->temp["asrenabled"] = true;
		else $this->temp["asrenabled"] = false;
		if ($row["ASR_RED_REQUIRED_YN"] == "Y")
		$this->temp["requireasr"] = true;
		else $this->temp["requireasr"] = false;
		$this->filterSettings["AsrProIntegration"] = $this->temp;

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_INCLUDE);
		$C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_EXCLUDE);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,27);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->temp = array();
		$this->temp["includemakes"] = $row["VEHICLE_MAKES_INCLUDE"];
		$this->temp["excludemakes"] = $row["VEHICLE_MAKES_EXCLUDE"];
		$this->filterSettings["MakeIncludeExclude"] = $this->temp;

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::RECOMMENDATIONS_ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::RECOMMENDATIONS_AFTER_DATE);
		$C->addSelectColumn(TriggerSettingFilterPeer::RECOMMENDATIONS_INCLUDE_TEXT);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,17);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->temp = array();
		if ($row["RECOMMENDATIONS_ENABLED_YN"] == "Y")
		$this->temp["processrecommends"] = true;
		else $this->temp["processrecommends"] = false;
		$this->temp["emailrecommends"] = $row["RECOMMENDATIONS_INCLUDE_TEXT"];
		$this->temp["donotprocessbefore"] = date('n/j/y',strtotime($row["RECOMMENDATIONS_AFTER_DATE"]));
		$this->filterSettings["Recommendations"] = $this->temp;

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 18 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	public function loadForm8()
	{
		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,8, $this->dmstrigconn);

		$C = new Criteria();
		$C->addSelectColumn(ChromeMakePeer::MAKE);
		$C->addAscendingOrderByColumn(ChromeMakePeer::MAKE);
		$makedrop = ChromeMakePeer::doSelectRs($C);
		$makedrop->setFetchMode( ResultSet::FETCHMODE_ASSOC );

		$this->makedrop = array();
		$this->makedrop['DEFAULT'] = "Default Settings";
		while ($makedrop->next())
		{
			$row = $makedrop->getRow();
			$this->makedrop[$row['MAKE']] = $row['MAKE'];
		}

		//This file holds the arrays used to populate the Customer recovery vehicle filter dropdowns
		include "TriggerCRVData.php";
		//This file gets existing vehicle filters
		include "TriggerCRVehicleFilters.php";

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		$this->vehicleFilterData["email"] = $this->vehicleEmail;
		$this->vehicleFilterData["coupon"] = $this->couponSelect;
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		$this->vehicleFilterData["months"] = $this->months;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;
		$this->vehicleFilterData["defaultFilter"]["customer_id"] = $this->customer_id;

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::RECOVERY_STATE_ONLY);
		$C->addSelectColumn(TriggerSettingFilterPeer::RECOVERY_OLDEST_YEAR);
		$C->addSelectColumn(TriggerSettingFilterPeer::RECOVERY_MAX_MONTHS);
		$C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_INCLUDE);
		$C->addSelectColumn(TriggerSettingFilterPeer::VEHICLE_MAKES_EXCLUDE);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,19);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->filterSettings = array();
		$this->temp = array();
		if ($row["RECOVERY_STATE_ONLY"] == "Y")
		$this->temp["instate"] = true;
		else $this->temp["instate"] = false;
		$this->temp["oldestyear"] = $row["RECOVERY_OLDEST_YEAR"];
		$this->temp["maxmonths"] = $row["RECOVERY_MAX_MONTHS"];
		$this->temp["includemakes"] = $row["VEHICLE_MAKES_INCLUDE"];
		$this->temp["excludemakes"] = $row["VEHICLE_MAKES_EXCLUDE"];
		$this->filterSettings["Recovery"] = $this->temp;

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 19 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	public function loadForm9()
	{
		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,9, $this->dmstrigconn);

		$this->inspections = array('- Select -','Alaska Emissions Inspection','Arizona Emissions Inspection','California Emissions Inspection','Colorado Emissions Inspection','Connecticut Emissions Inspection','Delaware Safety Inspection','District of Columbia Safety Inspection','Georgia Emissions Inspection','Hawaii Safety Inspection','Illinois Emissions Inspection','Indiana Emissions Inspection','Louisiana Safety Inspection','Maine Safety Inspection','Massachusetts Safety Inspection','Mississippi Safety Inspection','Missouri Safety Inspection','Nevada Emissions Inspection','New Hampshire Safety Inspection','New Jersey Safety Inspection','New Mexico Emissions Inspection','New York Safety Inspection','North Carolina Inspection (Safety and Emissions)','Ohio Emissions Inspection','Oregon Emissions Inspection','Pennsylvania Safety Inspection','Rhode Island Safety Inspection','Texas Safety Inspection','Utah Safety Inspection','Vermont Safety Inspection','Virginia Safety Inspection','Washington Emissions Inspection','West Virginia Safety Inspection','Wisconsin Emissions Inspection');

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->filterSettings = array();
		$this->filterSettings["StateInspection"]["inspections"] = $this->inspections;

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::STATE_INSPECTION_REQUIRED);
		$C->addSelectColumn(TriggerSettingFilterPeer::OPCODES);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,21);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$temp = array_keys($this->inspections,$row['STATE_INSPECTION_REQUIRED']);
		$this->filterSettings["StateInspection"]["inspection"] = $temp[0];
		$this->filterSettings["StateInspection"]["opcodes"] = $row["OPCODES"];

		$this->loadMakes();

		//This file holds the arrays used to populate the State Inspection vehicle filter dropdowns
		include "TriggerSIVData.php";
		//This file gets existing vehicle filters
		include "TriggerSIVehicleFilters.php";

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_2);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_3);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_4);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_5);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,22);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();

		$row = $filterrs->getRow();

		$temp = array_keys($this->delaySelect,$row['NOTIFICATION_PERIOD'] . " Days");
		$vSettings["delay"] = $temp[0];
		$vSettings["mail"] = $row["MAIL1_1"];
		$vSettings['mail_yn'] = $row["MAIL_YN"];
		$vSettings['email_yn'] = $row["EMAIL_YN"];
		$vSettings['id'] = intval($row["TRIGGER_SETTING_FILTER_ID"]);
		$vSettings["email_chase_days_1"] = $row["EMAIL_CHASE_DAYS_1"];
		$vSettings["email_chase_days_2"] = $row["EMAIL_CHASE_DAYS_2"];
		$vSettings["email_chase_days_3"] = $row["EMAIL_CHASE_DAYS_3"];
		$vSettings["email_chase_days_4"] = $row["EMAIL_CHASE_DAYS_4"];
		$vSettings["email_chase_days_5"] = $row["EMAIL_CHASE_DAYS_5"];

		if ($row["ENABLED_YN"] == "Y") $vSettings["defaultenabled"] = 1;
		else $vSettings["defaultenabled"] = 0;

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		//$this->vehicleFilterData["email"] = $this->vehicleEmail;
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		$this->vehicleFilterData["delay"] = $this->delaySelect;
		//$this->vehicleFilterData["coupon"] = $this->couponSelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;
		$this->vehicleFilterData["defaultFilter"] = $vSettings;
		$this->vehicleFilterData["defaultFilter"]["customer_id"] = $this->customer_id;

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 22 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	public function loadForm12()
	{
		if ($this->PageVersion == 2)
		{
			return $this->LoadForm(12);
			die("**");
		}

		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,12, $this->dmstrigconn);

		$this->loadMakes();

		include "TriggerPFVData.php";
		include "TriggerPFVehicleFilters.php";

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		//$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD_TYPE);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_YN);
        $C->addSelectColumn(TriggerSettingFilterPeer::MAIL_YN);
        $C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_2);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_3);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_4);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_5);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,15);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();

		if ($row['NOTIFICATION_PERIOD'] == -1 && $row['NOTIFICATION_PERIOD_TYPE'] == "HOUR")
		$temp1["delay"] = "Never";
		elseif ($row['NOTIFICATION_PERIOD'] == 0 && $row['NOTIFICATION_PERIOD_TYPE'] == "HOUR")
		$temp1["delay"] = "No Delay";
		else
		{
			$temp1["delay"] = $row['NOTIFICATION_PERIOD'] . " " . ucwords(strtolower($row['NOTIFICATION_PERIOD_TYPE']));
			if ($row['NOTIFICATION_PERIOD'] > 1) $temp1["delay"] .= "s";
		}

		$temp = array_keys($this->delaySelect,$temp1["delay"]);
		$vSettings["delay"] = $temp[0];
		$vSettings["mail"] = $row["MAIL1_1"];
		//$vSettings["email"] = $row["EMAIL_1"];
		$vSettings['id'] = intval($row["TRIGGER_SETTING_FILTER_ID"]);
		$vSettings['mail_yn'] = $row["MAIL_YN"];
		$vSettings['email_yn'] = $row["EMAIL_YN"];
		$vSettings["email_chase_days_1"] = $row["EMAIL_CHASE_DAYS_1"];
		$vSettings["email_chase_days_2"] = $row["EMAIL_CHASE_DAYS_2"];
		$vSettings["email_chase_days_3"] = $row["EMAIL_CHASE_DAYS_3"];
		$vSettings["email_chase_days_4"] = $row["EMAIL_CHASE_DAYS_4"];
		$vSettings["email_chase_days_5"] = $row["EMAIL_CHASE_DAYS_5"];

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		//$this->vehicleFilterData["email"] = $this->vehicleEmail;
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		$this->vehicleFilterData["delay"] = $this->delaySelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;
		$this->vehicleFilterData["defaultFilter"] = $vSettings;
		$this->vehicleFilterData["defaultFilter"]["customer_id"] = $this->customer_id;

		$this->filterSettings = array();

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_CUST_PROMPT_ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_CUST_PROMPT_GREETING);
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_CUST_PROMPT_VOICEMAIL);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,11);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->temp = array();
		if ($row["FOLLOWUP_CUST_PROMPT_ENABLED_YN"] == "Y")
		{
			$this->temp["enablecustom"] = true;
			$this->temp["greetingprompt"] = $row["FOLLOWUP_CUST_PROMPT_GREETING"];
			$this->temp["voiceprompt"] = $row["FOLLOWUP_CUST_PROMPT_VOICEMAIL"];
		}
		else $this->temp["enablecustom"] = false;
		$this->filterSettings["FollowUpCustomGreetingPrompt"] = $this->temp;

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::FOLLOWUP_VEHICLE_TYPE);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,28);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$this->filterSettings["SalesVehicleType"] = $row["FOLLOWUP_VEHICLE_TYPE"];

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 15 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
		$this->theform = 12;
	}


	public function loadForm14()
	{
		$TriggerSettingId 	= TriggerSettingPeer::GetSettingId($this->customer_id,14, $this->dmstrigconn);
		$TriggerLevel		= intval($this->getRequestParameter('level'));
		if (!$TriggerLevel) $TriggerLevel = 1;
		$this->TriggerLevel = $TriggerLevel;


		$this->loadMakes();

		include "TriggerLEVData.php";
		include "TriggerLEVehicleFilters.php";

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_2);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_3);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_4);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_5);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,24);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$C->add(TriggerSettingFilterPeer::LEVEL, $TriggerLevel);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();

		$vSettings["delay"] =$row['NOTIFICATION_PERIOD'] - 1;
		$vSettings["mail"] = $row["MAIL1_1"];
		$vSettings["id"] = $row['TRIGGER_SETTING_FILTER_ID'];
        $vSettings["mail_yn"] = $row['MAIL_YN'];
	    $vSettings["email_yn"] = $row['EMAIL_YN'];
		$vSettings["email_chase_days_1"] = $row["EMAIL_CHASE_DAYS_1"];
		$vSettings["email_chase_days_2"] = $row["EMAIL_CHASE_DAYS_2"];
		$vSettings["email_chase_days_3"] = $row["EMAIL_CHASE_DAYS_3"];
		$vSettings["email_chase_days_4"] = $row["EMAIL_CHASE_DAYS_4"];
		$vSettings["email_chase_days_5"] = $row["EMAIL_CHASE_DAYS_5"];

		//$vSettings["email"] = $row["EMAIL_1"];
		if ($row["ENABLED_YN"] == "Y") $vSettings["defaultenabled"] = 1;
		else $vSettings["defaultenabled"] = 0;

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		//$this->vehicleFilterData["email"] = $this->vehicleEmail;
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;
		$this->vehicleFilterData["defaultFilter"] = $vSettings;
		$this->vehicleFilterData["defaultFilter"]["customer_id"] = $this->customer_id;

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 24 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	public function loadForm15()
	{
		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,15, $this->dmstrigconn);

		$this->loadMakes();

		include "TriggerWNVData.php";
		include "TriggerWNVehicleFilters.php";

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);

		//$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_2);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_3);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_4);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_5);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,29);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');

		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();

		$vSettings["mail"] = $row["MAIL1_1"];
		//$vSettings["email"] = $row["EMAIL_1"];
		if ($row["ENABLED_YN"] == "Y") $vSettings["defaultenabled"] = 1;
		else $vSettings["defaultenabled"] = 0;

		$vSettings["monthNotification"] =$row['NOTIFICATION_PERIOD'];
		$vSettings["id"] = $row["TRIGGER_SETTING_FILTER_ID"];
		$vSettings["mail_yn"] = $row["MAIL_YN"];
		$vSettings["email_yn"] = $row["EMAIL_YN"];
		$vSettings["email_chase_days_1"] = $row["EMAIL_CHASE_DAYS_1"];
		$vSettings["email_chase_days_2"] = $row["EMAIL_CHASE_DAYS_2"];
		$vSettings["email_chase_days_3"] = $row["EMAIL_CHASE_DAYS_3"];
		$vSettings["email_chase_days_4"] = $row["EMAIL_CHASE_DAYS_4"];
		$vSettings["email_chase_days_5"] = $row["EMAIL_CHASE_DAYS_5"];

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
		$C->addSelectColumn(TriggerSettingFilterPeer::WARRANTY_EXPIRATION_MILEAGE_ZERO_YN);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,23);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$vSettings["mileageNotification"] =$row['NOTIFICATION_PERIOD'];
		if ($row["WARRANTY_EXPIRATION_MILEAGE_ZERO_YN"] == "Y") $vSettings["warrantymileage"] = 1;
		else $vSettings["warrantymileage"] = 0;

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		//$this->vehicleFilterData["email"] = $this->vehicleEmail;
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		//$this->vehicleFilterData["delay"] = $this->delaySelect;
		$this->vehicleFilterData["monthNotification"] = $this->delaySelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;
		$this->vehicleFilterData["defaultFilter"] = $vSettings;
		$this->vehicleFilterData["monthNotification"] = $this->monthNotification;
		$this->vehicleFilterData["mileageNotification"] = $this->mileageNotification;
		$this->vehicleFilterData["defaultFilter"]["customer_id"] = $this->customer_id;

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 29 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	public function loadForm18()
	{
		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,18, $this->dmstrigconn);

		$this->loadCommon();

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerMAVData.php";

		//This file gets existing vehicle filters
		include("TriggerMAVehicleFilters.php");

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["vehicleEmail"] = $this->vehicleEmail;
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		$this->vehicleFilterData["couponSelect"] = $this->couponSelect;
		$this->vehicleFilterData["mailSelect"] = $this->mailSelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON2_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);

		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON3_1);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,30);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$vSettings["defaultReturnReminderMail"] = $row["MAIL1_1"];
		if ($row["ENABLED_YN"] == "Y") $vSettings["defaultEnabled"] = 1;
		else $vSettings["defaultEnabled"] = 0;
		$vSettings["customer_id"] = $this->customer_id;
		$vSettings["id"] = $row["TRIGGER_SETTING_FILTER_ID"];
		$vSettings["mail_yn"] = $row["MAIL_YN"];
		$vSettings["email_yn"] = $row["EMAIL_YN"];
		$this->vehicleFilterData["defaultFilter"] = $vSettings;

		$this->filterSettings = array();

		$sql = "
				SELECT		change_date,
							user_id
				FROM		trigger_setting_log
				WHERE		customer_id = " . $this->customer_id . " AND
							trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND
							trigger_filter_id = 30
				ORDER BY	change_date DESC
				LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	public function loadForm19()
	{
		$TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,19, $this->dmstrigconn);

		$this->loadCommon();

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerPAVData.php";

		//This file gets existing vehicle filters
		include("TriggerPAVehicleFilters.php");

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["vehicleEmail"] = $this->vehicleEmail;
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		$this->vehicleFilterData["couponSelect"] = $this->couponSelect;
		$this->vehicleFilterData["mailSelect"] = $this->mailSelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON2_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::COUPON3_1);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,31);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();
		$vSettings["defaultReturnReminderMail"] = $row["MAIL1_1"];
		if ($row["ENABLED_YN"] == "Y") $vSettings["defaultEnabled"] = 1;
		else $vSettings["defaultEnabled"] = 0;
		$vSettings["customer_id"] = $this->customer_id;
		$this->vehicleFilterData["defaultFilter"] = $vSettings;

		$this->filterSettings = array();

		$sql = "
				SELECT		change_date,
							user_id
				FROM		trigger_setting_log
				WHERE		customer_id = " . $this->customer_id . " AND
							trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND
							trigger_filter_id = 31
				ORDER BY	change_date DESC
				LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	/**
	*
	******************************************************************************************/
	public function GetTriggerBrandLevels($TriggerId, $TriggerSettingId)
	{
		$VehicleFilterId	= TriggerSettingFilterPeer::GetTriggerVehicleFilterId($TriggerId,$this->dmstrigconn);

		$result = array();

		// New HVAC triggers
		if (in_array($TriggerId, array(HVAC_THANK_YOU, HVAC_SERVICE_REMINDER, HVAC_PRE_RENEWAL, HVAC_SERVICE_CONTRACT_EXPIRATION))) {
			$C = new Criteria;
			$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
			$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
			$C->addSelectColumn(TriggerSettingFilterPeer::LEVEL);
			$C->addSelectColumn(TriggerSettingFilterPeer::SETTING_1);
			$C->addAnd(TriggerSettingFilterPeer::TRIGGER_SETTING_ID, $TriggerSettingId);
			$C->addAnd(TriggerSettingFilterPeer::ACTIVE_YN, 'Y');
			$C->addAnd(TriggerSettingFilterPeer::BRAND, NULL, Criteria::ISNOTNULL);
			$C->addAnd(TriggerSettingFilterPeer::FILTER_ID, $VehicleFilterId);
			$Rs = TriggerSettingFilterPeer::doSelectRs($C, $this->dmstrigconn);

			while ($Rs->next()) {
				$brand 			= $Rs->get(1) ? strtoupper($Rs->get(1)) : 'DEFAULT';
				$enabled		= strtoupper($Rs->get(2))=='Y' ? 1 : 0;
				$level			= $Rs->get(3);
				$contract		= $Rs->get(4) ? strtoupper($Rs->get(4)) : 'DEFAULT';

				$result[$brand][$contract]['brand']				= $brand;
				$result[$brand][$contract]['contract']			= $contract;
				$result[$brand][$contract]['enabled']			+= $enabled;
				$result[$brand][$contract]['levels'][$level]	= $enabled;
			}
		} else {
			$C = new Criteria;
			$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
			$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
			$C->addSelectColumn(TriggerSettingFilterPeer::LEVEL);
			$C->addAnd(TriggerSettingFilterPeer::TRIGGER_SETTING_ID, $TriggerSettingId);
			$C->addAnd(TriggerSettingFilterPeer::ACTIVE_YN, 'Y');
			$C->addAnd(TriggerSettingFilterPeer::BRAND, NULL, Criteria::ISNOTNULL);
			$C->addAnd(TriggerSettingFilterPeer::FILTER_ID, $VehicleFilterId);
			$Rs = TriggerSettingFilterPeer::doSelectRs($C, $this->dmstrigconn);

			while ($Rs->next()) {
				$brand 			= $Rs->get(1) ? strtoupper($Rs->get(1)) : 'DEFAULT';
				$enabled		= strtoupper($Rs->get(2))=='Y' ? 1 : 0;
				$level			= $Rs->get(3);

				$result[$brand]['brand'] 	= $brand;
				$result[$brand]['enabled'] += $enabled;
				$result[$brand]['levels'][$level] = $enabled;
			}
		}

		return $result;
	}


	/***
	`*
	`* Get Trigger Overview Stats
	`*
	`************************************************************************************************/
	public function GetOverviewStats($CustomerId, $TriggerNameId)
	{
		$Dms 	= new Dms($CustomerId);
		$Result	= array();

		switch($TriggerNameId) {
			case BANKRUPTCY_RECOVERY:
				$Result = array(
					'Bankruptcy Consumers'	=> $Dms->GetConquestConsumerCount('B'),
					'On 1st Notice'			=> $Dms->GetConquestConsumerCount('B', 1),
					'On 2nd Notice'			=> $Dms->GetConquestConsumerCount('B', 2),
					'On 3rd Notice'			=> $Dms->GetConquestConsumerCount('B', 3),
				);
			break;
			case CUSTOMER_RECOVERY:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Sales'			=> $Dms->GetTotalDealCount(),
					'Services'		=> $Dms->GetTotalServiceCount(),
				);
			break;
			case DECLINED_REPAIRS:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Services'		=> $Dms->GetTotalServiceCount(),
				);
			break;
			case SCHEDULED_MAINTENANCE:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Sales'			=> $Dms->GetTotalDealCount(),
					'Services'		=> $Dms->GetTotalServiceCount(),
				);
			break;
			case STATE_INSPECTION_REMINDER:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Sales'			=> $Dms->GetTotalDealCount(),
					'Services'		=> $Dms->GetTotalServiceCount(),
				);
			break;
			case CUSTOMER_BIRTHDAY:
				$birthdays 	= $Dms->GetConsumerBirthdayMonthCount();
				$Result 	= array(
					'Consumers'				=> $Dms->GetCountConsumers(true),
					'Consumers w/Birthday'	=> $Dms->GetCountConsumers(true, false, array('birthday')),
					'January'				=> $birthdays[1],
					'February'				=> $birthdays[2],
					'March'					=> $birthdays[3],
					'April'					=> $birthdays[4],
					'May'					=> $birthdays[5],
					'June'					=> $birthdays[6],
					'July'					=> $birthdays[7],
					'August'				=> $birthdays[8],
					'September'				=> $birthdays[9],
					'October'				=> $birthdays[10],
					'November'				=> $birthdays[11],
					'December'				=> $birthdays[12],
				);
			break;
			case SERVICE_FOLLOW_UP:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Services'		=> $Dms->GetTotalServiceCount(),
				);
			break;
			case PURCHASE_FOLLOW_UP:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Cash'			=> $Dms->GetTotalDealCount('CASH'),
					'Loans'			=> $Dms->GetTotalDealCount('LOAN')
				);
			break;
			case TRADE_CYCLE:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Cash'			=> $Dms->GetTotalDealCount('CASH'),
					'Loans'			=> $Dms->GetTotalDealCount('LOAN'),
					'Expired Loans'	=> $Dms->GetTotalLoanFinalPaymentCountByDate(date('Y-m-d'), 'BEFORE'),
					'Active Loans'	=> $Dms->GetTotalLoanFinalPaymentCountByDate(date('Y-m-d'), 'AFTER'),
				);
			break;
			case EQUITY_TRIGGER:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Cash'			=> $Dms->GetTotalDealCount('CASH'),
					'Loans'			=> $Dms->GetTotalDealCount('LOAN'),
					'Expired Loans'	=> $Dms->GetTotalLoanFinalPaymentCountByDate(date('Y-m-d'), 'BEFORE'),
					'Active Loans'	=> $Dms->GetTotalLoanFinalPaymentCountByDate(date('Y-m-d'), 'AFTER'),
					'Vehicle Equity > $0'	=> $Dms->GetVehicleEquityCountByValue(0, 'GREATER'),
					'Vehicle Equity < $0'	=> $Dms->GetVehicleEquityCountByValue(0, 'LESS'),
				);
			break;
			case VEHICLE_ANNIVERSARY:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Cash'			=> $Dms->GetTotalDealCount('CASH'),
					'Loans'			=> $Dms->GetTotalDealCount('LOAN'),
					'New'			=> $Dms->GetDealNewUseCount(array('CASH','LOAN'), 'NEW'),
					'Used'			=> $Dms->GetDealNewUseCount(array('CASH','LOAN'), 'USED'),
				);
			break;
			case EXPIRING_LEASE_CUSTOMERS:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Lease'			=> $Dms->GetTotalDealCount('LEASE'),
					'New'			=> $Dms->GetDealNewUseCount(array('LEASE'), 'NEW'),
					'Used'			=> $Dms->GetDealNewUseCount(array('LEASE'), 'USED'),
				);
			break;
			case SERVICE_TO_SALES:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Sales'			=> $Dms->GetTotalDealCount(),
					'Services'		=> $Dms->GetTotalServiceCount(),
				);
			break;
			case WARRANTY_NOTIFICATION:
				$Result = array(
					'Consumers'			=> $Dms->GetCountConsumers(true),
					'Warranty Records'	=> $Dms->GetTotalWarrantySummaryCount(),
				);
			break;
			case LOAN_RATE_TRIGGER:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Sales'			=> $Dms->GetTotalDealCount(),
					'New'			=> $Dms->GetDealNewUseCount(array('LOAN'), 'NEW'),
					'Used'			=> $Dms->GetDealNewUseCount(array('LOAN'), 'USED'),
				);
			break;
			case SERVICE_CONTRACT_FOLLOW_UP:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Sales'			=> $Dms->GetTotalDealCount(),
					'New'			=> $Dms->GetDealNewUseCount(array('CASH','LOAN','UNKNOWN'), 'NEW'),
					'Used'			=> $Dms->GetDealNewUseCount(array('CASH','LOAN','UNKNOWN'), 'USED'),
				);
			break;
			case HIJACK:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Sales'			=> $Dms->GetTotalDealCount(),
					'New'			=> $Dms->GetDealNewUseCount(array('LOAN'), 'NEW'),
					'Used'			=> $Dms->GetDealNewUseCount(array('LOAN'), 'USED'),
				);
			break;
			case INMARKET_SHOPPER:
				$Result = array(
					'Consumers'		=> $Dms->GetCountConsumers(true),
					'Sales'			=> $Dms->GetTotalDealCount(),
					'New'			=> $Dms->GetDealNewUseCount(array('LOAN'), 'NEW'),
					'Used'			=> $Dms->GetDealNewUseCount(array('LOAN'), 'USED'),
				);
			break;
			case HVAC_CUSTOMER_RECOVERY:
				$Result = array(
					'Consumers'		=> $Dms->GetCountHvacEventConsumers(),
					'Sales'			=> $Dms->GetCountHvacEvents(array('Sales')),
					'Service'		=> $Dms->GetCountHvacEvents(array('Service')),
					'Maintenance'	=> $Dms->GetCountHvacEvents(array('Maintenance')),
				);
			break;
			case HVAC_DECLINED_SERVICES:
				$Result = array(

				);
			break;
			case HVAC_ANNUAL_MAINTENANCE:
				$Result = array(
					'Maintenance'	=> $Dms->GetCountHvacEvents(array('Maintenance')),
				);
			break;
			case HVAC_SERVICE_CONTRACT:
				$Result = array(

				);
			break;
			case HVAC_SERVICE_RENEWAL:
				$Result = array(
					'Active Contracts'	=> $Dms->GetCountContracts(true),
					'Expired Contracts'	=> $Dms->GetCountContracts(false),
				);
			break;
			case HVAC_APPOINTMENT_CONFIRMATION:
				$Result = array(
					'Appointments'	=> $Dms->GetCountFutureHvacAppointments(),
				);
			break;
			case HVAC_SALES_FOLLOWUP:
				$Result = array(
					'Sales'			=> $Dms->GetCountHvacEvents(array('Sales')),
				);
			break;
			case HVAC_DECLINED_PURCHASE:
				$Result = array(

				);
			break;
			case HVAC_RADIUS_MARKETING:
				$Result = array(

				);
			break;
			case HVAC_THANK_YOU:
				$Result = array(
					'Consumers'			=> $Dms->GetCountHvacConsumers(),
					'Active Contracts'	=> $Dms->GetCountHvacContracts(),
					'Expired Contracts'	=> $Dms->GetCountHvacContracts(true)
				);
			break;
			case HVAC_SERVICE_REMINDER:
				$Result = array(
					'Consumers'			=> $Dms->GetCountHvacConsumers(),
					'Active Contracts'	=> $Dms->GetCountHvacContracts(),
					'Expired Contracts'	=> $Dms->GetCountHvacContracts(true)
				);
			break;
			case HVAC_PRE_RENEWAL:
				$Result = array(
					'Consumers'			=> $Dms->GetCountHvacConsumers(),
					'Active Contracts'	=> $Dms->GetCountHvacContracts(),
					'Expired Contracts'	=> $Dms->GetCountHvacContracts(true)
				);
			break;
			case HVAC_SERVICE_CONTRACT_EXPIRATION:
				$Result = array(
					'Consumers'			=> $Dms->GetCountHvacConsumers(),
					'Active Contracts'	=> $Dms->GetCountHvacContracts(),
					'Expired Contracts'	=> $Dms->GetCountHvacContracts(true)
				);
			break;
		}

		return $Result;
	}


	/***
	`* Trade Cycle (6 notifications)
	`******************************************************************************************/
	public function LoadForm20()
	{
		$TriggerNameId		= 20;
		$TriggerSettingId 	= TriggerSettingPeer::GetSettingId($this->customer_id, 20, $this->dmstrigconn);
		$this->Brands		= self::GetTriggerBrandLevels(20, $TriggerSettingId);

		$this->ProductConfiguredStats 	= $this->GetProductConfiguredStats($this->customer_id);
		$this->OverviewStats			= $this->GetOverviewStats($this->customer_id, $TriggerNameId);

		$TriggerLevel		= intval($this->getRequestParameter('level'));
		if (!$TriggerLevel) $TriggerLevel = 1;
		$this->TriggerLevel = $TriggerLevel;

		$this->brand = $this->getRequestParameter('brand');
		if (!$this->brand) $this->brand = 'DEFAULT';


		$this->LoadMakes();


		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerTCVData.php";

		//This file gets existing vehicle filters
		include("TriggerTCVehicleFilters.php");

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_2);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_3);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_4);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_5);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,33);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
	#$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$C->add(TriggerSettingFilterPeer::BRAND,"$this->brand");
	#$C->add(TriggerSettingFilterPeer::LEVEL, $TriggerLevel);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();

		$vSettings["delay"] =$row['NOTIFICATION_PERIOD'] - 1;
		$vSettings["mail"] = $row["MAIL1_1"];
		$vSettings["id"] = $row['TRIGGER_SETTING_FILTER_ID'];
        $vSettings["mail_yn"] = $row['MAIL_YN'];
	    $vSettings["email_yn"] = $row['EMAIL_YN'];
		$vSettings["email_chase_days_1"] = $row["EMAIL_CHASE_DAYS_1"];
		$vSettings["email_chase_days_2"] = $row["EMAIL_CHASE_DAYS_2"];
		$vSettings["email_chase_days_3"] = $row["EMAIL_CHASE_DAYS_3"];
		$vSettings["email_chase_days_4"] = $row["EMAIL_CHASE_DAYS_4"];
		$vSettings["email_chase_days_5"] = $row["EMAIL_CHASE_DAYS_5"];

		//$vSettings["email"] = $row["EMAIL_1"];
		if ($row["ENABLED_YN"] == "Y") $vSettings["defaultenabled"] = 1;
		else $vSettings["defaultenabled"] = 0;

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		//$this->vehicleFilterData["email"] = $this->vehicleEmail;
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;
		$this->vehicleFilterData["defaultFilter"] = $vSettings;
		$this->vehicleFilterData["defaultFilter"]["customer_id"] = $this->customer_id;

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 33 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	public function loadForm31()
	{
		$TriggerSettingId 	= TriggerSettingPeer::GetSettingId($this->customer_id,31, $this->dmstrigconn);
		$TriggerLevel		= intval($this->getRequestParameter('level'));
		if (!$TriggerLevel) $TriggerLevel = 1;
		$this->TriggerLevel = $TriggerLevel;


		$this->loadMakes();

		include "TriggerLEVData.php";
		#include "TriggerLEVehicleFilters.php";

		//Get data for default vehicle filter
		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::BRAND);
		$C->addSelectColumn(TriggerSettingFilterPeer::ENABLED_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL1_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::NOTIFICATION_PERIOD);
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::MAIL_YN);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_1);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_2);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_3);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_4);
		$C->addSelectColumn(TriggerSettingFilterPeer::EMAIL_CHASE_DAYS_5);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,34);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::BRAND,'DEFAULT');
		$C->add(TriggerSettingFilterPeer::LEVEL, $TriggerLevel);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );
		$filterrs->next();
		$row = $filterrs->getRow();

		$vSettings["delay"] =$row['NOTIFICATION_PERIOD'] - 1;
		$vSettings["mail"] = $row["MAIL1_1"];
		$vSettings["id"] = $row['TRIGGER_SETTING_FILTER_ID'];
        $vSettings["mail_yn"] = $row['MAIL_YN'];
	    $vSettings["email_yn"] = $row['EMAIL_YN'];
		$vSettings["email_chase_days_1"] = $row["EMAIL_CHASE_DAYS_1"];
		$vSettings["email_chase_days_2"] = $row["EMAIL_CHASE_DAYS_2"];
		$vSettings["email_chase_days_3"] = $row["EMAIL_CHASE_DAYS_3"];
		$vSettings["email_chase_days_4"] = $row["EMAIL_CHASE_DAYS_4"];
		$vSettings["email_chase_days_5"] = $row["EMAIL_CHASE_DAYS_5"];

		//$vSettings["email"] = $row["EMAIL_1"];
		if ($row["ENABLED_YN"] == "Y") $vSettings["defaultenabled"] = 1;
		else $vSettings["defaultenabled"] = 0;

		//Array to pass to vehicle filter partials for populating drop boxes.
		$this->vehicleFilterData = array();
		$this->vehicleFilterData["makedrop"] = $this->makedrop;
		//$this->vehicleFilterData["email"] = $this->vehicleEmail;
		$this->vehicleFilterData["mail"] = $this->mailSelect;
		$this->vehicleFilterData["existingFilters"] = $this->existingFilters;
		$this->vehicleFilterData["defaultFilter"] = $vSettings;
		$this->vehicleFilterData["defaultFilter"]["customer_id"] = $this->customer_id;

		$sql = "SELECT change_date, user_id FROM trigger_setting_log WHERE customer_id = " . $this->customer_id . " AND trigger_name_id = " . intval($this->getRequestParameter('form')) . " AND trigger_filter_id = 34 ORDER BY change_date DESC LIMIT 1";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_array($result);
			$this->vehicleFilterData["defaultFilter"]["change_date"] = $row["change_date"];
			$this->vehicleFilterData["defaultFilter"]["user_id"] = $row["user_id"];
		}
		else
		{
			$this->vehicleFilterData["defaultFilter"]["change_date"] = '0000-00-00 00:00:00';
			$this->vehicleFilterData["defaultFilter"]["user_id"] = 0;
		}
	}


	public function saveForm1()
	{
		//die($this->getRequestParameter("coupon1_1_return_reminder"));
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, 1, $this->dmstrigconn);
		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerSMVData.php";

		$filterid = $this->getFilterId($this->TriggerSettingId,1);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);

		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(1);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		if ($this->getRequestParameter('timeandmileage') == "simple")
		$this->TriggerSettingFilter->setTimeMileageType("SIMPLE");
		else
		$this->TriggerSettingFilter->setTimeMileageType("SERVICE PLAN");

		$this->TriggerSettingFilter->setCoupon21($this->getRequestParameter("coupon2_1_service_reminder"));
		$this->TriggerSettingFilter->setCoupon22($this->getRequestParameter("coupon2_2_service_reminder"));
		$this->TriggerSettingFilter->setCoupon11($this->getRequestParameter("coupon1_1_return_reminder"));
		$this->TriggerSettingFilter->setCoupon12($this->getRequestParameter("coupon1_2_return_reminder"));

		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 1, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,2);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);

		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(2);
		$this->TriggerSettingFilter->setActiveYn('Y');
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setOpcodes($this->getRequestParameter('opcodes'));
		$this->TriggerSettingFilter->setCoupon21($this->getRequestParameter("coupon2_1_service_reminder"));
		$this->TriggerSettingFilter->setCoupon22($this->getRequestParameter("coupon2_2_service_reminder"));
		$this->TriggerSettingFilter->setCoupon11($this->getRequestParameter("coupon1_1_return_reminder"));
		$this->TriggerSettingFilter->setCoupon12($this->getRequestParameter("coupon1_2_return_reminder"));
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->timing = $this->vehicleNotificationTiming[$this->getRequestParameter('defaultNotificationTiming')];
		$this->returnmail = $this->getRequestParameter('defaultReturnReminderMail');
		$this->salesmail = $this->getRequestParameter('defaultSalesToServiceMail');
		$filterid = $this->getFilterId($this->TriggerSettingId,3);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);

		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(3);
		$this->TriggerSettingFilter->setActiveYn('Y');
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setNotificationPeriod(intval($this->timing));
		$this->TriggerSettingFilter->setNotificationPeriodType("MONTH");
		$this->setCoupons();
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		if ($this->salesmail) { $this->TriggerSettingFilter->setMail21($this->salesmail); }
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 3, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController/form/' . $this->form);
	}


	public function saveForm2()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, 2, $this->dmstrigconn);
		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerACVData.php";

		$filterid = $this->getFilterId($this->TriggerSettingId,4);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(4);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		if ($this->getRequestParameter('contactadvisor') == 1)
		$this->TriggerSettingFilter->setContactAdvisor(1);
		else
		$this->TriggerSettingFilter->setContactAdvisor(0);
		$this->TriggerSettingFilter->setContactAdvisor(0);
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$filterid = $this->getFilterId($this->TriggerSettingId,5);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(5);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setNotificationPeriod(intval($this->timing));
		$this->TriggerSettingFilter->setNotificationPeriodType("MONTH");
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		if ($this->salesmail) { $this->TriggerSettingFilter->setMail21($this->salesmail); }
		$this->TriggerSettingFilter->setEmail1($this->email);
		$this->TriggerSettingFilter->setCoupon11($this->coupon1);
		$this->TriggerSettingFilter->setCoupon21($this->coupon2);
		$this->TriggerSettingFilter->setCoupon31($this->coupon3);
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm3()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, 3, $this->dmstrigconn);
		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerBVData.php";

		$filterid = $this->getFilterId($this->TriggerSettingId,6);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(6);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$filtercodes = "";
		if ($this->getRequestParameter('startwithm') == 1) $filtercodes .=" [[:<:]]M";
		if ($this->getRequestParameter('startwithbck') == 1) $filtercodes .=" [[:<:]]BCK";
		if ($this->getRequestParameter('startwithro') == 1) $filtercodes .=" [[:<:]]RO";
		if ($this->getRequestParameter('endwithp') == 1) $filtercodes .=" P[[:>:]]";
		if ($this->getRequestParameter('arenumeric') == 1) $filtercodes .=" [[:digit:]]*";
		if ($this->getRequestParameter('startwithm') == 1) $filtercodes .=" APPT";
		$this->TriggerSettingFilter->setPartsFilterPartCodes(trim($filtercodes));
		$this->TriggerSettingFilter->setPartsRecallDays($this->partsrecall[$this->getRequestParameter('partsrecall')]);
		$this->TriggerSettingFilter->setPartsAfterSecondCall($this->thirdcall[$this->getRequestParameter('thirdcall')]);
		if ($this->getRequestParameter('callro') == 1)
		$this->TriggerSettingFilter->setPartsCallRoOpcode($this->getRequestParameter('callroOpcode'));
		$this->TriggerSettingFilter->setPartsFilterCountermen($this->getRequestParameter('countermen'));
		$this->TriggerSettingFilter->setPartsFilterCustomers($this->getRequestParameter('custnums'));
		$this->TriggerSettingFilter->setPartsSpecialOrderReturnDays($this->getRequestParameter('return'));
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 3, trigger_filter_id = 6, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,7);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->returnmail = $this->getRequestParameter('defaultReturnReminderMail');
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(7);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$this->saveCommon();

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 3, trigger_filter_id = 7, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm5()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,5, $this->dmstrigconn);

		$this->timing = $this->vehicleNotificationTiming[$this->getRequestParameter('defaultNotificationTiming')];
		if ($this->getRequestParameter('defaultenabled') == 1)
		$this->enabled = "Y";
		else $this->enabled = "N";
		$this->returnmail = $this->getRequestParameter('defaultReturnReminderMail');
		$filterid = $this->getFilterId($this->TriggerSettingId,26);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(26);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setLevel(1);
		$this->TriggerSettingFilter->setEnabledYn($this->enabled);
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 5, trigger_filter_id = 26, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm6()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,6, $this->dmstrigconn);

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerFUVData.php";

		$this->timing = $this->delaySelect[$this->getRequestParameter('defaultNotificationTiming')];
		if ($this->timing == "Never")
		{
			$this->period = -1;
			$this->periodtype = "HOUR";
		}
		elseif ($this->timing == "No Delay")
		{
			$this->period = 0;
			$this->periodtype = "HOUR";
		}
		else
		{
			$this->period = intval($this->timing);
			if (stripos($this->timing,'HOUR') !== false) $this->periodtype = "HOUR";
			if (stripos($this->timing,'DAY') !== false) $this->periodtype = "DAY";
			if (stripos($this->timing,'WEEK') !== false) $this->periodtype = "WEEK";
			if (stripos($this->timing,'MONTH') !== false) $this->periodtype = "MONTH";
		}
		$this->returnmail = $this->getRequestParameter('defaultReturnReminderMail');
		$this->email = $this->getRequestParameter('defaultVehicleEmail');

		$filterid = $this->getFilterId($this->TriggerSettingId,15);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(15);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setNotificationPeriod($this->period);
		$this->TriggerSettingFilter->setNotificationPeriodType($this->periodtype);
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		$this->setFollowupCalltypeQuestions();
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 6, trigger_filter_id = 15, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,11);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(11);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		if ($this->getRequestParameter('enablecustom') == 1)
		{
			$this->TriggerSettingFilter->setFollowupCustPromptEnabledYn("Y");
			$this->TriggerSettingFilter->setFollowupCustPromptGreeting($this->getRequestParameter('greetingprompt'));
			$this->TriggerSettingFilter->setFollowupCustPromptVoicemail($this->getRequestParameter('voiceprompt'));
		}
		else
		$this->TriggerSettingFilter->setFollowupCustPromptEnabledYn("N");
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 6, trigger_filter_id = 11, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,13);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(13);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		if ($this->getRequestParameter('contactadvisor') == 1)
		$this->TriggerSettingFilter->setFollowupSettingsContact("Y");
		else $this->TriggerSettingFilter->setFollowupSettingsContact("N");
		if ($this->getRequestParameter('custpay') == 1)
		$this->TriggerSettingFilter->setFollowupSettingsCustPay("Y");
		else $this->TriggerSettingFilter->setFollowupSettingsCustPay("N");
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 6, trigger_filter_id = 13, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,14);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(14);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		if ($this->getRequestParameter('active') == 1)
		{
			$this->TriggerSettingFilter->setFollowup21dayEnableYn("Y");
			$this->TriggerSettingFilter->setFollowup21dayPickupMessage($this->getRequestParameter('answermsg'));
			$this->TriggerSettingFilter->setFollowup21dayMessageVoicemail($this->getRequestParameter('voicemailmsg'));
		}
		else $this->TriggerSettingFilter->setFollowup21dayEnableYn("N");
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 6, trigger_filter_id = 14, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm7()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,7, $this->dmstrigconn);

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerDRVData.php";

		$filterid = $this->getFilterId($this->TriggerSettingId,16);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(16);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		if ($this->getRequestParameter('asrenabled') == 1)
		{
			$this->TriggerSettingFilter->setAsrProEnabledYn("Y");
		}
		else
		$this->TriggerSettingFilter->setAsrProEnabledYn("N");
		if ($this->getRequestParameter('requireasr') == 1)
		{
			$this->TriggerSettingFilter->setAsrRedRequiredYn("Y");
		}
		else
		$this->TriggerSettingFilter->setAsrRedRequiredYn("N");
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 7, trigger_filter_id = 16, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));


				$this->make = 'DEFAULT';
				if ($this->getRequestParameter('categoryEnabled') == true) $this->enabled = "Y";
				else $this->enabled = "N";

				$this->addServiceFilter($this->make,$this->enabled,$this->getRequestParameter('brakesMailY'),$this->getRequestParameter('brakesOpcodesY'),$this->getRequestParameter('brakesDelayY'),1);

				$this->addServiceFilter($this->make,$this->enabled,$this->getRequestParameter('brakesMailR'),$this->getRequestParameter('brakesOpcodesR'),$this->getRequestParameter('brakesDelayR'),2);

				$this->addServiceFilter($this->make,$this->enabled,$this->getRequestParameter('tiresMailY'),$this->getRequestParameter('tiresOpcodesY'),$this->getRequestParameter('tiresDelayY'),3);

				$this->addServiceFilter($this->make,$this->enabled,$this->getRequestParameter('tiresMailR'),$this->getRequestParameter('tiresOpcodesR'),$this->getRequestParameter('tiresDelayR'),4);

				$this->addServiceFilter($this->make,$this->enabled,$this->getRequestParameter('batteriesMailY'),$this->getRequestParameter('batteriesOpcodesY'),$this->getRequestParameter('batteriesDelayY'),5);

				$this->addServiceFilter($this->make,$this->enabled,$this->getRequestParameter('batteriesMailR'),$this->getRequestParameter('batteriesOpcodesR'),$this->getRequestParameter('batteriesDelayR'),6);

				$this->addServiceFilter($this->make,$this->enabled,$this->getRequestParameter('additionalMailY'),$this->getRequestParameter('additionalOpcodesY'),$this->getRequestParameter('additionalDelayY'),7);

				$this->addServiceFilter($this->make,$this->enabled,$this->getRequestParameter('additionalMailR'),$this->getRequestParameter('additionalOpcodesR'),$this->getRequestParameter('additionalDelayR'),8);

		$filterid = $this->getFilterId($this->TriggerSettingId,27);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(27);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setVehicleMakesInclude($this->getRequestParameter('includemakes'));
		$this->TriggerSettingFilter->setVehicleMakesExclude($this->getRequestParameter('excludemakes'));
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 7, trigger_filter_id = 27, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,17);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(17);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		if ($this->getRequestParameter('processrecommends') == 1)
		{
			$this->TriggerSettingFilter->setRecommendationsEnabledYn("Y");
		}
		else
		$this->TriggerSettingFilter->setRecommendationsEnabledYn("N");
		$this->TriggerSettingFilter->setRecommendationsAfterDate(date('Y-m-d',strtotime($this->getRequestParameter('donotprocessbefore'))));
		if ($this->getRequestParameter('emailrecommends') == "Y")
		{
			$this->TriggerSettingFilter->setRecommendationsIncludeText("Y");
		}
		else
		$this->TriggerSettingFilter->setRecommendationsIncludeText("N");
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 7, trigger_filter_id = 17, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm8()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,8, $this->dmstrigconn);

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerCRVData.php";

		$filterid = $this->getFilterId($this->TriggerSettingId,19);
		echo "filterid = {$filterid}<br />";
		die("Aborting\n");

		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(19);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		if ($this->getRequestParameter('instate') == 1)
		{
			$this->TriggerSettingFilter->setRecoveryStateOnly("Y");
		}
		else
		$this->TriggerSettingFilter->setRecoveryStateOnly("N");
		$this->TriggerSettingFilter->setRecoveryOldestYear($this->getRequestParameter('oldestyear'));
		$this->TriggerSettingFilter->setRecoveryMaxMonths($this->getRequestParameter('maxmonths'));
		$this->TriggerSettingFilter->setVehicleMakesInclude($this->getRequestParameter('includemakes'));
		$this->TriggerSettingFilter->setVehicleMakesExclude($this->getRequestParameter('excludemakes'));
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 8, trigger_filter_id = 19, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm9()
	{
		$this->inspections = array('- Select -','Alaska Emissions Inspection','Arizona Emissions Inspection','California Emissions Inspection','Colorado Emissions Inspection','Connecticut Emissions Inspection','Delaware Safety Inspection','District of Columbia Safety Inspection','Georgia Emissions Inspection','Hawaii Safety Inspection','Illinois Emissions Inspection','Indiana Emissions Inspection','Louisiana Safety Inspection','Maine Safety Inspection','Massachusetts Safety Inspection','Mississippi Safety Inspection','Missouri Safety Inspection','Nevada Emissions Inspection','New Hampshire Safety Inspection','New Jersey Safety Inspection','New Mexico Emissions Inspection','New York Safety Inspection','North Carolina Inspection (Safety and Emissions)','Ohio Emissions Inspection','Oregon Emissions Inspection','Pennsylvania Safety Inspection','Rhode Island Safety Inspection','Texas Safety Inspection','Utah Safety Inspection','Vermont Safety Inspection','Virginia Safety Inspection','Washington Emissions Inspection','West Virginia Safety Inspection','Wisconsin Emissions Inspection');

		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,9, $this->dmstrigconn);

		//This file holds the arrays used to populate the State Inspection vehicle filter dropdowns
		include "TriggerSIVData.php";

		$this->timing = $this->delaySelect[$this->getRequestParameter('defaultNotificationTiming')];
		if ($this->getRequestParameter('defaultenabled') == 1)
		$this->enabled = "Y";
		else $this->enabled = "N";
		$this->returnmail = $this->getRequestParameter('defaultReturnReminderMail');
		$filterid = $this->getFilterId($this->TriggerSettingId,22);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(22);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setEnabledYn($this->enabled);
		$this->TriggerSettingFilter->setNotificationPeriod(intval($this->timing));
		$this->TriggerSettingFilter->setNotificationPeriodType("DAY");
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 9, trigger_filter_id = 22, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,21);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(21);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setStateInspectionRequired($this->inspections[$this->getRequestParameter('inspection')]);
		$this->TriggerSettingFilter->setOpcodes($this->getRequestParameter('opcodes'));
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 9, trigger_filter_id = 21, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm12()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,12, $this->dmstrigconn);

		//This file holds the arrays used to populate the Sceduled Maintenance vehicle filter dropdowns
		include "TriggerPFVData.php";

		$this->timing = $this->delaySelect[$this->getRequestParameter('defaultNotificationTiming')];
		if ($this->timing == "Never")
		{
			$this->period = -1;
			$this->periodtype = "HOUR";
		}
		elseif ($this->timing == "No Delay")
		{
			$this->period = 0;
			$this->periodtype = "HOUR";
		}
		else
		{
			$this->period = intval($this->timing);
			$this->periodtype = "DAY";
		}
		$this->returnmail = $this->getRequestParameter('defaultReturnReminderMail');
		//$this->email = $this->getRequestParameter('defaultVehicleEmail');

		$filterid = $this->getFilterId($this->TriggerSettingId,15);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(15);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setNotificationPeriod($this->period);
		$this->TriggerSettingFilter->setNotificationPeriodType($this->periodtype);
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		//$this->TriggerSettingFilter->setEmail1($this->email);
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 12, trigger_filter_id = 15, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,11);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(11);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		if ($this->getRequestParameter('enablecustom') == 1)
		{
			$this->TriggerSettingFilter->setFollowupCustPromptEnabledYn("Y");
			$this->TriggerSettingFilter->setFollowupCustPromptGreeting($this->getRequestParameter('greetingprompt'));
			$this->TriggerSettingFilter->setFollowupCustPromptVoicemail($this->getRequestParameter('voiceprompt'));
		}
		else
		$this->TriggerSettingFilter->setFollowupCustPromptEnabledYn("N");
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 12, trigger_filter_id = 11, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,28);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(28);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setFollowupVehicleType($this->getRequestParameter('vehicletype'));
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 12, trigger_filter_id = 28, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm14()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->level = intval($this->getRequestParameter('level'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,14, $this->dmstrigconn);

		if ($this->getRequestParameter('defaultenabled') == 1)
		$this->enabled = "Y";
		else $this->enabled = "N";

		//This file holds the arrays used to populate the Lease Expiration vehicle filter dropdowns
		include "TriggerLEVData.php";

		$this->period = intval($this->getRequestParameter('defaultdelay')) + 1;
		$this->periodtype = "MONTH";

		$this->returnmail = $this->getRequestParameter('defaultReturnReminderMail');
		//$this->email = $this->getRequestParameter('defaultVehicleEmail');

		$filterid = $this->getFilterId($this->TriggerSettingId,24, $this->level);

		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(24);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setEnabledYn($this->enabled);

		if ($this->level)
			$this->TriggerSettingFilter->setLevel($this->level);

		$this->TriggerSettingFilter->setNotificationPeriod($this->period);
		$this->TriggerSettingFilter->setNotificationPeriodType($this->periodtype);
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		//$this->TriggerSettingFilter->setEmail1($this->email);
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 14, trigger_filter_id = 24, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm15()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->notificationPeriod = intval($this->getRequestParameter('monthNotification'));
		$this->notificationPeriod2 = intval($this->getRequestParameter('mileageNotification'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,15, $this->dmstrigconn);

		//This file holds the arrays used to populate the Lease Expiration vehicle filter dropdowns
		include "TriggerWNVData.php";

		$this->returnmail = $this->getRequestParameter('defaultReturnReminderMail');
		//$this->email = $this->getRequestParameter('defaultVehicleEmail');
		if ($this->getRequestParameter('defaultenabled') == 1)
		$this->enabled = "Y";
		else $this->enabled = "N";
		if ($this->getRequestParameter('warrantymileage') == 1)
		$this->zeromileage = "Y";
		else $this->zeromileage = "N";

		$filterid = $this->getFilterId($this->TriggerSettingId,29);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(29);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		$this->TriggerSettingFilter->setNotificationPeriod($this->notificationPeriod);
		$this->TriggerSettingFilter->setNotificationPeriodType("MONTH");
		//$this->TriggerSettingFilter->setEmail1($this->email);
		$this->TriggerSettingFilter->setEnabledYn($this->enabled);
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 15, trigger_filter_id = 29, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$filterid = $this->getFilterId($this->TriggerSettingId,23);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(23);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setNotificationPeriod($this->notificationPeriod2);
		$this->TriggerSettingFilter->setWarrantyExpirationMileageZeroYn($this->zeromileage);
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 15, trigger_filter_id = 23, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm18()
	{
		return false; ///////////////////////////////////////////////
		////////@@@@@@@@@@@@@@@@@@@@@@@ Change this when we're ready for it
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,19, $this->dmstrigconn);
		$this->returnmail = $this->getRequestParameter('defaultMail');
		$enabled = $this->getRequestParameter('defaultEnabled');
		if (!$enabled) $enabled = 'N';
		else $enabled = 'Y';


		$filterid = $this->getFilterId($this->TriggerSettingId,31);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(31);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setLevel(1);
		$this->TriggerSettingFilter->setEnabledYn($enabled);
		$this->TriggerSettingFilter->setNotificationPeriod($this->getRequestParameter('defaultDelay'));
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		//die(print_r($this->TriggerSettingFilter));
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "
				INSERT INTO		trigger_setting_log
				SET				user_id = " . $this->curuser . ",
								change_date = '" . date('Y-m-d H:i:s') . "',
								customer_id = " . $this->customer_id . ",
								trigger_name_id = 19,
								trigger_filter_id = 33, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function saveForm19()
	{
		$this->form = intval($this->getRequestParameter('form'));
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id,19, $this->dmstrigconn);
		$this->returnmail = $this->getRequestParameter('defaultMail');
		$enabled = $this->getRequestParameter('defaultEnabled');
		if (!$enabled) $enabled = 'N';
		else $enabled = 'Y';


		$filterid = $this->getFilterId($this->TriggerSettingId,31);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(31);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setLevel(1);
		$this->TriggerSettingFilter->setEnabledYn($enabled);
		$this->TriggerSettingFilter->setNotificationPeriod($this->getRequestParameter('defaultDelay'));
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		//die(print_r($this->TriggerSettingFilter));
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "
				INSERT INTO		trigger_setting_log
				SET				user_id = " . $this->curuser . ",
								change_date = '" . date('Y-m-d H:i:s') . "',
								customer_id = " . $this->customer_id . ",
								trigger_name_id = 19,
								trigger_filter_id = 33, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	/**
	* Get product mail/email configured status
	****************************************************************************************/
	public function GetProductConfiguredStats($CustomerId)
	{
		$arrayApproved	= array();
		$arrayProduct 	= Us2ProductLiveConfigPeer::GetApprovedByCustomer($CustomerId);
		$arrayEmail		= EmailTemplateMapPeer::GetAssignedProductByCustomer($CustomerId);

		foreach ($arrayProduct as $id => $data) {
			$ProductId = $data['product_id'];
			$arrayApproved[$ProductId]['product'] 	= true;
			$arrayApproved[$ProductId]['email']		= false;
		}

		foreach ($arrayEmail as $ProductId) {
			$arrayApproved[$ProductId]['email'] = true;
		}

		return $arrayApproved;
	}


	/***
	`*
	`* Save trigger form
	`*
	`************************************************************************************************/
	public function SaveForm($TriggerId)
	{
		$this->CustomerId 		= $this->getUser()->getAttribute('customer_id');
		$this->TriggerName		= TriggerNamePeer::retrieveByPk($TriggerId, $this->dmstrigconn);
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->CustomerId, $TriggerId, $this->dmstrigconn);
		$this->VehicleFilterId	= TriggerSettingFilterPeer::GetTriggerVehicleFilterId($TriggerId, $this->dmstrigconn);
		$this->brand			= $this->getRequestParameter('brand');
		if (in_array($TriggerId, self::$NEW_HVAC_TRIGGERS)) {
			$this->contract			= $this->getRequestParameter('contract', 'DEFAULT');
			$this->DoLog(__LINE__.": YES! contract: {$this->contract}");
		}
		$this->DoLog(__LINE__.": TriggerId: {$TriggerId}, array: ".print_r(self::$NEW_HVAC_TRIGGERS, true).", contract: {$this->contract}");

		$this->SaveCommon();



		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
			$enabled		= $this->Get("enabled[$level]") ? 'Y' : 'N';

			$sendMail		= $this->Get("send_mail[$level]") ? 'Y' : 'N';
			$sendEmail		= $this->Get("send_email[$level]") ? 'Y' : 'N';
			$sendLivecall	= $this->Get("send_livecall[$level]") ? 'Y' : 'N';
			$sendVoice		= $this->Get("send_voice[$level]") ? 'Y' : 'N';
			$sendSms		= $this->Get("send_sms[$level]") ? 'Y' : 'N';
			$sendFacebook	= $this->Get("send_facebook[$level]") ? 'Y' : 'N';
			$mileageZero	= $this->Get("warranty_exp_mileage_zero[$level]") ? 'Y' : 'N';
			$product		= $this->Get("product[$level]");
			$product2		= $this->Get("product2[$level]");
			$opcodes		= $this->Get("opcodes[$level]");
			$setting1		= $this->Get("setting_1[$level]");
			$setting2		= $this->Get("setting_2[$level]");
			$setting3		= $this->Get("setting_3[$level]");
			$setting4		= $this->Get("setting_4[$level]");
			$setting5		= $this->Get("setting_5[$level]");
			$setting6		= $this->Get("setting_6[$level]");
			$setting7		= $this->Get("setting_7[$level]");
			$setting8		= $this->Get("setting_8[$level]");
			$setting9		= $this->Get("setting_9[$level]");
			$setting10		= $this->Get("setting_10[$level]");
			$chase2			= $this->Get("email_chase_days_2[$level]");
			$chase3			= $this->Get("email_chase_days_3[$level]");
			$notePeriod		= $this->Get("notification_period[$level]");
			$notePeriodType	= $this->Get("notification_period_type[$level]");
			$trigIdentifier	= $this->Get("trigger_identifier[$level]");


			$this->DoLog(__LINE__.": LoadByCustomerBrandLevel({$this->CustomerId}, {$this->TriggerSettingId}, {$this->VehicleFilterId}, {$this->brand}, {$level}, {$this->contract}, this->dmstrigconn)");
			$TriggerSettingFilter = TriggerSettingFilterPeer::LoadByCustomerBrandLevel($this->CustomerId, $this->TriggerSettingId, $this->VehicleFilterId, $this->brand, $level, $this->contract, $this->dmstrigconn);

			# Create one if it doesn't exist
			if (! $TriggerSettingFilter)
			{
				$TriggerSettingFilter = $this->BuildEmptyFilter();
				$TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
				$TriggerSettingFilter->setFilterId($this->VehicleFilterId);
				$TriggerSettingFilter->setCustomerId($this->CustomerId);
				$TriggerSettingFilter->setLevel($level);
				$TriggerSettingFilter->setBrand($this->brand);
				if (in_array($TriggerId, self::$NEW_HVAC_TRIGGERS)) {
					$TriggerSettingFilter->setSetting1($this->contract);
				}
				$TriggerSettingFilter->save($this->dmstrigconn);
				$this->DoLog(__LINE__.": TriggerSettingFilter->save(".$TriggerSettingFilter->getTriggerSettingFilterId().") (BuildEmptyFilter) contract: {$this->contract}");
			}

			# If Sales or Service Follow-Up Triggers with disabled or no delay, change to HOUR
			if (in_array($TriggerId, array(PURCHASE_FOLLOW_UP, SERVICE_FOLLOW_UP)) && $notePeriod <=0 ) $notePeriodType = 'HOUR';

			if ($TriggerId == SERVICE_FOLLOW_UP)
				$this->SetFollowupCallTypeQuestions($TriggerSettingFilter);

			$TriggerSettingFilter->setEnabledYn($enabled);
			$TriggerSettingFilter->setMail11($product);
			$TriggerSettingFilter->setMail21($product2);
			$TriggerSettingFilter->setMailYn($sendMail);
			$TriggerSettingFilter->setEmailYn($sendEmail);
			$TriggerSettingFilter->setLivecallYn($sendLivecall);
			$TriggerSettingFilter->setVoiceYn($sendVoice);
			$TriggerSettingFilter->setSmsYn($sendSms);
			$TriggerSettingFilter->setFacebookYn($sendFacebook);

			// If this is one of the new HVAC triggers
			if (in_array($TriggerId, self::$NEW_HVAC_TRIGGERS)) {
				// Hijack setting_1 for the contract
				$TriggerSettingFilter->setSetting1($this->contract);
			} else {
				$TriggerSettingFilter->setSetting1($setting1);
			}

			$TriggerSettingFilter->setSetting2($setting2);
			$TriggerSettingFilter->setSetting3($setting3);
			$TriggerSettingFilter->setSetting4($setting4);
			$TriggerSettingFilter->setSetting5($setting5);
			$TriggerSettingFilter->setSetting6($setting6);
			$TriggerSettingFilter->setSetting7($setting7);
			$TriggerSettingFilter->setSetting8($setting8);
			$TriggerSettingFilter->setSetting9($setting9);
			$TriggerSettingFilter->setSetting10($setting10);
			$TriggerSettingFilter->setOpcodes($opcodes);
			$TriggerSettingFilter->setEmailChaseDays2($chase2);
			$TriggerSettingFilter->setEmailChaseDays3($chase3);
			$TriggerSettingFilter->setNotificationPeriod($notePeriod);
			$TriggerSettingFilter->setNotificationPeriodType($notePeriodType);
			$TriggerSettingFilter->setWarrantyExpirationMileageZeroYn($mileageZero);
			$TriggerSettingFilter->save($this->dmstrigconn);
			$this->DoLog(__LINE__.": TriggerSettingFilter->save(".$TriggerSettingFilter->getTriggerSettingFilterId().") contract: {$this->contract}");


			# Save the trigger identifier as a trigger filter options
			if ($trigIdentifier)
			{
				$filterId 	= $TriggerSettingFilter->getTriggerSettingFilterId();
				$query 		= "INSERT INTO trigger_setting_filter_detail (trigger_setting_filter_id, field_name, field_value) VALUES ('$filterId','TRIGGER','$trigIdentifier') ON DUPLICATE KEY UPDATE field_value=VALUES(field_value) ";
				$this->dmstrigconn->executeQuery($query);
			}




			#	$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 20, trigger_filter_id = 33, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
			#	$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
		}

		/**`
		*` Save additional trigger filters
		*````````````````````````````````````````````````````````````````*/
		$Contract = '';
		switch($TriggerId)
		{
			case CUSTOMER_RECOVERY:
				$this->SaveCustomerRecovery($this->TriggerSettingId);
			break;
			case SCHEDULED_MAINTENANCE:
				$this->SaveTimeAndMileage($this->TriggerSettingId);
				$this->SaveOilChangeOpCodes($this->TriggerSettingId);
				#$this->setCoupons();
			break;
			case PURCHASE_FOLLOW_UP:
				$this->SaveFollowUpCustomGreetingPrompt($this->TriggerSettingId);
				$this->SaveSalesFollowUpVehicleType($this->TriggerSettingId);
			break;
			case SERVICE_FOLLOW_UP:
				$this->SaveFollowUpCustomGreetingPrompt($this->TriggerSettingId);
				$this->SaveFollowUpSettings($this->TriggerSettingId);
				$this->Save21DayFollowUp($this->TriggerSettingId);
			break;
			case STATE_INSPECTION_REMINDER:
				$this->SaveStateInspection($this->TriggerSettingId);
			break;
			case DECLINED_REPAIRS:
				$this->SaveAsrProIntegration($this->TriggerSettingId);
				$this->SaveMakeIncludeExclude($this->TriggerSettingId);
				$this->SaveRecommendations($this->TriggerSettingId);
			break;
            case HVAC_CUSTOMER_RECOVERY:
                $this->SaveHvacCustomerRecovery($this->TriggerSettingId);
            break;
            case HVAC_DECLINED_SERVICES:
                $this->SaveHvacDeclinedServices($this->TriggerSettingId);
            break;
            case HVAC_ANNUAL_MAINTENANCE:
                $this->SaveHvacAnnualMaintenance($this->TriggerSettingId);
            break;
            case HVAC_SERVICE_CONTRACT:
                $this->SaveHvacServiceContract($this->TriggerSettingId);
            break;
            case HVAC_SERVICE_RENEWAL:
                $this->SaveHvacServiceRenewal($this->TriggerSettingId);
            break;
            case HVAC_APPOINTMENT_CONFIRMATION:
                $this->SaveHvacAppointmentConfirmation($this->TriggerSettingId);
            break;
            case HVAC_SALES_FOLLOWUP:
                $this->SaveHvacSalesFollowup($this->TriggerSettingId);
            break;
            case HVAC_DECLINED_PURCHASE:
                $this->SaveHvacDeclinedPurchase($this->TriggerSettingId);
            break;
            case HVAC_RADIUS_MARKETING:
                $this->SaveHvacRadiusMarketing($this->TriggerSettingId);
            break;
			case HVAC_THANK_YOU:
				$this->SaveHvacThankYou($this->TriggerSettingId);
				$Contract = "/contract/".urlencode($this->contract);
			break;
			case HVAC_SERVICE_REMINDER:
				$this->SaveHvacServiceReminder($this->TriggerSettingId);
				$Contract = "/contract/".urlencode($this->contract);
			break;
			case HVAC_PRE_RENEWAL:
				$this->SaveHvacPreRenewal($this->TriggerSettingId);
				$Contract = "/contract/".urlencode($this->contract);
			break;
			case HVAC_SERVICE_CONTRACT_EXPIRATION:
				$this->SaveHvacServiceContractExpiration($this->TriggerSettingId);
				$Contract = "/contract/".urlencode($this->contract);
			break;
			case 52:	// DigitalWatchDog
				$this->SaveDigitalWatchdog($this->TriggerSettingId);
				break;
			case 53:	// Intelligent Mapping (autodealer)
				$this->SaveIntelligentMapping($this->TriggerSettingId);
				break;
			case 54:	// Intelligent Mapping (autodealer)
				$this->SaveIntelligentMappingAutoService($this->TriggerSettingId);
				break;
			case SERVICE_NO_WARRANTY:	// Service No Warranty
				$this->SaveServiceNoWarranty($this->TriggerSettingId);
				break;
			case 56:	// DealerX
				$this->SaveDealerX($this->TriggerSettingId);
				break;
		}

		$brandenc = urlencode($this->brand);
		header("Location: /TrigCustomer/TriggerController/form/{$TriggerId}/brand/{$brandenc}{$Contract}");
		exit;
	}


	/***
	`*
	`* Save Save21DayFollowUp Filter
	`*
	`************************************************************************************************/
	public function Save21DayFollowUp($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 14);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(14);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);

		if ($this->Get('active') == 1) {
			$TriggerSettingFilter->setFollowup21dayEnableYn('Y');
			$TriggerSettingFilter->setFollowup21dayPickupMessage($this->Get('answermsg'));
			$TriggerSettingFilter->setFollowup21dayMessageVoicemail($this->Get('voicemailmsg'));
		}
		else
			$TriggerSettingFilter->setFollowup21dayEnableYn('N');

		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveFollowUpSettings Filter
	`*
	`************************************************************************************************/
	public function SaveFollowUpSettings($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 13);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(13);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);

		if ($this->Get('contactadvisor') == 1)	$TriggerSettingFilter->setFollowupSettingsContact('Y');
		else 									$TriggerSettingFilter->setFollowupSettingsContact('N');

		if ($this->Get('custpay') == 1)			$TriggerSettingFilter->setFollowupSettingsCustPay('Y');
		else 									$TriggerSettingFilter->setFollowupSettingsCustPay('N');

		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveSalesFollowUpVehicleType Filter
	`*
	`************************************************************************************************/
	public function SaveSalesFollowUpVehicleType($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 28);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(28);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);
		$TriggerSettingFilter->setFollowupVehicleType($this->Get('vehicletype'));
		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveFollowUpCustomGreetingPrompt Filter
	`*
	`************************************************************************************************/
	public function SaveFollowUpCustomGreetingPrompt($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 11);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(11);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);

		if ($this->Get('enablecustom')==1)
		{
			$TriggerSettingFilter->setFollowupCustPromptEnabledYn('Y');
			$TriggerSettingFilter->setFollowupCustPromptGreeting($this->Get('greetingprompt'));
			$TriggerSettingFilter->setFollowupCustPromptVoicemail($this->Get('voiceprompt'));
		} else
			$TriggerSettingFilter->setFollowupCustPromptEnabledYn('N');

		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveRecommendations Filter
	`*
	`************************************************************************************************/
	public function SaveRecommendations($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 17);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(17);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);
		$TriggerSettingFilter->setRecommendationsAfterDate(date('Y-m-d', strtotime($this->getRequestParameter('donotprocessbefore'))));

		if ($this->Get('processrecommends')==1)	$TriggerSettingFilter->setRecommendationsEnabledYn('Y');
		else									$TriggerSettingFilter->setRecommendationsEnabledYn('N');

		if ($this->Get('emailrecommends')==1)	$TriggerSettingFilter->setRecommendationsIncludeText('Y');
		else									$TriggerSettingFilter->setRecommendationsIncludeText('N');

		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveMakeIncludeExclude Filter
	`*
	`************************************************************************************************/
	public function SaveMakeIncludeExclude($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 27);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(27);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);
		$TriggerSettingFilter->setVehicleMakesInclude($this->Get('includemakes'));
		$TriggerSettingFilter->setVehicleMakesExclude($this->Get('excludemakes'));
		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveAsrProIntegration Filter
	`*
	`************************************************************************************************/
	public function SaveAsrProIntegration($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 16);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(16);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);

		if ($this->Get('asrenabled')==1)	$TriggerSettingFilter->setAsrProEnabledYn('Y');
		else							$TriggerSettingFilter->setAsrProEnabledYn('N');

		if ($this->Get('requireasr')==1)	$TriggerSettingFilter->setAsrRedRequiredYn('Y');
		else							$TriggerSettingFilter->setAsrRedRequiredYn('N');

		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveCustomerRecovery Filter
	`*
	`************************************************************************************************/
	public function SaveCustomerRecovery($TriggerSettingId)
	{

		$this->DoLog(__LINE__.": SaveCustomerRecovery({$TriggerSettingId})");
		$FilterId = $this->GetFilterId($TriggerSettingId, 19);

		$this->DoLog(__LINE__.": SaveCustomerRecovery FilterId = {$FilterId}");

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(19);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);

		if ($this->Get('instate')==1)	$TriggerSettingFilter->setRecoveryStateOnly('Y');
		else							$TriggerSettingFilter->setRecoveryStateOnly('N');

		$TriggerSettingFilter->setRecoveryOldestYear($this->Get('oldestyear'));
		$TriggerSettingFilter->setRecoveryMaxMonths($this->Get('maxmonths'));
		$TriggerSettingFilter->setVehicleMakesInclude($this->Get('includemakes'));
		$TriggerSettingFilter->setVehicleMakesExclude($this->Get('excludemakes'));
		$TriggerSettingFilter->save($this->dmstrigconn);

		echo "SaveCustomerRecover()<br />";

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveHvacCustomerRecovery Filter
	`*
	`************************************************************************************************/
	public function SaveHvacCustomerRecovery($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 39);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(39);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);

		if ($this->Get('instate')==1)	$TriggerSettingFilter->setRecoveryStateOnly('Y');
		else							$TriggerSettingFilter->setRecoveryStateOnly('N');

		$TriggerSettingFilter->setVehicleMakesInclude($this->Get('includemakes'));
		$TriggerSettingFilter->setVehicleMakesExclude($this->Get('excludemakes'));
		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveHvacDeclinedServices Filter
	`*
	`************************************************************************************************/
	public function SaveHvacDeclinedServices($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
            $FilterId = $this->GetFilterId($TriggerSettingId, 40, $level);

            if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
            else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

            $TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
            $TriggerSettingFilter->setFilterId(40);
            $TriggerSettingFilter->setActiveYn('Y');
            $TriggerSettingFilter->setCustomerId($this->CustomerId);

            $TriggerSettingFilter->setNotificationPeriod($this->Get("delay[{$level}]"));
            $TriggerSettingFilter->setNotificationPeriodType($this->Get("delay_type[{$level}]"));
            $TriggerSettingFilter->setOpcodes(serialize($this->Get("opcodes[{$level}]")));
            $TriggerSettingFilter->save($this->dmstrigconn);

            #$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
            #$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
        }
	}


	/***
	`*
	`* Save SaveHvacAnnualMaintenance Filter
	`*
	`************************************************************************************************/
	public function SaveHvacAnnualMaintenance($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
            $FilterId = $this->GetFilterId($TriggerSettingId, 41, $level);

            if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
            else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

            $TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
            $TriggerSettingFilter->setFilterId(41);
            $TriggerSettingFilter->setActiveYn('Y');
            $TriggerSettingFilter->setCustomerId($this->CustomerId);

            $TriggerSettingFilter->setNotificationPeriod($this->Get("delay[{$level}]"));
            $TriggerSettingFilter->setNotificationPeriodType($this->Get("delay_type[{$level}]"));
            $TriggerSettingFilter->save($this->dmstrigconn);

            #$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
            #$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
        }
	}


	/***
	`*
	`* Save SaveHvacServiceContract Filter
	`*
	`************************************************************************************************/
	public function SaveHvacServiceContract($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
            $FilterId = $this->GetFilterId($TriggerSettingId, 42, $level);

            if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
            else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

            $TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
            $TriggerSettingFilter->setFilterId(42);
            $TriggerSettingFilter->setActiveYn('Y');
            $TriggerSettingFilter->setCustomerId($this->CustomerId);

            $TriggerSettingFilter->setNotificationPeriod($this->Get("system_age[{$level}]"));
            $TriggerSettingFilter->setNotificationPeriodType($this->Get("system_age_type[{$level}]"));
            $TriggerSettingFilter->setSetting1($this->Get("timing[{$level}]"));
            $TriggerSettingFilter->setSetting2($this->Get("communications[{$level}]"));
			$TriggerSettingFilter->setSetting3($this->Get("system_age_from[{$level}]"));
            $TriggerSettingFilter->save($this->dmstrigconn);

            #$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
            #$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
        }
	}


	/***
	`*
	`* Save SaveHvacServiceRenewal Filter
	`*
	`************************************************************************************************/
	public function SaveHvacServiceRenewal($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
            $FilterId = $this->GetFilterId($TriggerSettingId, 43, $level);

            if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
            else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

            $TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
            $TriggerSettingFilter->setFilterId(43);
            $TriggerSettingFilter->setActiveYn('Y');
            $TriggerSettingFilter->setCustomerId($this->CustomerId);

            $TriggerSettingFilter->setNotificationPeriod($this->Get("timing[{$level}]"));
            $TriggerSettingFilter->setNotificationPeriodType($this->Get("timing_type[{$level}]"));
            $TriggerSettingFilter->save($this->dmstrigconn);

            #$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
            #$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
        }
	}


	/***
	`*
	`* Save SaveHvacAppointmentConfirmation Filter
	`*
	`************************************************************************************************/
	public function SaveHvacAppointmentConfirmation($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
            $FilterId = $this->GetFilterId($TriggerSettingId, 44, $level);

            if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
            else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

            $TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
            $TriggerSettingFilter->setFilterId(44);
            $TriggerSettingFilter->setActiveYn('Y');
            $TriggerSettingFilter->setCustomerId($this->CustomerId);

            $TriggerSettingFilter->setNotificationPeriod($this->Get("timing[{$level}]"));
            $TriggerSettingFilter->setNotificationPeriodType($this->Get("timing_type[{$level}]"));
            $TriggerSettingFilter->save($this->dmstrigconn);

            #$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
            #$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
        }
	}


	/***
	`*
	`* Save SaveHvacSalesFollowup Filter
	`*
	`************************************************************************************************/
	public function SaveHvacSalesFollowup($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
            $FilterId = $this->GetFilterId($TriggerSettingId, 45, $level);

            if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
            else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

            $TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
            $TriggerSettingFilter->setFilterId(45);
            $TriggerSettingFilter->setActiveYn('Y');
            $TriggerSettingFilter->setCustomerId($this->CustomerId);

            $TriggerSettingFilter->setNotificationPeriod($this->Get("delay[{$level}]"));
            $TriggerSettingFilter->setNotificationPeriodType($this->Get("delay_type[{$level}]"));
            $TriggerSettingFilter->save($this->dmstrigconn);

            #$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
            #$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
        }
	}


	/***
	`*
	`* Save SaveHvacDeclinedPurchase Filter
	`*
	`************************************************************************************************/
	public function SaveHvacDeclinedPurchase($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
            $FilterId = $this->GetFilterId($TriggerSettingId, 46, $level);

            if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
            else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

            $TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
            $TriggerSettingFilter->setFilterId(46);
            $TriggerSettingFilter->setActiveYn('Y');
            $TriggerSettingFilter->setCustomerId($this->CustomerId);

            $TriggerSettingFilter->setNotificationPeriod($this->Get("delay[{$level}]"));
            $TriggerSettingFilter->setNotificationPeriodType($this->Get("delay_type[{$level}]"));
            $TriggerSettingFilter->setOpcodes(serialize($this->Get("opcodes[{$level}]")));
            $TriggerSettingFilter->save($this->dmstrigconn);

            #$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
            #$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
        }
	}


	/***
	`*
	`* Save SaveHvacRadiusMarketing Filter
	`*
	`************************************************************************************************/
	public function SaveHvacRadiusMarketing($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
            $FilterId = $this->GetFilterId($TriggerSettingId, 47, $level);

            if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
            else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

            $TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
            $TriggerSettingFilter->setFilterId(47);
            $TriggerSettingFilter->setActiveYn('Y');
            $TriggerSettingFilter->setCustomerId($this->CustomerId);

            $TriggerSettingFilter->setNotificationPeriod($this->Get("delay[{$level}]"));
            $TriggerSettingFilter->setNotificationPeriodType($this->Get("delay_type[{$level}]"));
            $TriggerSettingFilter->setSetting1($this->Get("radius_min[{$level}]"));
            $TriggerSettingFilter->setSetting8($this->Get("radius_max[{$level}]"));
            $TriggerSettingFilter->setSetting2($this->Get("communications[{$level}]"));
            $TriggerSettingFilter->setSetting3(implode(' ', $this->Get("home_ownership[{$level}]")));
            $TriggerSettingFilter->setSetting4(implode(' ', $this->Get("dwelling[{$level}]")));
            $TriggerSettingFilter->setSetting5(implode(' ', $this->Get("length_of_res[{$level}]")));
            $TriggerSettingFilter->setSetting6(implode(' ', $this->Get("year_built[{$level}]")));
            $TriggerSettingFilter->setSetting7(implode(' ', $this->Get("est_value[{$level}]")));
            $TriggerSettingFilter->save($this->dmstrigconn);

            #$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
            #$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
        }
	}


	/***
	`*
	`* Save SaveHvacThankYou Filter
	`*
	`************************************************************************************************/
	public function SaveHvacThankYou($TriggerSettingId)
	{
		$this->DoLog(__LINE__.": TriggerSettingId: {$TriggerSettingId}, this->contract: {$this->contract}");
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
			$FilterId = $this->GetFilterId($TriggerSettingId, 53, $level);

			if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
			else				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

			$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
			$TriggerSettingFilter->setFilterId(53);
			$TriggerSettingFilter->setActiveYn('Y');
			$TriggerSettingFilter->setCustomerId($this->CustomerId);

			$TriggerSettingFilter->setMail11($this->Get("product[{$level}]"));
			$TriggerSettingFilter->setNotificationPeriod($this->Get("delay[{$level}]"));
			$TriggerSettingFilter->setNotificationPeriodType($this->Get("delay_type[{$level}]"));
			$TriggerSettingFilter->setSetting1($this->contract);
			$TriggerSettingFilter->save($this->dmstrigconn);
			$this->DoLog(__LINE__.": TriggerSettingFilter->save(".$TriggerSettingFilter->getTriggerSettingFilterId()."), contract: {$this->contract}");
		}
	}


	/***
	`*
	`* Save SaveHvacServiceReminder Filter
	`*
	`************************************************************************************************/
	public function SaveHvacServiceReminder($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
			$FilterId = $this->GetFilterId($TriggerSettingId, 54, $level);

			if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
			else				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

			$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
			$TriggerSettingFilter->setFilterId(54);
			$TriggerSettingFilter->setActiveYn('Y');
			$TriggerSettingFilter->setCustomerId($this->CustomerId);

			$TriggerSettingFilter->setNotificationPeriod($this->Get("delay[{$level}]"));
			$TriggerSettingFilter->setNotificationPeriodType($this->Get("delay_type[{$level}]"));
			$TriggerSettingFilter->setSetting1($this->contract);
			$TriggerSettingFilter->save($this->dmstrigconn);
		}
	}


	/***
	`*
	`* Save SaveHvacPreRenewal Filter
	`*
	`************************************************************************************************/
	public function SaveHvacPreRenewal($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
			$FilterId = $this->GetFilterId($TriggerSettingId, 55, $level);

			if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
			else				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

			$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
			$TriggerSettingFilter->setFilterId(55);
			$TriggerSettingFilter->setActiveYn('Y');
			$TriggerSettingFilter->setCustomerId($this->CustomerId);

			$TriggerSettingFilter->setNotificationPeriod($this->Get("timing[{$level}]"));
			$TriggerSettingFilter->setNotificationPeriodType($this->Get("timing_type[{$level}]"));
			$TriggerSettingFilter->setSetting1($this->contract);
			$TriggerSettingFilter->save($this->dmstrigconn);
		}
	}


	/***
	`*
	`* Save SaveHvacServiceContractExpiration Filter
	`*
	`************************************************************************************************/
	public function SaveHvacServiceContractExpiration($TriggerSettingId)
	{
		/**`
		*` Loop through each level and create the trigger filters
		*` for the selected brand
		*````````````````````````````````````````````````````````````````*/
		for ($level=1; $level <= $this->TriggerName->GetLevelCount(); $level++)
		{
			$FilterId = $this->GetFilterId($TriggerSettingId, 56, $level);

			if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
			else				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

			$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
			$TriggerSettingFilter->setFilterId(56);
			$TriggerSettingFilter->setActiveYn('Y');
			$TriggerSettingFilter->setCustomerId($this->CustomerId);

			$TriggerSettingFilter->setNotificationPeriod($this->Get("delay[{$level}]"));
			$TriggerSettingFilter->setNotificationPeriodType($this->Get("delay_type[{$level}]"));
			$TriggerSettingFilter->setSetting1($this->contract);
			$TriggerSettingFilter->save($this->dmstrigconn);
		}
	}




	/***
	`*
	`* Save SaveDigitalWatchdog Filter
	`*
	`************************************************************************************************/
	public function SaveDigitalWatchdog($TriggerSettingId)
	{


		$Conn 					= Propel::GetConnection();




		// echo "this->CustomerId = {$this->CustomerId}<br />\n";
		$CustomerRec 	= CustomerPeer::retrieveByPK($this->CustomerId);
		// echo "CustomerRec = <pre>" . print_r($CustomerRec, true) . "</pre><br />";
		$ScTrigId 		= $this->getRequestParameter('sc_trig_id');
		// echo "ScTrigId = {$ScTrigId}<br />\n";

		$ClientId 		= $CustomerRec->getClientId();
		if ( $ScTrigId > 0 )
		{
			// Retrieve the old record
			$Query 			= "SELECT * FROM smartchannel_customer_trigger WHERE smartchannel_customer_trigger_id = {$ScTrigId} ";
			$Rs 			= $Conn->executeQuery($Query);

			$TrigRec 		= false;
			while($Rs->next())
			{
				$TrigRec 	= $Rs->getRow();
			}

			if ( $TrigRec )
			{

				$CustTrigName 	= addslashes($this->getRequestParameter('sc_name'));
				$TrigData 	= json_decode($TrigRec['data_json'], true);
				$TrigData['pixl_company_id'] 	= $this->getRequestParameter('sc_pixl_company_id');
				$TrigData['pixl_id'] 			= $this->getRequestParameter('sc_pixl_id');
				$TrigData['pixl_subdomain'] 	= $this->getRequestParameter('sc_pixl_subdomain');

				$Query 		= "UPDATE smartchannel_customer_trigger SET data_json = '" . json_encode($TrigData) . "', name = '{$CustTrigName}' WHERE smartchannel_customer_trigger_id = {$ScTrigId} LIMIT 1 ";
				// echo "Query = {$Query}<br />\n";
				$Rs 		= $Conn->executeQuery($Query);

			}

			if ( $_POST['newfilter_filter_name_id'] > 0 && $ScTrigId > 0 )
			{
				$NewFilterId 		= $_POST['newfilter_filter_name_id'];
				$NewMailProductId 	= $_POST['newfilter_mail_product_id'];
				$MaxPosId 			= 0;

				// Get the max sequence
				$Query 				= "SELECT max(sequence_pos_id) as max_pos_id FROM smartchannel_customer_trigger_detail "
									. "WHERE smartchannel_customer_trigger_id = {$ScTrigId} ";
				$Rs 				= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$MaxPosId 		= $Rs->get('max_pos_id');
				}		
				$MaxPosId++;	
				$CommRec 			= array('mail_product_id'	=> $NewMailProductId,
											'email_id'			=> 0,
											'social_id' 		=> 0
											);
				$Query 				= "INSERT INTO smartchannel_customer_trigger_detail (`smartchannel_customer_trigger_id`,`sequence_pos_id`,`smartchannel_trigger_name_id`,`properties_json`,`communication_json`) "
									. "VALUES ({$ScTrigId},{$MaxPosId},{$NewFilterId},'[]','" . addslashes(json_encode($CommRec)) . "') ";
				// echo "Query = {$Query}<br />\n";
				$Rs 				= $Conn->executeQuery($Query);
			}


			// die("Aborting\n");


		} else {
			// Create a new smart_channel_trigger record.


			$StartDate 		= date("Y-m-d");
			$EndDate 		= "2029-12-31";

			$CustTrigName 	= addslashes($this->getRequestParameter('sc_name'));
			$TrigData 		= array(
									'data_source'		=> 'api',
									'pixl_company_id' 	=> $this->getRequestParameter('sc_pixl_company_id'),
									'pixl_id' 			=> $this->getRequestParameter('sc_pixl_id'),
									'pixl_subdomain'	=> $this->getRequestParameter('sc_pixl_subdomain'),
									'sftp_host'			=> '',
									'sftp_user'			=> '',
									'sftp_pass'			=> '',
									'sftp_folder'		=> '',
									'sftp_file'			=> '',
									'start_date'		=> date("m/d/Y", strtotime($StartDate)),
									'end_date'			=> date("m/d/Y", strtotime($EndDate)),
									);
			$Query 			= "INSERT INTO smartchannel_customer_trigger (`client_id`,`customer_id`,`name`,`data_json`,`start_date`,`end_date`) "
							. "VALUES ({$ClientId}, {$this->CustomerId}, '{$CustTrigName}', '" . addslashes(json_encode($TrigData)) . "','{$StartDate}','{$EndDate}') ";
			// echo "Query = {$Query}<br />\n";
			$Rs 			= $Conn->executeQuery($Query);

			//$NewTriggerId 	= $Conn->lastInsertId();
			$NewTriggerId 	= mysql_insert_id($Conn->getResource());

			// echo "NewTriggerId = {$NewTriggerId}\n";

			if ( $_POST['newfilter_filter_name_id'] > 0 && $NewTriggerId > 0 )
			{
				$NewFilterId 		= $_POST['newfilter_filter_name_id'];
				$NewMailProductId 	= $_POST['newfilter_mail_product_id'];
				$MaxPosId 			= 0;

				// Get the max sequence
				$Query 				= "SELECT max(sequence_pos_id) as max_pos_id FROM smartchannel_customer_trigger_detail "
									. "WHERE smartchannel_customer_trigger_id = {$NewTriggerId} ";
				// echo "Query = {$Query}<br />\n";
				$Rs 				= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$MaxPosId 		= $Rs->get('max_pos_id');
				}		
				$MaxPosId++;	
				$CommRec 			= array('mail_product_id'	=> $NewMailProductId,
											'email_id'			=> 0,
											'social_id' 		=> 0
											);
				$Query 				= "INSERT INTO smartchannel_customer_trigger_detail (`smartchannel_customer_trigger_id`,`sequence_pos_id`,`smartchannel_trigger_name_id`,`properties_json`,`communication_json`) "
									. "VALUES ({$NewTriggerId},{$MaxPosId},{$NewFilterId},'[]'." . json_encode($CommRec) . "') ";
				// echo "Query = {$Query}<br />\n";
				$Rs 				= $Conn->executeQuery($Query);
			}



			// $NewScTrigId 	= $Conn->lastInsertId();
			// echo "NewScTrigId = " . print_r($NewScTrigId, true) . "\n";
		}

		// Find the detail records and update
		$KeyLen 			= strlen('sc_pixl_detail_trigger_name_id_');
		foreach($_POST as $Key => $Value)
		{
			if ( substr($Key, 0, $KeyLen)  == 'sc_pixl_detail_trigger_name_id_' )
			{
				$DetailId 	= substr($Key, $KeyLen - strlen($Key) );
				// echo "SmartChannel DetailId = {$DetailId}<br />";

				$DetailRec 	= false;

				$Query 		= "SELECT * FROM smartchannel_customer_trigger_detail "
							. "WHERE smartchannel_customer_trigger_detail_id = {$DetailId} ";
				$Rs 		= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$DetailRec 	= $Rs->getRow();					
				}

				if ( $DetailRec )
				{
					$communications = json_decode($DetailRec['communication_json'], true);



					$TriggerNameId 	= $_POST['sc_pixl_detail_trigger_name_id_' . $DetailId];
					$MailProductId 	= $_POST['sc_pixl_detail_mail_product_' . $DetailId];



					$communications['mail_product_id'] = $MailProductId;

					$Query 			= "UPDATE smartchannel_customer_trigger_detail SET "
									. "smartchannel_trigger_name_id = {$TriggerNameId}, communication_json='" . json_encode($communications) . "' "
									. "WHERE smartchannel_customer_trigger_detail_id = {$DetailId} "
									. "LIMIT 1 ";
					// echo "Query = {$Query}<br />\n";
				// echo "Query = {$Query}\n";
					$Rs 			= $Conn->executeQuery($Query);

				}

			}
		}

		$MoveMode 				= $this->getRequestParameter('move');

		if ( strlen($MoveMode) > 0 )
		{
			$TrigDetail 		= $this->getRequestParameter('detail_id');
			$SwitchDetailRow 	= false;


			// Get the detail record
			$Query 				= "SELECT * FROM smartchannel_customer_trigger_detail "
								. "WHERE smartchannel_customer_trigger_detail_id = {$TrigDetail} ";
					//	echo "Query = {$Query}<br />";
			$Rs 				= $Conn->executeQuery($Query);
			while($Rs->next())
			{
				$DetailRow 		= $Rs->getRow();
			//	echo "DetailRow = <pre>" . print_r($DetailRow, true) . "</pre><br />";
				$SequencePosId 	= $DetailRow['sequence_pos_id'];
			}

			// echo "MoveMode = {$MoveMode}<br />";
			// die("Aborting\n");

			// ToRec
			switch($MoveMode)
			{
				case 'up':
					$SwitchSeqPosId = $SequencePosId -1;
					break;
				case 'down':
					$SwitchSeqPosId = $SequencePosId +1;
					break;
			}
			// find the record we want to switch the position with
			$Query 				= "SELECT * FROM smartchannel_customer_trigger_detail "
								. "WHERE smartchannel_customer_trigger_id = {$DetailRow['smartchannel_customer_trigger_id']} "
								. "AND sequence_pos_id = {$SwitchSeqPosId} "
								. "LIMIT 1 ";
					//	echo "Query = {$Query}<br />";
			$Rs 				= $Conn->executeQuery($Query);
			while($Rs->next())
			{
				$SwitchDetailRow 	= $Rs->getRow();
				// echo "SwitchDetailRow = <pre>" . print_r($SwitchDetailRow, true) . "</pre><br />";
			}
			if ( $SwitchDetailRow )
			{
				$Query 			= "UPDATE smartchannel_customer_trigger_detail "
								. "SET sequence_pos_id = {$SequencePosId} "
								. "WHERE smartchannel_customer_trigger_detail_id = {$SwitchDetailRow['smartchannel_customer_trigger_detail_id']} ";
					//	echo "Query = {$Query}<br />";
				$Rs 			= $Conn->executeQuery($Query);

				$Query 			= "UPDATE smartchannel_customer_trigger_detail "
								. "SET sequence_pos_id = {$SwitchSeqPosId} "
								. "WHERE smartchannel_customer_trigger_detail_id = {$DetailRow['smartchannel_customer_trigger_detail_id']} ";
					// 	echo "Query = {$Query}<br />";
				$Rs 			= $Conn->executeQuery($Query);

			}

			


		}


		// if (!isset($this->vehicleFilterData['save_debug']))
		// {
		// 	$this->vehicleFilterData['save_debug'] = array();
		// }
		// $this->vehicleFilterData['save_debug'][] = "SaveDigitalWatchdog(TriggerSettingId = {$TriggerSettingId})<br />\n";
		// $this->vehicleFilterData['save_debug'][] = "_GET=<pre>" . print_r($_GET, true) . "</pre><br />";
		// $this->vehicleFilterData['save_debug'][] = "_POST=<pre>" . print_r($_POST, true) . "</pre><br />";

		// echo "this->vehicleFilterData = <pre>" . print_r($this->vehicleFilterData, true) . "</pre><br />";

		// echo "_GET=<pre>" . print_r($_GET, true) . "</pre><br />";
		// echo "_POST=<pre>" . print_r($_POST, true) . "</pre><br />";

		// die("Aborting\n");
	}




	/***
	`*
	`* Save SaveIntelligentMapping Filter
	`*
	`************************************************************************************************/
	public function SaveIntelligentMapping($TriggerSettingId)
	{
		//return true;
	//	echo "SaveIntelligentMapping(TriggerSettingId = {$TriggerSettingId})<br />\n";
		if (!isset($this->vehicleFilterData['save_debug']))
		{
			$this->vehicleFilterData['save_debug'] = array();
		}
		$this->vehicleFilterData['save_debug'][] = "SaveIntelligentMapping(TriggerSettingId = {$TriggerSettingId})<br />\n";
		$this->vehicleFilterData['save_debug'][] = "_GET=<pre>" . print_r($_GET, true) . "</pre><br />";
		$this->vehicleFilterData['save_debug'][] = "_POST=<pre>" . print_r($_POST, true) . "</pre><br />";

		// echo "SaveIntelligentMapping(TriggerSettingId = {$TriggerSettingId})<br />\n";
		// echo "_GET=<pre>" . print_r($_GET, true) . "</pre><br />";
		// echo "_POST=<pre>" . print_r($_POST, true) . "</pre><br />";
		// echo "this->filterSettings=<pre>" . print_r($this->filterSettings, true) . "</pre><br />";

		$WatchList 		= array();
		// foreach($_POST as $Key => $Value)
		// {
		// 	echo "Key = {$Key} / Value = {$Value}<br />";
		// 	if ( substr($Key, 0, 11) == 'pulse_only_' )
		// 	{
		// 		$DdsDealerId = substr($Key, 11, strlen($Key) - 10);
		// 		echo "PulseOnly DdsDealerId = '{$DdsDealerId}'<br />";
		// 		$IncludeBrandList = array();



		// 		$ModelList 	= array();
		// 		$MakeKey 	= "make_{$DdsDealerId}_";
		// 		$MakeKeyLen = strlen($MakeKey);
		// 		foreach($_POST as $Key => $Value)
		// 		{
		// 			// echo "_POST[{$Key}] = '{$Value}'<br />";
		// 			if ( substr($Key, 0, $MakeKeyLen) == $MakeKey )
		// 			{
						
		// 				$MakeModel 		= str_replace("_", " ", substr($Key, $MakeKeyLen, strlen($Key) - $MakeKeyLen));
		// 				$MakeModelParts = explode("|", $MakeModel);
		// 				$Make 			= $MakeModelParts[0];
		// 				$Model 			= $MakeModelParts[1];
		// 				$ModelList[]	= array('Make'	=> $Make,
		// 										'Model'	=> $Model
		// 										);

		// 			}
		// 		}




		// 		// $WatchList[] = array('PulseDealerId' 	=> $DdsDealerId,
		// 		// 					'IncludePii' => 'false',
		// 	}
		// 	if ( substr($Key, 0, 11) == 'pulse_plus_' )
		// 	{
		// 		$DdsDealerId = substr($Key, 11, strlen($Key) - 10);
		// 		echo "PulsePlus DdsDealerId = '{$DdsDealerId}'<br />";
		// 	}
		// }



		// Copy from PulseSubscribeAction

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

		$AmmsCoreDDS 			= new AmmsCoreDDSApi();
		$Radius 				= $this->getRequestParameter('radius');
		$DdsDealerId 			= $this->getRequestParameter('dds_dealer_id');
		$CustomerId 			= $this->getRequestParameter('customer_id');
		$BrandType 				= 'AUTODEALER';

		
		// Do we need to enroll the dealer?
		$SubRec 				= false;
		$Conn 					= Propel::GetConnection();
		$Query 					= "SELECT * FROM dds_pulse_count "
								. "WHERE customer_id = {$CustomerId} "
								. "AND brand_type = '{$BrandType}' "
								. "AND active_yn = 'Y' ";
		$Rs 					= $Conn->executeQuery($Query);
		while($Rs->next())
		{
			$SubRec 			= $Rs->getRow();
		}
		if ( !$SubRec )
		{
			$Result 	 		= json_decode($AmmsCoreDDS->EnrollDealer($CustomerId, $DdsDealerId, $Radius), true);
		}




		$this->DdsDealerList 	= array();
		$this->DealerDisplay 	= array();

		$Result 		= json_decode($AmmsCoreDDS->GetRadiusDealers($DdsDealerId, $Radius, $BrandType), true);
		//if ( $this->BrandType != "AUTODEALER" ) 
		// echo "GetRadiusDealers = <pre>" . print_r($Result, true) . "</pre><br />";

		if ( $Result['status'] == 'success')
		{				
			$RawDdsDealerList 	= $Result['data'];
			// echo "RawDdsDealerList = <pre>" . print_r($RawDdsDealerList, true) . "</pre><br />";
			foreach($RawDdsDealerList as $key => $Row)
			{
				$this->DdsDealerList[$Row['dealerId']] = $Row['dealerName'];
				// $this->DdsDealerList[$Row['dealerId']] = $Row;
				$DisplayKey 	= sprintf("%s_%s_%d", $Row['dealerName'], $Row['zip'], $Row['dealerId']);
				$this->DealerDisplay[$DisplayKey] = $Row['dealerId'];
			}
			//asort($this->DdsDealerList);
			ksort($this->DealerDisplay);
			// echo "DdsDealerList = <pre>" . print_r($this->DdsDealerList, true) . "</pre><br />";
			// echo "DealerDisplay = <pre>" . print_r($this->DealerDisplay, true) . "</pre><br />";
		}

		switch($BrandType)
		{
			case 'AUTOSERVICE':
				$SubscriptionType 	= '3rdparty';
				break;
			//case 'AUTODEALER':
			default:
				$SubscriptionType 	= 'competitor';
				break;
		}

		// echo "btnSubscribe<br />Post = <pre>" . print_r($_POST, true) . "</pre><br />";
		$SubscribeDoc 	= array('PulseDealerId' 	=> $DdsDealerId,
								'DocDealerId'		=> $CustomerId,
								'DataSource' 		=> $SubscriptionType,
								'Radius' 			=> $Radius,
								'BrandType' 		=> $BrandType,
								'WatchDataList' 	=> array()
								);

		foreach($this->DdsDealerList as $DdsId => $Name)
		{
			// echo "DdsDealerList[{$DdsDealerId}] = {$Name}<br />";
			$ModelList 	= array();
			$MakeKey 	= "make_{$DdsId}_";
			$MakeKeyLen = strlen($MakeKey);
			foreach($_POST as $Key => $Value)
			{
				// echo "_POST[{$Key}] = '{$Value}'<br />";
				if ( substr($Key, 0, $MakeKeyLen) == $MakeKey )
				{
					
					$MakeModel 		= str_replace("_", " ", substr($Key, $MakeKeyLen, strlen($Key) - $MakeKeyLen));
					$MakeModelParts = explode("|", $MakeModel);
					$Make 			= $MakeModelParts[0];
					$Model 			= $MakeModelParts[1];
					$ModelList[]	= array('Make'	=> $Make,
											'Model'	=> $Model
											);

				}
			}
			// echo "ModelList for dealer {$DdsDealerId} = <pre>" . print_r($ModelList, true) . "</pre><br />";

		// 	echo "DdsDealerId = {$DdsId}<br />\n";
			if ( isset($_POST['pulse_plus_on']))
			{
				$SubscribeDoc['WatchDataList'][] 		= array('PulseDealerId'	=> $DdsId,
															'IncludePii'	=> 'true',
															'IncludeBrandList'	=> $ModelList
															);
				$this->PostVars['pulse_plus_' . $DdsId] = 1;
			} elseif ( isset($_POST['pulse_on'])) 
			{

				$SubscribeDoc['WatchDataList'][] 		= array('PulseDealerId'	=> $DdsId,
															'IncludePii'	=> 'false',
															'IncludeBrandList'	=> $ModelList
															);
				$this->PostVars['pulse_' . $DdsId] = 1;
			} elseif ( isset($_POST['pulse_plus_' . $DdsId])) 
			{

				$SubscribeDoc['WatchDataList'][] 		= array('PulseDealerId'	=> $DdsId,
															'IncludePii'	=> 'true',
															'IncludeBrandList'	=> $ModelList
															);
			}elseif ( isset($_POST['pulse_only_' . $DdsId])) 
			{

				$SubscribeDoc['WatchDataList'][] 		= array('PulseDealerId'	=> $DdsId,
															'IncludePii'	=> 'false',
															'IncludeBrandList'	=> $ModelList
															);
			}
		}
		// echo "SubscribeDoc = <pre>" . print_r($SubscribeDoc, true) . "</pre><br />";

		// If we have at least one dealership selected, go ahead and setup a subscription.		
		if ( count($SubscribeDoc['WatchDataList']) > 0 )
		{
			$Result 		= json_decode($AmmsCoreDDS->Subscribe($SubscribeDoc), true);

			echo "AmmsCoreDDS->Subscribe Result = <pre>" . print_r($Result, true) . "</pre><br />";
			if ( $Result['status'] == 'success')
			{
				$SubRec 			= false;
				$ClientId 			= 0; 

				$DdsDealerId 		= $this->getRequestParameter('dds_dealer_id');
				// Get the subscription id that was crated.
				$Query 				= "SELECT * FROM dds_subscription "
									. "WHERE dds_dealer_id = '{$DdsDealerId}' "
									. "AND customer_id = {$CustomerId} "
									. "AND brand_type = '{$BrandType}' ";
				$Rs 				= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$SubRec 		= $Rs->getRow();
				}

				$StartDate 			= date("Y-m-d");
				$EndDate 			= '2029-12-31';
				$TriggerName 		= 'Intelligent Mapping - Dealer';

				/// Get the client_id
				$Query 				= "SELECT client_id FROM customer WHERE customer_id = {$CustomerId} ";
				$Rs 				= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$ClientId 		= $Rs->get('client_id');
				}


				// Now we have the subscription record, let's set/update the mapping_trigger
				if ( $SubRec )
				{

					// Do we need to update the record or create a new one?
					$TrigRow 		= false;
					$Query 			= "SELECT * FROM intelligent_mapping_trigger "
									. "WHERE dds_subscription_id = {$SubRec['dds_subscription_id']} ";
					$Rs 			= $Conn->executeQuery($Query);
					while($Rs->next())
					{
						$TrigRow 	= $Rs->getRow();
					}

					if( $TrigRow )
					{
						// Update the record
						$TrigData 		= array(					
												);
						$Fields 		= array('client_id' 		=> $ClientId,
												'customer_id' 		=> $CustomerId,
												'CustTrigName' 		=> $TriggerName,
												'dds_subscription_id'	=> $SubRec['dds_subscription_id'],
												'data_json'			=> json_encode($TrigData),
												'start_date' 		=> $StartDate,
												'end_date' 			=> $EndDate,
												'intelligent_mapping_trigger_id' => $TrigRow['intelligent_mapping_trigger_id']
												);
						$UpdateTrigRecRaw 	= json_decode($AmmsCoreDDS->UpdateTriggerRec($TrigRow['intelligent_mapping_trigger_id'], $Fields), true);

						// echo "UpdateTrigRec  Fields = <pre>" . print_r($Fields, true) . "</pre><br />";
						echo "UpdateTrigRecRaw =   <pre>" . print_r($UpdateTrigRecRaw, true) . "</pre><br />";

					} else {
						// Create a new record
						$TrigData 		= array(					
												);
						$Fields 		= array('client_id' 		=> $ClientId,
												'customer_id' 		=> $CustomerId,
												'CustTrigName' 		=> $TriggerName,
												'dds_subscription_id'	=> $SubRec['dds_subscription_id'],
												'data_json'			=> json_encode($TrigData),
												'start_date' 		=> $StartDate,
												'end_date' 			=> $EndDate
												);
						$NewTrigRecRaw 	= json_decode($AmmsCoreDDS->NewTriggerRec($Fields), true);

						// echo "NewTrigRec  Fields = <pre>" . print_r($Fields, true) . "</pre><br />";
						echo "NewTrigRecRaw = <pre>" . print_r($NewTriggerRec, true) . "</pre><br />";
					}

				}
			}

		}
		// echo "SubscribeDoc = <pre>" . print_r($SubscribeDoc, true) . "</pre>\n";
		// die("Aborting\n");

		// Do we need to add a new trigger detail?
		$newFilterNameId 				= intval($this->getRequestParameter('newfilter_filter_name_id'));
		$newFilterMailProductId 		= intval($this->getRequestParameter('newfilter_mail_product_id'));
		$newFilterEmailProductId 		= intval($this->getRequestParameter('newfilter_email_product_id'));
		if ( $newFilterNameId > 0 && $newFilterMailProductId > 0 )
		{

			// echo "Have new product\n<br />";
			// echo "SubRec = <pre>" . print_r($SubRec, true) . "<br />\n";
			if ( $SubRec )
			{
				$NewDDSSubId 			= false;
				// if we got a screwed up record - let's patch it.
				if ( $SubRec['dds_subscription_id'] == 0 )
				{
					$Query 				= "SELECT dds_subscription_id FROM dds_subscription "
										. "WHERE dds_dealer_id = '{$SubRec['dds_dealer_id']}' "
										. "AND brand_type = '{$SubRec['brand_type']}' ";
									echo "Query = {$Query}\n";
					$Rs 				= $Conn->executeQuery($Query);
					while($Rs->next())
					{
						$NewDDSSubId = $Rs->get('dds_subscription_id');
					}
					if ( $NewDDSSubId )
					{
						$SubRec['dds_subscription_id'] = $NewDDSSubId;
						$Query 			= "UPDATE dds_pulse_count "
										. "SET dds_subscription_id = {$NewDDSSubId} "
										. "WHERE dds_pulse_count_id = {$SubRec['dds_pulse_count_id']} ";
									echo "Query = {$Query}\n";
						$Rs 			= $Conn->executeQuery($Query);
					}
				}
			}
			// echo "Have new product<br />";
			// echo "SubRec = <pre>" . print_r($SubRec, true) . "</pre><br />";
			// Do we have a SubRec
			if ( is_array($SubRec) )
			{

				$TrigRow 		= false;
				$Query 			= "SELECT * FROM intelligent_mapping_trigger "
								. "WHERE dds_subscription_id = {$SubRec['dds_subscription_id']} ";
							echo "Query = {$Query}\n";
				$Rs 			= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$TrigRow 	= $Rs->getRow();
				}

				if ($TrigRow)
				{
					// Find the max sequence
					$NewPosId 			= 1;
					$Query 				= "SELECT max(sequence_pos_id) as max_pos_id "
										. "FROM intelligent_mapping_trigger_detail "
										. "WHERE intelligent_mapping_trigger_id = {$TrigRow['intelligent_mapping_trigger_id']} ";
							echo "Query = {$Query}\n";

					// continue;

					$Rs 				= $Conn->executeQuery($Query);
					while($Rs->next())
					{
						$NewPosId 		= $Rs->get('max_pos_id');
						if ( $NewPosId == 0 )
							$NewPosId = 1;
					}

					$Fields 			= array(
											'intelligent_mapping_trigger_id' 		=> $TrigRow['intelligent_mapping_trigger_id'],
											'sequence_pos_id' 						=> $NewPosId,
											'intelligent_mapping_trigger_name_id' 	=> $newFilterNameId,
											'properties_json' 						=> json_encode(	
																								array()
																								),	
											'communication_json'					=> json_encode(
																								array('mail_product_id'	=> $newFilterMailProductId,
																									'email_id'			=> $newFilterEmailProductId,
																									'social_id' 		=> 0  )
																								),	
											'active_yn' 			=> 'Y'
											);
					echo "New Detail Fields = <pre>" . print_r($Fields, true) . "</pre><br />";

					$NewDetailResult 	= $AmmsCoreDDS->NewTriggerDetailRec($Fields);
					echo "NewDetailResult = <pre>" . print_r($NewDetailResult, true) . "</pre><br />";

				}

			} else {
				echo "No SubRec found<br />\n";
			}
		}

		// See if we have a mail product
		foreach($_POST as $Key => $Value)
		{
			// echo "_POST[{$Key}] = {$Value}<br />\n";
			if ( substr($Key, 0, 10) == 'mail_prod_')
			{
				$DetailId 	= substr($Key, 10, strlen($Key) - 10);
				if ( $DetailId > 0 )
				{
					$Rec 				= false;
					$UpdateFlag 		= false;
					$Query 				= "SELECT * FROM intelligent_mapping_trigger_detail "
										. "WHERE intelligent_mapping_trigger_detail_id = {$DetailId} ";
					$Rs 				= $Conn->executeQuery($Query);
					while($Rs->next())
					{
						$Rec 			= $Rs->getRow();
					}
					if ( $Rec )
					{
						$Comm 			= json_decode($Rec['communication_json'], true);
						if ( $Comm['mail_product_id'] != $Value )
						{
							$Comm['mail_product_id'] = $Value;
							$UpdateFlag 	= true;
						}
						$MailFilterId 	= intval($_POST['filter_id_' . $DetailId]);
						if ( $Rec['intelligent_mapping_trigger_name_id'] != $MailFilterId && $MailFilterId > 0 )
						{
							$Rec['intelligent_mapping_trigger_name_id'] = $MailFilterId;
							$UpdateFlag = true;
						}
					}

					if ( $UpdateFlag )
					{
						$Query 		=	"UPDATE intelligent_mapping_trigger_detail "
									. "SET communication_json = '" . addslashes(json_encode($Comm)) . "', intelligent_mapping_trigger_name_id={$Rec['intelligent_mapping_trigger_name_id']} "
									. "WHERE intelligent_mapping_trigger_detail_id = {$DetailId} "
									. "LIMIT 1 ";
								echo "Query = {$Query}\n";
						$Rs 		= $Conn->executeUpdate($Query);
					}
				}
			}
		}




		// die("SaveIntelligentMapping() - Aborting\n");
	}





	/***
	`*
	`* Save SaveIntelligentMapping Filter
	`*
	`************************************************************************************************/
	public function SaveIntelligentMappingAutoService($TriggerSettingId)
	{
		//return true;
//		echo "SaveIntelligentMappingAutoService(TriggerSettingId = {$TriggerSettingId})<br />\n";
		if (!isset($this->vehicleFilterData['save_debug']))
		{
			$this->vehicleFilterData['save_debug'] = array();
		}
		$this->vehicleFilterData['save_debug'][] = "SaveIntelligentMappingAutoService(TriggerSettingId = {$TriggerSettingId})<br />\n";
		$this->vehicleFilterData['save_debug'][] = "_GET=<pre>" . print_r($_GET, true) . "</pre><br />";
		$this->vehicleFilterData['save_debug'][] = "_POST=<pre>" . print_r($_POST, true) . "</pre><br />";

		// echo "SaveIntelligentMappingAutoService(TriggerSettingId = {$TriggerSettingId})<br />\n";
		// echo "_GET=<pre>" . print_r($_GET, true) . "</pre><br />";
		// echo "_POST=<pre>" . print_r($_POST, true) . "</pre><br />";
		// echo "this->filterSettings=<pre>" . print_r($this->filterSettings, true) . "</pre><br />";

		$WatchList 		= array();
		



		// Copy from PulseSubscribeAction

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

		$AmmsCoreDDS 			= new AmmsCoreDDSApi();
		$Radius 				= $this->getRequestParameter('radius');
		$DdsDealerId 			= $this->getRequestParameter('dds_dealer_id');
		$CustomerId 			= $this->getRequestParameter('customer_id');
		$BrandType 				= 'AUTOSERVICE';

		
		// Do we need to enroll the dealer?
		$SubRec 				= false;
		$Conn 					= Propel::GetConnection();
		$Query 					= "SELECT * FROM dds_pulse_count "
								. "WHERE customer_id = {$CustomerId} "
								. "AND brand_type = '{$BrandType}' "
								. "AND active_yn = 'Y' ";
		$Rs 					= $Conn->executeQuery($Query);
		while($Rs->next())
		{
			$SubRec 			= $Rs->getRow();
		}
		if ( !$SubRec )
		{
			$Result 	 		= json_decode($AmmsCoreDDS->EnrollDealer($CustomerId, $DdsDealerId, $Radius), true);
		}




		$this->DdsDealerList 	= array();
		$this->DealerDisplay 	= array();

		$Result 		= json_decode($AmmsCoreDDS->GetRadiusDealers($DdsDealerId, $Radius, $BrandType), true);
		//if ( $this->BrandType != "AUTODEALER" ) 
		// echo "GetRadiusDealers = <pre>" . print_r($Result, true) . "</pre><br />";

		if ( $Result['status'] == 'success')
		{				
			$RawDdsDealerList 	= $Result['data'];
			// echo "RawDdsDealerList = <pre>" . print_r($RawDdsDealerList, true) . "</pre><br />";
			foreach($RawDdsDealerList as $key => $Row)
			{
				$this->DdsDealerList[$Row['dealerId']] = $Row['dealerName'];
				// $this->DdsDealerList[$Row['dealerId']] = $Row;
				$DisplayKey 	= sprintf("%s_%s_%d", $Row['dealerName'], $Row['zip'], $Row['dealerId']);
				$this->DealerDisplay[$DisplayKey] = $Row['dealerId'];
			}
			//asort($this->DdsDealerList);
			ksort($this->DealerDisplay);
			// echo "DdsDealerList = <pre>" . print_r($this->DdsDealerList, true) . "</pre><br />";
			// echo "DealerDisplay = <pre>" . print_r($this->DealerDisplay, true) . "</pre><br />";
		}

		switch($BrandType)
		{
			case 'AUTOSERVICE':
				$SubscriptionType 	= '3rdparty';
				break;
			//case 'AUTODEALER':
			default:
				$SubscriptionType 	= 'competitor';
				break;
		}

		// echo "btnSubscribe<br />Post = <pre>" . print_r($_POST, true) . "</pre><br />";
		$SubscribeDoc 	= array('PulseDealerId' 	=> $DdsDealerId,
								'DocDealerId'		=> $CustomerId,
								'DataSource' 		=> $SubscriptionType,
								'Radius' 			=> $Radius,
								'BrandType' 		=> $BrandType,
								'WatchDataList' 	=> array()
								);

		foreach($this->DdsDealerList as $DdsId => $Name)
		{
			// echo "DdsDealerList[{$DdsDealerId}] = {$Name}<br />";
			$ModelList 	= array();
			$MakeKey 	= "make_{$DdsId}_";
			$MakeKeyLen = strlen($MakeKey);
			foreach($_POST as $Key => $Value)
			{
				// echo "_POST[{$Key}] = '{$Value}'<br />";
				if ( substr($Key, 0, $MakeKeyLen) == $MakeKey )
				{
					
					$MakeModel 		= str_replace("_", " ", substr($Key, $MakeKeyLen, strlen($Key) - $MakeKeyLen));
					$MakeModelParts = explode("|", $MakeModel);
					$Make 			= $MakeModelParts[0];
					$Model 			= $MakeModelParts[1];
					$ModelList[]	= array('Make'	=> $Make,
											'Model'	=> $Model
											);

				}
			}
			// echo "ModelList for dealer {$DdsDealerId} = <pre>" . print_r($ModelList, true) . "</pre><br />";

			if ( isset($_POST['pulse_plus_on']))
			{
				$SubscribeDoc['WatchDataList'][] 		= array('PulseDealerId'	=> $DdsId,
															'IncludePii'	=> 'true',
															'IncludeBrandList'	=> $ModelList
															);
				$this->PostVars['pulse_plus_' . $DdsId] = 1;
			} elseif ( isset($_POST['pulse_on'])) 
			{

				$SubscribeDoc['WatchDataList'][] 		= array('PulseDealerId'	=> $DdsId,
															'IncludePii'	=> 'false',
															'IncludeBrandList'	=> $ModelList
															);
				$this->PostVars['pulse_' . $DdsId] = 1;
			} elseif ( isset($_POST['pulse_plus_' . $DdsId])) 
			{

				$SubscribeDoc['WatchDataList'][] 		= array('PulseDealerId'	=> $DdsId,
															'IncludePii'	=> 'true',
															'IncludeBrandList'	=> $ModelList
															);
			}elseif ( isset($_POST['pulse_only_' . $DdsId])) 
			{

				$SubscribeDoc['WatchDataList'][] 		= array('PulseDealerId'	=> $DdsId,
															'IncludePii'	=> 'false',
															'IncludeBrandList'	=> $ModelList
															);
			}
		}
		// echo "SubscribeDoc = <pre>" . print_r($SubscribeDoc, true) . "</pre><br />";

		// If we have at least one dealership selected, go ahead and setup a subscription.		
		if ( count($SubscribeDoc['WatchDataList']) > 0 )
		{
			// echo "Calling Subscribe()<br />";

			$Result 		= json_decode($AmmsCoreDDS->Subscribe($SubscribeDoc), true);

			// echo "AmmsCoreDDS->Subscribe Result = <pre>" . print_r($Result, true) . "</pre><br />";
			if ( $Result['status'] == 'success')
			{
				$SubRec 			= false;
				$ClientId 			= 0; 

				$DdsDealerId 		= $this->getRequestParameter('dds_dealer_id');
				// Get the subscription id that was crated.
				$Query 				= "SELECT * FROM dds_subscription "
									. "WHERE dds_dealer_id = '{$DdsDealerId}' "
									. "AND customer_id = {$CustomerId} "
									. "AND brand_type = '{$BrandType}' ";
				$Rs 				= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$SubRec 		= $Rs->getRow();
				}
				$StartDate 			= date("Y-m-d");
				$EndDate 			= '2029-12-31';
				$TriggerName 		= 'Intelligent Mapping Auto Service';

				/// Get the client_id
				$Query 				= "SELECT client_id FROM customer WHERE customer_id = {$CustomerId} ";
				$Rs 				= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$ClientId 		= $Rs->get('client_id');
				}


				// Now we have the subscription record, let's set/update the mapping_trigger
				if ( $SubRec )
				{

					// Do we need to update the record or create a new one?
					$TrigRow 		= false;
					$Query 			= "SELECT * FROM intelligent_mapping_trigger "
									. "WHERE dds_subscription_id = {$SubRec['dds_subscription_id']} ";
					$Rs 			= $Conn->executeQuery($Query);
					while($Rs->next())
					{
						$TrigRow 	= $Rs->getRow();
					}

					if( $TrigRow )
					{
						// Update the record
						$TrigData 		= array(					
												);
						$Fields 		= array('client_id' 		=> $ClientId,
												'customer_id' 		=> $CustomerId,
												'CustTrigName' 		=> $TriggerName,
												'dds_subscription_id'	=> $SubRec['dds_subscription_id'],
												'data_json'			=> json_encode($TrigData),
												'start_date' 		=> $StartDate,
												'end_date' 			=> $EndDate,
												'intelligent_mapping_trigger_id' => $TrigRow['intelligent_mapping_trigger_id']
												);
						$UpdateTrigRecRaw 	= json_decode($AmmsCoreDDS->UpdateTriggerRec($TrigRow['intelligent_mapping_trigger_id'], $Fields), true);

						// echo "UpdateTrigRec  Fields = <pre>" . print_r($Fields, true) . "</pre><br />";
						// echo "UpdateTrigRecRaw =   <pre>" . print_r($UpdateTrigRecRaw, true) . "</pre><br />";

					} else {
						// Create a new record
						$TrigData 		= array(					
												);
						$Fields 		= array('client_id' 		=> $ClientId,
												'customer_id' 		=> $CustomerId,
												'CustTrigName' 		=> $TriggerName,
												'dds_subscription_id'	=> $SubRec['dds_subscription_id'],
												'data_json'			=> json_encode($TrigData),
												'start_date' 		=> $StartDate,
												'end_date' 			=> $EndDate
												);
						$NewTrigRecRaw 	= json_decode($AmmsCoreDDS->NewTriggerRec($Fields), true);

						// echo "NewTrigRec  Fields = <pre>" . print_r($Fields, true) . "</pre><br />";
						// echo "NewTrigRecRaw = <pre>" . print_r($NewTriggerRec, true) . "</pre><br />";
					}

				}

				// Do we need to add a new trigger detail?
				$newFilterNameId 				= intval($this->getRequestParameter('newfilter_filter_name_id'));
				$newFilterMailProductId 		= intval($this->getRequestParameter('newfilter_mail_product_id'));
				$newFilterEmailProductId 		= intval($this->getRequestParameter('newfilter_email_product_id'));
				if ( $newFilterNameId > 0 && $newFilterMailProductId > 0 )
				{

					// Find the max sequence
					$NewPosId 			= 1;
					$Query 				= "SELECT max(sequence_pos_id) as max_pos_id "
										. "FROM intelligent_mapping_trigger_detail "
										. "WHERE intelligent_mapping_trigger_id = {$TrigRow['intelligent_mapping_trigger_id']} ";
					$Rs 				= $Conn->executeQuery($Query);
					while($Rs->next())
					{
						$NewPosId 		= $Rs->get('max_pos_id');
						if ( $NewPosId == 0 )
							$NewPosId = 1;
					}

					$Fields 			= array(
											'intelligent_mapping_trigger_id' 		=> $TrigRow['intelligent_mapping_trigger_id'],
											'sequence_pos_id' 						=> $NewPosId,
											'intelligent_mapping_trigger_name_id' 	=> $newFilterNameId,
											'properties_json' 						=> json_encode(	
																								array()
																								),	
											'communication_json'					=> json_encode(
																								array('mail_product_id'	=> $newFilterMailProductId,
																									'email_id'			=> $newFilterEmailProductId,
																									'social_id' 		=> 0  )
																								),	
											'active_yn' 			=> 'Y'
											);
					// echo "New Detail Fields = <pre>" . print_r($Fields, true) . "</pre><br />";

					$NewDetailResult 	= $AmmsCoreDDS->NewTriggerDetailRec($Fields);
					// echo "NewDetailResult = <pre>" . print_r($NewDetailResult, true) . "</pre><br />";
				}
			}

		} else {
			// We need to supbscribe

			$Radius 				= $this->getRequestParameter('radius');
			$DdsDealerId 			= $this->getRequestParameter('dds_dealer_id');
			$CustomerId 			= $this->getRequestParameter('customer_id');
			$BrandType 				= 'AUTOSERVICE';

			$Result 	 			= json_decode($AmmsCoreDDS->EnrollDealer($CustomerId, $DdsDealerId, $Radius, $BrandType), true);

			// echo "Subscribe result: <pre>" . print_r($Result, true) . "</pre><br />";


		}



		// echo "Done with SaveIntelligentMappingAutoService()<br />\n";


		// die("Aborting\n");
	}



	/***
	`*
	`* Save SaveDealerX Filter
	`*
	`************************************************************************************************/
	public function SaveDealerX($TriggerSettingId)
	{


		$Conn 					= Propel::GetConnection();




		// echo "this->CustomerId = {$this->CustomerId}<br />\n";
		$CustomerRec 	= CustomerPeer::retrieveByPK($this->CustomerId);
		// echo "CustomerRec = <pre>" . print_r($CustomerRec, true) . "</pre><br />";
		$DxTrigId 		= $this->getRequestParameter('dx_trig_id');
		// echo "ScTrigId = {$ScTrigId}<br />\n";

		$ClientId 		= $CustomerRec->getClientId();
		if ( $_POST['newbucket_name'] != "" && intval($_POST['newbucket_template_id']) > 0 )
		{
			// We want to create a new dealerx_custoemr_trigger record - if it exists - set it back to active.

			$Query 		= "INSERT INTO dealerx_customer_trigger (`client_id`,`customer_id`,`template_id`,`name`,`data_json`,`start_date`,`end_date`,`active_yn`) "
						. "VALUES ({$ClientId},{$this->CustomerId}," . intval($_POST['newbucket_template_id']) . ", '" . addslashes($_POST['newbucket_name']) . "','',now(),'2029-12-31 23:59:59','Y') " 
						. "ON DUPLICATE KEY UPDATE active_yn=VALUES(active_yn) ";
			$Rs 		= $Conn->executeQuery($Query);
			
		}



		// Spin through the $_POST variables to dig out the new trigger filter
		$SearchKey 		= 'newfilter_filter_name_id_';
		$SearchKeyLen	= strlen($SearchKey);
		foreach($_POST as $key => $value)
		{
			if ( substr($key, 0, $SearchKeyLen) == $SearchKey && intval($value) > 0 )
			{
				$Dx_Cust_Trig_Id 	= substr($key, $SearchKeyLen, strlen($key) - $SearchKeyLen);
				$NewMailProductId 	= $_POST['newfilter_mail_product_id_' . $Dx_Cust_Trig_Id];
				$NewFilterId 		= $value;

				$Query 				= "SELECT max(sequence_pos_id) as max_pos_id FROM dealerx_customer_trigger_detail "
									. "WHERE dealerx_customer_trigger_id = {$Dx_Cust_Trig_Id} ";
				// echo "Query = {$Query}<br />\n";
				$Rs 				= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$MaxPosId 		= $Rs->get('max_pos_id');
				}		
				$MaxPosId++;	
				$CommRec 			= array('mail_product_id'	=> $NewMailProductId,
											'email_id'			=> 0,
											'social_id' 		=> 0,
											'chase_offset_days'	=> 0,
											'mail_chase_product_id'	=> 0
											);
				$Query 				= "INSERT INTO dealerx_customer_trigger_detail (`dealerx_customer_trigger_id`,`sequence_pos_id`,`dealerx_trigger_name_id`,`properties_json`,`communication_json`) "
									. "VALUES ({$Dx_Cust_Trig_Id},{$MaxPosId},{$NewFilterId},'[]','" . json_encode($CommRec) . "') ";
				// echo "Query = {$Query}<br />\n";
				$Rs 				= $Conn->executeQuery($Query);

			}
		}

		// Spin through and make sure the rest are updated as well

		$SearchKey 		= 'dx_detail_trigger_name_id_';
		$SearchKeyLen	= strlen($SearchKey);
		foreach($_POST as $key => $value)
		{
			if ( substr($key, 0, $SearchKeyLen) == $SearchKey && intval($value) > 0 )
			{
				$DetailId 			= substr($key, $SearchKeyLen, strlen($key) - $SearchKeyLen);

				$TriggerNameId 		= intval($value);
				$MailProductId 		= intval($_POST['dx_detail_mail_product_' . $DetailId]);
				$ChaseDays 			= intval($_POST['dx_detail_chase_days_' . $DetailId]);
				$ChaseProduct 		= intval($_POST['dx_detail_mail_chase_' . $DetailId]);

				$DetailRec 	= false;

				$Query 		= "SELECT * FROM dealerx_customer_trigger_detail "
							. "WHERE dealerx_customer_trigger_detail_id = {$DetailId} ";
				$Rs 		= $Conn->executeQuery($Query);
				while($Rs->next())
				{
					$DetailRec 	= $Rs->getRow();					
				}

				if ( $DetailRec )
				{
					$communications = json_decode($DetailRec['communication_json'], true);



					$communications['mail_product_id'] = $MailProductId;
					$communications['chase_offset_days'] = $ChaseDays;
					$communications['mail_chase_product_id'] = $ChaseProduct;

					$Query 			= "UPDATE dealerx_customer_trigger_detail SET "
									. "dealerx_trigger_name_id = {$TriggerNameId}, communication_json='" . addslashes(json_encode($communications)) . "' "
									. "WHERE dealerx_customer_trigger_detail_id = {$DetailId} "
									. "LIMIT 1 ";
					// echo "Query = {$Query}<br />\n";
				// echo "Query = {$Query}\n";
					$Rs 			= $Conn->executeQuery($Query);

				}

			}
		}


		// if ( $DxTrigId > 0 )
		// {
		// 	// Retrieve the old record
		// 	$Query 			= "SELECT * FROM dealerx_customer_trigger WHERE dealerx_customer_trigger_id = {$DxTrigId} ";
		// 	$Rs 			= $Conn->executeQuery($Query);

		// 	$TrigRec 		= false;
		// 	while($Rs->next())
		// 	{
		// 		$TrigRec 	= $Rs->getRow();
		// 	}

		// 	if ( $TrigRec )
		// 	{

		// 		$CustTrigName 	= addslashes($this->getRequestParameter('sc_name'));
		// 		$TrigData 	= json_decode($TrigRec['data_json'], true);
				

		// 		$Query 		= "UPDATE dealerx_customer_trigger SET data_json = '" . json_encode($TrigData) . "', name = '{$CustTrigName}' WHERE dealerx_customer_trigger_id = {$DxTrigId} LIMIT 1 ";
		// 		// echo "Query = {$Query}<br />\n";
		// 		$Rs 		= $Conn->executeQuery($Query);

		// 	}


		// 	if ( $_POST['newfilter_filter_name_id'] > 0 && $ScTrigId > 0 )
		// 	{
		// 		$NewFilterId 		= $_POST['newfilter_filter_name_id'];
		// 		$NewMailProductId 	= $_POST['newfilter_mail_product_id'];
		// 		$MaxPosId 			= 0;

		// 		// Get the max sequence
		// 		$Query 				= "SELECT max(sequence_pos_id) as max_pos_id FROM dealerx_customer_trigger_detail "
		// 							. "WHERE dealerx_customer_trigger_id = {$ScTrigId} ";
		// 		$Rs 				= $Conn->executeQuery($Query);
		// 		while($Rs->next())
		// 		{
		// 			$MaxPosId 		= $Rs->get('max_pos_id');
		// 		}		
		// 		$MaxPosId++;	
		// 		$CommRec 			= array('mail_product_id'	=> $NewMailProductId,
		// 									'email_id'			=> 0,
		// 									'social_id' 		=> 0
		// 									);
		// 		$Query 				= "INSERT INTO dealerx_customer_trigger_detail (`dealerx_customer_trigger_id`,`sequence_pos_id`,`dealerx_trigger_name_id`,`properties_json`,`communication_json`) "
		// 							. "VALUES ({$ScTrigId},{$MaxPosId},{$NewFilterId},'[]','" . addslashes(json_encode($CommRec)) . "') ";
		// 		// echo "Query = {$Query}<br />\n";
		// 		$Rs 				= $Conn->executeQuery($Query);
		// 	}


		// 	// die("Aborting\n");


		// } else {
		// 	// Create a new smart_channel_trigger record.


		// 	$StartDate 		= date("Y-m-d");
		// 	$EndDate 		= "2029-12-31";

		// 	$CustTrigName 	= addslashes($this->getRequestParameter('sc_name'));
		// 	$TrigData 		= array(
		// 							);
		// 	$Query 			= "INSERT INTO dealerx_customer_trigger (`client_id`,`customer_id`,`name`,`data_json`,`start_date`,`end_date`) "
		// 					. "VALUES ({$ClientId}, {$this->CustomerId}, '{$CustTrigName}', '" . addslashes(json_encode($TrigData)) . "','{$StartDate}','{$EndDate}') ";
		// 	// echo "Query = {$Query}<br />\n";
		// 	$Rs 			= $Conn->executeQuery($Query);

		// 	//$NewTriggerId 	= $Conn->lastInsertId();
		// 	$NewTriggerId 	= mysql_insert_id($Conn->getResource());

		// 	// echo "NewTriggerId = {$NewTriggerId}\n";

		// 	if ( $_POST['newfilter_filter_name_id'] > 0 && $NewTriggerId > 0 )
		// 	{
		// 		$NewFilterId 		= $_POST['newfilter_filter_name_id'];
		// 		$NewMailProductId 	= $_POST['newfilter_mail_product_id'];
		// 		$MaxPosId 			= 0;

		// 		// Get the max sequence
		// 		$Query 				= "SELECT max(sequence_pos_id) as max_pos_id FROM dealerx_customer_trigger_detail "
		// 							. "WHERE dealerx_customer_trigger_id = {$NewTriggerId} ";
		// 		// echo "Query = {$Query}<br />\n";
		// 		$Rs 				= $Conn->executeQuery($Query);
		// 		while($Rs->next())
		// 		{
		// 			$MaxPosId 		= $Rs->get('max_pos_id');
		// 		}		
		// 		$MaxPosId++;	
		// 		$CommRec 			= array('mail_product_id'	=> $NewMailProductId,
		// 									'email_id'			=> 0,
		// 									'social_id' 		=> 0
		// 									);
		// 		$Query 				= "INSERT INTO dealerx_customer_trigger_detail (`smartchannel_customer_trigger_id`,`sequence_pos_id`,`dealerx_trigger_name_id`,`properties_json`,`communication_json`) "
		// 							. "VALUES ({$NewTriggerId},{$MaxPosId},{$NewFilterId},'[]'." . json_encode($CommRec) . "') ";
		// 		// echo "Query = {$Query}<br />\n";
		// 		$Rs 				= $Conn->executeQuery($Query);
		// 	}


		// }

		// // Find the detail records and update
		// $KeyLen 			= strlen('sc_pixl_detail_trigger_name_id_');
		// foreach($_POST as $Key => $Value)
		// {
		// 	if ( substr($Key, 0, $KeyLen)  == 'sc_pixl_detail_trigger_name_id_' )
		// 	{
		// 		$DetailId 	= substr($Key, $KeyLen - strlen($Key) );
		// 		// echo "SmartChannel DetailId = {$DetailId}<br />";

		// 		$DetailRec 	= false;

		// 		$Query 		= "SELECT * FROM dealerx_customer_trigger_detail "
		// 					. "WHERE dealerx_customer_trigger_detail_id = {$DetailId} ";
		// 		$Rs 		= $Conn->executeQuery($Query);
		// 		while($Rs->next())
		// 		{
		// 			$DetailRec 	= $Rs->getRow();					
		// 		}

		// 		if ( $DetailRec )
		// 		{
		// 			$communications = json_decode($DetailRec['communication_json'], true);



		// 			$TriggerNameId 	= $_POST['sc_pixl_detail_trigger_name_id_' . $DetailId];
		// 			$MailProductId 	= $_POST['sc_pixl_detail_mail_product_' . $DetailId];



		// 			$communications['mail_product_id'] = $MailProductId;

		// 			$Query 			= "UPDATE dealerx_customer_trigger_detail SET "
		// 							. "dealerx_trigger_name_id = {$TriggerNameId}, communication_json='" . json_encode($communications) . "' "
		// 							. "WHERE dealerx_customer_trigger_detail_id = {$DetailId} "
		// 							. "LIMIT 1 ";
		// 			// echo "Query = {$Query}<br />\n";
		// 		// echo "Query = {$Query}\n";
		// 			$Rs 			= $Conn->executeQuery($Query);

		// 		}

		// 	}
		// }

		// $MoveMode 				= $this->getRequestParameter('move');

		// if ( strlen($MoveMode) > 0 )
		// {
		// 	$TrigDetail 		= $this->getRequestParameter('detail_id');
		// 	$SwitchDetailRow 	= false;


		// 	// Get the detail record
		// 	$Query 				= "SELECT * FROM dealerx_customer_trigger_detail "
		// 						. "WHERE dealerx_customer_trigger_detail_id = {$TrigDetail} ";
		// 			//	echo "Query = {$Query}<br />";
		// 	$Rs 				= $Conn->executeQuery($Query);
		// 	while($Rs->next())
		// 	{
		// 		$DetailRow 		= $Rs->getRow();
		// 	//	echo "DetailRow = <pre>" . print_r($DetailRow, true) . "</pre><br />";
		// 		$SequencePosId 	= $DetailRow['sequence_pos_id'];
		// 	}

		// 	// echo "MoveMode = {$MoveMode}<br />";
		// 	// die("Aborting\n");

		// 	// ToRec
		// 	switch($MoveMode)
		// 	{
		// 		case 'up':
		// 			$SwitchSeqPosId = $SequencePosId -1;
		// 			break;
		// 		case 'down':
		// 			$SwitchSeqPosId = $SequencePosId +1;
		// 			break;
		// 	}
		// 	// find the record we want to switch the position with
		// 	$Query 				= "SELECT * FROM dealerx_customer_trigger_detail "
		// 						. "WHERE dealerx_customer_trigger_id = {$DetailRow['dealerx_customer_trigger_id']} "
		// 						. "AND sequence_pos_id = {$SwitchSeqPosId} "
		// 						. "LIMIT 1 ";
		// 			//	echo "Query = {$Query}<br />";
		// 	$Rs 				= $Conn->executeQuery($Query);
		// 	while($Rs->next())
		// 	{
		// 		$SwitchDetailRow 	= $Rs->getRow();
		// 		// echo "SwitchDetailRow = <pre>" . print_r($SwitchDetailRow, true) . "</pre><br />";
		// 	}
		// 	if ( $SwitchDetailRow )
		// 	{
		// 		$Query 			= "UPDATE dealerx_customer_trigger_detail "
		// 						. "SET sequence_pos_id = {$SequencePosId} "
		// 						. "WHERE dealerx_customer_trigger_detail_id = {$SwitchDetailRow['dealerx_customer_trigger_detail_id']} ";
		// 			//	echo "Query = {$Query}<br />";
		// 		$Rs 			= $Conn->executeQuery($Query);

		// 		$Query 			= "UPDATE dealerx_customer_trigger_detail "
		// 						. "SET sequence_pos_id = {$SwitchSeqPosId} "
		// 						. "WHERE dealerx_customer_trigger_detail_id = {$DetailRow['dealerx_customer_trigger_detail_id']} ";
		// 			// 	echo "Query = {$Query}<br />";
		// 		$Rs 			= $Conn->executeQuery($Query);

		// 	}

		// }

	}



	/***
	`*
	`* Save SaveServiceNoWarranty Filter
	`*
	`************************************************************************************************/
	public function SaveServiceNoWarranty($TriggerSettingId)
	{
		// TODO: Save settings from UI
		$FilterId = $this->GetFilterId($TriggerSettingId, 60);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(60);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);
		$TriggerSettingFilter->setOpcodes(serialize($this->Get('opcodes')));
		$TriggerSettingFilter->save($this->dmstrigconn);

	}


	/***
	`*
	`* Save SaveStateInspection Filter
	`*
	`************************************************************************************************/
	public function SaveStateInspection($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 21);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(21);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setCustomerId($this->CustomerId);
		$TriggerSettingFilter->setOpcodes($this->Get('opcodes'));
		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save TimeAndMileage Filter
	`*
	`************************************************************************************************/
	public function SaveTimeAndMileage($TriggerSettingId)
	{
		$FilterId = $this->GetFilterId($TriggerSettingId, 1);

		if ($FilterId < 0)	$TriggerSettingFilter = $this->BuildEmptyFilter();
		else 				$TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);

		$TriggerSettingFilter->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilter->setFilterId(1);
		$TriggerSettingFilter->setCustomerId($this->CustomerId);

		if ($this->Get('timeandmileage') == 'simple')
			$TriggerSettingFilter->setTimeMileageType('SIMPLE');
		else
			$TriggerSettingFilter->setTimeMileageType('SERVICE PLAN');

		$TriggerSettingFilter->setCoupon21($this->Get("coupon2_1_service_reminder"));
		$TriggerSettingFilter->setCoupon22($this->Get("coupon2_2_service_reminder"));
		$TriggerSettingFilter->setCoupon11($this->Get("coupon1_1_return_reminder"));
		$TriggerSettingFilter->setCoupon12($this->Get("coupon1_2_return_reminder"));
		$TriggerSettingFilter->save($this->dmstrigconn);

		#$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 1, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		#$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));
	}


	/***
	`*
	`* Save SaveOilChangeOpCodes Filter
	`*
	`************************************************************************************************/
	public function SaveOilChangeOpCodes($TriggerSettingId)
	{
		$this->DoLog(__LINE__.": SaveOilChangeOpCodes(TriggerSettingId={$TriggerSettingId})");

		$FilterId = $this->GetFilterId($TriggerSettingId, 2);


		$this->DoLog(__LINE__.": SaveOilChangeOpCodes() FilterId = {$FilterId}");

		if ($FilterId < 0)	{
			$TriggerSettingFilterRec = $this->BuildEmptyFilter();
			$this->DoLog(__LINE__.": SaveOilChangeOpCodes() Creating empty record.");
			if ( $this->brand != 'DEFAULT')
			{
				$TriggerSettingFilterRec->setBrand($this->brand);
			$this->DoLog(__LINE__.": SaveOilChangeOpCodes() empty record setting brand = '{$this->brand}'.");
			}
		} else {
			$TriggerSettingFilterRec = TriggerSettingFilterPeer::retrieveByPK($FilterId, $this->dmstrigconn);
			$this->DoLog(__LINE__.": SaveOilChangeOpCodes() retrieving existing record.");
		}	

		$TriggerSettingFilterRec->setTriggerSettingId($TriggerSettingId);
		$TriggerSettingFilterRec->setFilterId(2);
		$TriggerSettingFilterRec->setActiveYn('Y');
		$TriggerSettingFilterRec->setCustomerId($this->CustomerId);
		$TriggerSettingFilterRec->setOpcodes($this->Get('opcodes'));
		$TriggerSettingFilterRec->setCoupon21($this->Get('coupon2_1_service_reminder'));
		$TriggerSettingFilterRec->setCoupon22($this->Get('coupon2_2_service_reminder'));
		$TriggerSettingFilterRec->setCoupon11($this->Get('coupon1_1_return_reminder'));
		$TriggerSettingFilterRec->setCoupon12($this->Get('coupon1_2_return_reminder'));
		$TriggerSettingFilterRec->save($this->dmstrigconn);

		// $sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 1, trigger_filter_id = 2, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "||TriggerSettingId={$TriggerSettingId}'";
		// $result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		// $this->DoLog(__LINE__.": SaveOilChangeOpCodes(TriggerSettingId={$TriggerSettingId})");
	}


	public function saveForm20()
	{
		die("Error: Unable to save");
	}


	public function saveForm31()
	{
		$this->form 				= intval($this->getRequestParameter('form'));
		$this->level 				= intval($this->getRequestParameter('level'));
		$this->customer_id 			= $this->getUser()->getAttribute('customer_id');
		$this->TriggerSettingId 	= TriggerSettingPeer::GetSettingId($this->customer_id,31, $this->dmstrigconn);

		if ($this->getRequestParameter('defaultenabled') == 1)
		$this->enabled = "Y";
		else $this->enabled = "N";

		//This file holds the arrays used to populate the Lease Expiration vehicle filter dropdowns
		###include "TriggerLEVData.php";

		$this->period = intval($this->getRequestParameter('defaultdelay')) + 1;
		$this->periodtype = "DAY";

		$this->returnmail = $this->getRequestParameter('defaultReturnReminderMail');
		//$this->email = $this->getRequestParameter('defaultVehicleEmail');

		$filterid = $this->getFilterId($this->TriggerSettingId,34, $this->level);

		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(34);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setBrand("DEFAULT");
		$this->TriggerSettingFilter->setEnabledYn($this->enabled);

		if ($this->level)
			$this->TriggerSettingFilter->setLevel($this->level);

		$this->TriggerSettingFilter->setNotificationPeriod($this->period);
		$this->TriggerSettingFilter->setNotificationPeriodType($this->periodtype);
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		//$this->TriggerSettingFilter->setEmail1($this->email);
		$this->TriggerSettingFilter->save($this->dmstrigconn);

		$sql = "INSERT INTO trigger_setting_log SET user_id = " . $this->curuser . ", change_date = '" . date('Y-m-d H:i:s') . "', customer_id = " . $this->customer_id . ", trigger_name_id = 31, trigger_filter_id = 34, log_data = '" . mysql_real_escape_string(serialize($this->TriggerSettingFilter)) . "'";
		$result = mysql_query($sql, $this->dmstrigsqlconn) or die(mysql_error($this->dmstrigsqlconn));

		$this->saveCommon();

		$this->redirect('TrigCustomer/TriggerController?nav=' . $this->form);
	}


	public function buildEmptyFilter()
	{

		$TriggerSettingFilter = new TriggerSettingFilter();

		$TriggerSettingFilter->setTriggerSettingId(0);
		$TriggerSettingFilter->setFilterId(0);
		$TriggerSettingFilter->setCustomerId (0);
		$TriggerSettingFilter->setBrand("DEFAULT");
		$TriggerSettingFilter->setLevel(1);
		$TriggerSettingFilter->setActiveYn('Y');
		$TriggerSettingFilter->setEnabledYn("Y");
		$TriggerSettingFilter->setMail11("");
		$TriggerSettingFilter->setMail21("");
		$TriggerSettingFilter->setEmail1("");
		$TriggerSettingFilter->setCoupon11("");
		$TriggerSettingFilter->setCoupon21("");
		$TriggerSettingFilter->setCoupon31("");
		$TriggerSettingFilter->setNotificationPeriod(0);
		$TriggerSettingFilter->setNotificationPeriodType("MONTH");
		$TriggerSettingFilter->setmail12("");
		$TriggerSettingFilter->setMail22("");
		$TriggerSettingFilter->setEmail2("");
		$TriggerSettingFilter->setCoupon12("");
		$TriggerSettingFilter->setCoupon22("");
		$TriggerSettingFilter->setCoupon32("");
		$TriggerSettingFilter->setMail13("");
		$TriggerSettingFilter->setMail23("");
		$TriggerSettingFilter->setCoupon13("");
		$TriggerSettingFilter->setCoupon23("");
		$TriggerSettingFilter->setCoupon33("");
		$TriggerSettingFilter->setTimeMileageType("simple");
		$TriggerSettingFilter->setOpcodes("");
		$TriggerSettingFilter->setPartsRecallDays(0);
		$TriggerSettingFilter->setPartsAfterSecondCall(0);
		$TriggerSettingFilter->setPartsFilterPartCodes("");
		$TriggerSettingFilter->setPartsCallRoOpcode("");
		$TriggerSettingFilter->setPartsFilterCountermen("");
		$TriggerSettingFilter->setPartsFilterCustomers("");
		$TriggerSettingFilter->setPartsSpecialOrderReturnDays(0);
		$TriggerSettingFilter->setSvcCompleteContact("");
		$TriggerSettingFilter->setSvcCompleteRentalReturnPeriod("");
		$TriggerSettingFilter->setFollowupCustPromptEnabledYn("N");
		$TriggerSettingFilter->setFollowupCustPromptGreeting("");
		$TriggerSettingFilter->setFollowupCustPromptVoicemail("");
		$TriggerSettingFilter->setFollowupCalltypeMode("");
		$TriggerSettingFilter->setFollowupCalltypeEmailOnly("");
		$TriggerSettingFilter->setFollowupCalltypeSurvey("");
		$TriggerSettingFilter->setFollowupCalltypeCsrEmail("");
		$TriggerSettingFilter->setFollowupCalltypeEmailResults("");
		$TriggerSettingFilter->setFollowupCalltypeQuestion1("");
		$TriggerSettingFilter->setFollowupCalltypeQuestion2("");
		$TriggerSettingFilter->setFollowupCalltypeQuestion3("");
		$TriggerSettingFilter->setFollowupSettingsContact("");
		$TriggerSettingFilter->setFollowupSettingsCustPay("");
		$TriggerSettingFilter->setFollowup21dayEnableYn("");
		$TriggerSettingFilter->setFollowup21dayPickupMessage("");
		$TriggerSettingFilter->setFollowup21dayMessageVoicemail("");
		$TriggerSettingFilter->setFollowupVehicleType("BOTH");
		$TriggerSettingFilter->setVehicleMakesInclude("");
		$TriggerSettingFilter->setVehicleMakesExclude("");
		$TriggerSettingFilter->setAsrProEnabledYn("N");
		$TriggerSettingFilter->setAsrRedRequiredYn("N");
		$TriggerSettingFilter->setRecommendationsEnabledYn("N");
		$TriggerSettingFilter->setRecommendationsAfterDate("0000-00-00");
		$TriggerSettingFilter->setRecommendationsIncludeText("");
		$TriggerSettingFilter->setRecoveryStateOnly("Y");
		$TriggerSettingFilter->setRecoveryOldestYear(0);
		$TriggerSettingFilter->setRecoveryMaxMonths(0);
		$TriggerSettingFilter->setStateInspectionRequired("");
		$TriggerSettingFilter->setWarrantyExpirationMileageZeroYn("Y");


		return $TriggerSettingFilter;
	}


	public function getFilterId($TriggerSettingId,$FilterId,$Level=0)
	{

		$IgnoreBrandFilterIds 	= array(19);
		$this->customer_id = $this->getUser()->getAttribute('customer_id');
		$this->DoLog(__LINE__.": getFilterId(TriggerSettingId={$TriggerSettingId},FilterId={$FilterId},Level={$Level}");
		$this->DoLog(__LINE__.": getFilterId() this->customer_id = {$this->customer_id}");
		$this->DoLog(__LINE__.": getFilterId() this->brand = {$this->brand}");

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,$FilterId);
		// 2016-04-27 Peter We must also search on brand
		if (!empty($this->brand) && !in_array($FilterId, $IgnoreBrandFilterIds)) $C->add(TriggerSettingFilterPeer::BRAND,$this->brand);
		if ($Level >0) $C->add(TriggerSettingFilterPeer::LEVEL,$Level);
		// 2016-04-27 Peter If Contract is supplied, search for that in setting_1 field
		if (!empty($this->contract)) $C->add(TriggerSettingFilterPeer::SETTING_1,$this->contract);

		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$this->DoLog(__LINE__.": getFilterId() filterrs = " . print_r($filterrs, true) );
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );

		$this->DoLog(__LINE__.": getFilterId() getRecordCount = " . $filterrs->getRecordCount() );
		if ($filterrs->getRecordCount() <= 0) return -1;
		else
		{
			$filterrs->next();
			$row = $filterrs->getRow();
		$this->DoLog(__LINE__.": getFilterId() row = " . print_r($row, true) );
			return $row["TRIGGER_SETTING_FILTER_ID"];
		}
	}


	public function addServiceFilter($make,$enabled,$mail,$opcodes,$delay,$level)
	{
		$this->returnmail = $mail;
		$this->opcodes = $opcodes;
		$this->TriggerSettingId = TriggerSettingPeer::GetSettingId($this->customer_id, $this->form, $this->dmstrigconn);

		$this->timing = $this->delaySelect[$delay];

		$this->period = intval($this->timing);
		if (stripos($this->timing,'HOUR') !== false) $this->periodtype = "HOUR";
		if (stripos($this->timing,'DAY') !== false) $this->periodtype = "DAY";
		if (stripos($this->timing,'WEEK') !== false) $this->periodtype = "WEEK";
		if (stripos($this->timing,'MONTH') !== false) $this->periodtype = "MONTH";
		$filterid = $this->getDeclinedRepairFilterId($this->TriggerSettingId,18,$level,$make);
		if ($filterid < 0)
		$this->TriggerSettingFilter = $this->buildEmptyFilter();
		else $this->TriggerSettingFilter = TriggerSettingFilterPeer::retrieveByPK($filterid,$this->dmstrigconn);
		$this->TriggerSettingFilter->setTriggerSettingId($this->TriggerSettingId);
		$this->TriggerSettingFilter->setFilterId(18);
		$this->TriggerSettingFilter->setCustomerId($this->customer_id);
		$this->TriggerSettingFilter->setLevel($level);
		$this->TriggerSettingFilter->setBrand($make);
		$this->TriggerSettingFilter->setNotificationPeriod($this->period);
		$this->TriggerSettingFilter->setNotificationPeriodType($this->periodtype);
		if ($this->returnmail) { $this->TriggerSettingFilter->setMail11($this->returnmail); }
		$this->TriggerSettingFilter->setOpcodes($this->opcodes);
		$this->TriggerSettingFilter->setEnabledYn($enabled);

		$this->TriggerSettingFilter->save($this->dmstrigconn);
	}


	public function getDeclinedRepairFilterId($TriggerSettingId,$FilterId,$level,$make)
	{
		$this->customer_id = $this->getUser()->getAttribute('customer_id');

		$C = new Criteria();
		$C->addSelectColumn(TriggerSettingFilterPeer::TRIGGER_SETTING_FILTER_ID);
		$C->add(TriggerSettingFilterPeer::TRIGGER_SETTING_ID,$TriggerSettingId);
		$C->add(TriggerSettingFilterPeer::CUSTOMER_ID,$this->customer_id);
		$C->add(TriggerSettingFilterPeer::FILTER_ID,$FilterId);
		$C->add(TriggerSettingFilterPeer::LEVEL,$level);
		$C->add(TriggerSettingFilterPeer::BRAND,$make);
		$filterrs = TriggerSettingFilterPeer::doSelectRs($C,$this->dmstrigconn);
		$filterrs->setFetchMode( ResultSet::FETCHMODE_ASSOC );

		if ($filterrs->getRecordCount() <= 0) return -1;
		else
		{
			$filterrs->next();
			$row = $filterrs->getRow();
			return $row["TRIGGER_SETTING_FILTER_ID"];
		}
	}


	public function getBirthday($customer_id,$conn)
	{
		$C = new Criteria();
		$C->add(DmsConsumerPeer::EXTERNAL_CUSTOMER_ID,$customer_id);
		$cust = DmsConsumerPeer::doSelectOne($C,$conn);
		return $cust->getBirthday();
	}


	public function getFollowupCalltypeQuestions($trig)
	{
		$arr = array();
		$qs = unserialize($trig->getPartsFilterCustomers());
	    return $qs;
	}


	/*
		explodeEmails(string)
		returns: Array()

		Accepts either a comma seperated list of emails, or a space seperated list of emails
		Returns an Array of emails that have been trimmed
	*/
	public function explodeEmails($the_emails)
	{
		$out = array();
		if (strpos($the_emails, ",")) {
			$tarr = explode(",",$the_emails);
		} else {
			$tarr = explode(" ", $the_emails);
		}
		for ($i=0;$i<count($tarr);$i++) {
			$c = trim($tarr[$i]);
			if (strpos($c, "@") > 0) {
				$out[] = $c;
			 }
		}
		return $out;
	}


	public function findSalesman($loop_sales_person_id)
	{
		$CDmsd = new Dmsd();
		$dms_master_conn	= $CDmsd->GetDmsDbConn($this->customer_id);
		$c = new Criteria();
		$c->add(DmsEmployeePeer::DMS_ID, $loop_sales_person_id);
		$employee = DmsEmployeePeer::doSelectOne($c, $dms_master_conn);
		if ($employee) {
			$ename =  $employee->getEmployeeName();
			preg_match("/[0-9]*/", $ename, $reg);
			$splts = explode(" ", $ename);
			$ret = true;
			foreach ($splts as $splt) {
				if (ctype_digit($splt)) {
					$ret = false;
				}
			}

			if ($ret) {
				return $ename;
			}
		}

		return false;
	}


	public function setFollowupCalltypeQuestions($TriggerSettingFilter=false)
	{
		$arr = array();
		// $fncb is the base name of the Function to Call... we will append the Number for each question
		$fncb = "setFollowupCalltypeQuestion";
		$q1 = "N";
		$q2 = "N";
		$q3 = "N";
		$surveyemail = array();
		$estr = $this->getRequestParameter("surveyemail");

		$responsetypes = 0;
		//die($this->getRequestParameter("question1_yn") );
		if ($this->getRequestParameter("question1_yn") == "1") { $q1 = "Y"; }
		if ($this->getRequestParameter("question2_yn") == "1") { $q2 = "Y"; }
		if ($this->getRequestParameter("question3_yn") == "1") { $q3 = "Y"; }
		$qs = array("question1_text" => $this->substituteTags($this->getRequestParameter("question1_text")),
			"question2_text" => $this->substituteTags($this->getRequestParameter("question2_text")),
			"question3_text" => $this->substituteTags($this->getRequestParameter("question3_text")),
			"question1_yn" => $q1,
			"question2_yn" => $q2,
			"question3_yn" => $q3,
			"calltype" => $this->getRequestParameter("calltype"),
			"standard_yn" => "N",
			'responseType' => $this->getRequestParameter('survey'),
			"emails" => $this->explodeEmails($estr),
			"standard_text" => $this->substituteTags($this->getRequestParameter("standard_text"))
		);
		$ser = serialize($qs);

		if ($TriggerSettingFilter)
			$TriggerSettingFilter->setPartsFilterCustomers($ser);
		else
			$this->TriggerSettingFilter->setPartsFilterCustomers($ser);
	}


	public function substituteTags($txt)
	{
		//$txt = str_replace("{DEALERSHIP_NAME}", $this->customer_name, $txt);
		return $txt;
	}


	public function MoveSmartchannelDetail($SmartchannelCustomerTriggerDetailId=0, $MoveDir='')
	{

		$Conn 			= Propel::GetConnection();
		// Load the detail
		$Query 			= "SELECT * FROM smartchannel_customer_trigger_detail "
						. "WHERE smartchannel_customer_trigger_detail_id = {$SmartchannelCustomerTriggerDetailId}";
		$Rs 			= $Conn->executeQuery($Query);
		while($Rs->next())
		{
			$DetailRow 		= $Rs->getRow();
			$SequencePosId 	= $DetailRow['sequence_pos_id'];
		}

		switch($this->getRequestParameter('move'))
		{
			case 'up':
				$SwitchSeqPosId = $SequencePosId -1;
				break;
			case 'down':
				$SwitchSeqPosId = $SequencePosId +1;
				break;
		}


		
		// find the record we want to switch the position with
		$Query 				= "SELECT * FROM smartchannel_customer_trigger_detail "
							. "WHERE smartchannel_customer_trigger_id = {$DetailRow['smartchannel_customer_trigger_id']} "
							. "AND sequence_pos_id = {$SwitchSeqPosId} "
							. "LIMIT 1 ";
				//	echo "Query = {$Query}<br />";
		$Rs 				= $Conn->executeQuery($Query);
		while($Rs->next())
		{
			$SwitchDetailRow 	= $Rs->getRow();
			// echo "SwitchDetailRow = <pre>" . print_r($SwitchDetailRow, true) . "</pre><br />";
		}
		if ( $SwitchDetailRow )
		{
			$Query 			= "UPDATE smartchannel_customer_trigger_detail "
							. "SET sequence_pos_id = {$SequencePosId} "
							. "WHERE smartchannel_customer_trigger_detail_id = {$SwitchDetailRow['smartchannel_customer_trigger_detail_id']} ";
				//	echo "Query = {$Query}<br />";
			$Rs 			= $Conn->executeQuery($Query);

			$Query 			= "UPDATE smartchannel_customer_trigger_detail "
							. "SET sequence_pos_id = {$SwitchSeqPosId} "
							. "WHERE smartchannel_customer_trigger_detail_id = {$DetailRow['smartchannel_customer_trigger_detail_id']} ";
				// 	echo "Query = {$Query}<br />";
			$Rs 			= $Conn->executeQuery($Query);

		}
	}




	public function MoveIntelligentMappingDetail($IntelligentMappintTriggerDetailId=0, $MoveDir='')
	{

		$Conn 			= Propel::GetConnection();
		// Load the detail
		$Query 			= "SELECT * FROM intelligent_mapping_trigger_detail "
						. "WHERE intelligent_mapping_trigger_detail_id = {$IntelligentMappintTriggerDetailId}";
		$Rs 			= $Conn->executeQuery($Query);
		while($Rs->next())
		{
			$DetailRow 		= $Rs->getRow();
			$SequencePosId 	= $DetailRow['sequence_pos_id'];
		}

		switch($this->getRequestParameter('move'))
		{
			case 'up':
				$SwitchSeqPosId = $SequencePosId -1;
				break;
			case 'down':
				$SwitchSeqPosId = $SequencePosId +1;
				break;
		}


		// find the record we want to switch the position with
		$Query 				= "SELECT * FROM intelligent_mapping_trigger_detail "
							. "WHERE intelligent_mapping_trigger_detail_id = {$DetailRow['intelligent_mapping_trigger_detail_id']} "
							. "AND sequence_pos_id = {$SwitchSeqPosId} "
							. "LIMIT 1 ";
				//	echo "Query = {$Query}<br />";
		$Rs 				= $Conn->executeQuery($Query);
		while($Rs->next())
		{
			$SwitchDetailRow 	= $Rs->getRow();
			// echo "SwitchDetailRow = <pre>" . print_r($SwitchDetailRow, true) . "</pre><br />";
		}
		if ( $SwitchDetailRow )
		{
			$Query 			= "UPDATE intelligent_mapping_trigger_detail "
							. "SET sequence_pos_id = {$SequencePosId} "
							. "WHERE intelligent_mapping_trigger_detail_id = {$SwitchDetailRow['intelligent_mapping_trigger_detail_id']} ";
				//	echo "Query = {$Query}<br />";
			$Rs 			= $Conn->executeQuery($Query);

			$Query 			= "UPDATE intelligent_mapping_trigger_detail "
							. "SET sequence_pos_id = {$SwitchSeqPosId} "
							. "WHERE intelligent_mapping_trigger_detail_id = {$DetailRow['intelligent_mapping_trigger_detail_id']} ";
				// 	echo "Query = {$Query}<br />";
			$Rs 			= $Conn->executeQuery($Query);

		}
		
	}




	public function MoveDealerXDetail($DealerXCustomerTriggerDetailId=0, $MoveDir='')
	{

		$Conn 			= Propel::GetConnection();
		// Load the detail
		$Query 			= "SELECT * FROM dealerx_customer_trigger_detail "
						. "WHERE dealerx_customer_trigger_detail_id = {$DealerXCustomerTriggerDetailId}";
				//	echo "Query = {$Query}<br />";
		$Rs 			= $Conn->executeQuery($Query);
		while($Rs->next())
		{
			$DetailRow 		= $Rs->getRow();
			$SequencePosId 	= $DetailRow['sequence_pos_id'];
		}

		switch($this->getRequestParameter('move'))
		{
			case 'up':
				$SwitchSeqPosId = $SequencePosId -1;
				break;
			case 'down':
				$SwitchSeqPosId = $SequencePosId +1;
				break;
		}
		

		// find the record we want to switch the position with
		$Query 				= "SELECT * FROM dealerx_customer_trigger_detail "
							. "WHERE dealerx_customer_trigger_id = {$DetailRow['dealerx_customer_trigger_id']} "
							. "AND sequence_pos_id = {$SwitchSeqPosId} "
							. "LIMIT 1 ";
				// echo "Query = {$Query}<br />";
		$Rs 				= $Conn->executeQuery($Query);
		while($Rs->next())
		{
			$SwitchDetailRow 	= $Rs->getRow();
			// echo "SwitchDetailRow = <pre>" . print_r($SwitchDetailRow, true) . "</pre><br />";
		}
		if ( $SwitchDetailRow )
		{
			$Query 			= "UPDATE dealerx_customer_trigger_detail "
							. "SET sequence_pos_id = {$SequencePosId} "
							. "WHERE dealerx_customer_trigger_detail_id = {$SwitchDetailRow['dealerx_customer_trigger_detail_id']} ";
				//	echo "Query = {$Query}<br />";
			$Rs 			= $Conn->executeQuery($Query);

			$Query 			= "UPDATE dealerx_customer_trigger_detail "
							. "SET sequence_pos_id = {$SwitchSeqPosId} "
							. "WHERE dealerx_customer_trigger_detail_id = {$DetailRow['dealerx_customer_trigger_detail_id']} ";
				// 	echo "Query = {$Query}<br />";
			$Rs 			= $Conn->executeQuery($Query);

		}
	}
}
