﻿/// <reference path="../../../../jQuery/1.3.2/jquery-1.3.2-vsdoc.js" />

/**
*
* Results
*
* This class used to manage the results page of the Uvl-Lite application
*
*/

// Check that namespace into which the Class definition will be creates has been defined & if not then create

if (!mrm.global.isNamespaceDefined("mrm.cms.display")) mrm.global.createNamespace("mrm.cms.display", "1.0");

mrm.cms.display.SearchCriteria = Object.subClass
(
	{
		/*
		=============================
		CONSTANTS
		=============================
		*/
		//CONST_POSTCODE_REGEX: /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/g,
		CONST_POSTCODE_REGEX: /^(GIR|[A-Z]\d[A-Z\d]?|[A-Z]{2}\d[A-Z\d]?)[ ]??(\d[A-Z]{0,2})??$/i,		
		POSTBACK_ACTION: "?wflw=se_na_ne",
		POSTBACK_WORKFLOW: "se_na_ne",
		SUBMIT_ACTION: "?wflw=se_na_se",
		SUBMIT_WORKFLOW: "se_na_se",
		DISABLED: "disabled",
		NULL: "null",
		ACTION: "action",
		UK: "UK",
		AJAX_MANAGER: null,
		HANDLER_URL: "/Handlers/WorkflowAsyncHandler.ashx",
		ARGUMENT_WORKFLOW: "wflw",
		SELECTOR_DATA_INPUTS: "input:text.mp-control-data, select.mp-control-data, input:checked.mp-control-data, input:selected.mp-control-data, input[type = 'hidden'].mp-control-data",
		SEARCH_CRITERIA_CONTAINER_SELECTOR: ".search-criteria-container",
		CONTROL_NAME: "SearchCriteria",

		/*
		=============================
		CONSTRUCTOR
		=============================
		*/
		"init": function () {
			//find the multi manufacturer search container and form
			var container = $(document).find('div.search-criteria-container');
			var form = container.find('form#frmSearchCriteriaForm');

			//Temporary solution for postoce until DB updated for ROI postcodes.			
			this.BindPostCodeInput(form);
			var budgetForm = $(document).find('form#frmBudgetCalculator');
			this.BindPostCodeInput(budgetForm);

			//bind the form action
			this.BindForm(form);

			//bvind the search button
			this.BindSearchButton(form);

			// set default ajax manager
			if ($.ajaxManager) {
				this.AJAX_MANAGER = $.ajaxManager;
			}
		},

		/*
		=============================
		METHODS
		=============================
		*/

		"BindPostCodeInput": function(form) {			
			var _this = this;
			var postcodeInput = form.find('input.postcode');			
			var postcodeStatus = postcodeInput.parents('div.dyanmiclookuplist-container').find('div.lookup-status');;

			postcodeInput.keypress(function () {
				var postcode = postcodeInput.val();
				if (_this.validatePostcode(postcode))
				{
					postcodeStatus.removeClass('lookup-invalid');
					postcodeStatus.addClass('lookup-valid');
				}
				else
				{
					postcodeStatus.removeClass('lookup-valid');
					postcodeStatus.addClass('lookup-invalid');					
				}
			});
		},

		"BindForm": function (form) {
			this.BindTypeManufacturerRangeFunctionality(form);
			this.BindCountryFunctionality(form);
		},

		"BindCountryFunctionality": function (form) {
			var _this = this;
			var countrySelect = form.find('select.country');

			if (countrySelect.val() != _this.UK) {
				_this.EnableROISearch(form);
			}

			countrySelect.change(function () {
				if (countrySelect.val() == _this.UK) {
					_this.EnableUKSearch(form);
				}
				else {
					_this.EnableROISearch(form);
				}
			});
		},

		"EnableUKSearch": function (form) {
			var _this = this;
			var postcodeInputContainer = form.find('input.postcode').parents('.control-container');
			var distanceSelectContainer = form.find('select.distance').parents('.control-container');

			//show the postcode and distance container items
			postcodeInputContainer.show();
			distanceSelectContainer.show();
		},

		"EnableROISearch": function (form) {
			var _this = this;
			var postcodeInputContainer = form.find('input.postcode').parents('.control-container');
			var distanceSelectContainer = form.find('select.distance').parents('.control-container');
			var distanceSelect = distanceSelectContainer.find('select.distance');

			//hide the controls
			postcodeInputContainer.hide();
			distanceSelectContainer.hide();

			//set the distance to national
			distanceSelect.val('1000');
		},

		"BindTypeManufacturerRangeFunctionality": function (form) {
			var _this = this;
			var vehicleTypeSelect = form.find('select.vehicletype');
			var manufacturerSelect = form.find('select.manufacturer');
			var rangeSelect = form.find('select.ranges');

			//rebind the action to be a postback in this case
			form.attr(_this.ACTION, this.POSTBACK_ACTION);

			//enable and disable the required selects
			if (manufacturerSelect.val() == _this.NULL) {
				_this.DisableSelect(rangeSelect);
			}

			//bind up the autopostback functionality on the manufacturer & VehicleType select
			_this.BindAutoPostback(vehicleTypeSelect, form, [manufacturerSelect, rangeSelect]);
			_this.BindAutoPostback(manufacturerSelect, form, [rangeSelect]);
		},

		"BindAutoPostback": function (selectControl, form, controlsToResetArray) {
			//scope
			var _this = this;

			//we need to make an ajax call to re-render out then search criteria view control

			//create the autopostback functionality
			selectControl.change(function (jqEvent) {
				jqEvent.stopImmediatePropagation();

				// setup ajax call
				_this.AJAX_MANAGER.clearArguments();

				//set the workflow argument
				_this.AJAX_MANAGER.ajaxSettings.arguments.add(_this.ARGUMENT_WORKFLOW, _this.POSTBACK_WORKFLOW);

				// add search criteria arguments to ajax call
				form.find(_this.SELECTOR_DATA_INPUTS).each(
					function () {
						var jqInputElement = $(this);
						_this.AJAX_MANAGER.ajaxSettings.arguments.add(jqInputElement.attr("name"), jqInputElement.val());
					}
				);

				// set the base url for the handler
				_this.AJAX_MANAGER.ajaxSettings.requestUrl = _this.HANDLER_URL;

				// set url
				_this.AJAX_MANAGER.updateUrl(_this.AJAX_MANAGER.ajaxSettings.arguments.getString("&"));

				// bind before send
				_this.AJAX_MANAGER.onBeforeSend =
				function () {
					_this.onSyncBefore(jqEvent);
				};

				// bind error
				_this.AJAX_MANAGER.onError =
				function (XMLHttpRequest, textStatus, errorThrown) {
					_this.onSyncError(jqEvent, XMLHttpRequest, textStatus, errorThrown);
				};

				// bind success
				_this.AJAX_MANAGER.onSuccess =
				function (p_response) {
					_this.onSyncSuccess(jqEvent, p_response);
				};

				// fire ajax request
				_this.AJAX_MANAGER.makeRequest();
			});
		},

		"DisableSelect": function (selectControl) {
			//scope
			var _this = this;

			selectControl.attr(_this.DISABLED, _this.DISABLED);
			selectControl.val(_this.NULL);
		},

		"BindSearchButton": function (form) {
			//scope
			var _this = this;

			//find the search button
			var button = form.find('button.btn-search');
			var postcodeInput = form.find('input.postcode');
			var countrySelect = form.find('select.country');
			var stockCountContainer = form.find('span.mp-stock-count');
			var errorSummaryContainer = form.find('div.error-summary');
			var postcodeError = errorSummaryContainer.find('span.postcode.error');
			var stockCountError = errorSummaryContainer.find('span.error.stock-count');
			var postcodeContainer = postcodeInput.parents('div.dyanmiclookuplist-container');

			//bind up the click event
			button.click(function (event) {
				//stop the default action from occurring
				event.preventDefault();

				//reset errors be re-evaluating
				postcodeError.addClass('none');
				errorSummaryContainer.addClass('none');
				stockCountError.addClass('none');

				//is PC validation required?
				var pcValidationRequired = (countrySelect.val() == _this.UK);

				//attempt to validate the postcode and stock count
				var stockCount = stockCountContainer.html().replace(/^\s+|\s+$/g, ""); //get html with whitespace trimmed

				var postcode = postcodeInput.val();				
				//var postcodeValid = ((_this.validatePostcode(postcode) && !postcodeContainer.hasClass('fieldError')) || !pcValidationRequired);
				//var postcodeValid = (!(postcode == "") && !postcodeContainer.hasClass('fieldError')) || !pcValidationRequired;
				var postcodeValid = (_this.validatePostcode(postcode) || !pcValidationRequired);

				if (postcodeValid && stockCount != "0") {					
					//rebind the action to be a submit then fire it
					form.attr(_this.ACTION, _this.SUBMIT_ACTION);
					form.submit();
				}
				else {
					errorSummaryContainer.removeClass('none');

					if (!postcodeValid) {
						postcodeError.removeClass('none');
					}

					if (stockCount == "0") {
						stockCountError.removeClass('none');
					}
				}
			});
		},

		"validatePostcode": function (postcode)
		{
			var re = this.CONST_POSTCODE_REGEX;
			return re.test(postcode);
		},

		/*
		=============================
		AJAX SYNC METHODS
		=============================
		*/

		"onSyncBefore": function (jqEvent) {
			//setup the UI elements and scope pointer
			var _this = this;
			var searchCriteriaContainer = $(this.SEARCH_CRITERIA_CONTAINER_SELECTOR);

			//set the visibility on the UI elements
			searchCriteriaContainer.css('opacity', '0.2');
		},

		"onSyncError": function (jqEvent, XMLHttpRequest, textStatus, errorThrown) {
			//handle an error			
			window.location.replace("/uvl/timeout.aspx");
		},

		"onSyncSuccess": function (jqEvent, p_response) {
			//scope pointer
			var _this = this;

			//check we have a valid response
			if (!p_response || !p_response.controls) return;

			//iterate the controls collection to output the controls to the page
			for (var i = 0; i <= p_response.controls.length; i++) {
				//get the controls ajax object from the returned collection
				var control = p_response.controls[i];

				//if control is set
				if (control) {
					//only process the search criteria control
					if (control.controlName == _this.CONTROL_NAME) {

						//locate the target dom element
						var target = $(control.targetDomId);

						//if we have located the target then output the html
						if (target.length > 0) {
							//output the new html
							target.html(control.content);

							//rebind the ajax calls
							var form = $('form#frmSearchCriteriaForm');

							//Temporary solution for postoce until DB updated for ROI postcodes.			
							_this.BindPostCodeInput(form);
							var budgetForm = $(document).find('form#frmBudgetCalculator');
							_this.BindPostCodeInput(budgetForm);

							_this.BindForm(form);							
							_this.BindSearchButton(form);

							//rebind the html list items	
							mrm.global.utilities.defaultControlBinder.bindControls();

							// Setup runtime namespace if doesn't exist
							if (!mrm.global.isNamespaceDefined("mrm.donnellyGroup.run.utilities")) mrm.global.createNamespace("mrm.donnellyGroup.run.utilities", "1.0");

							// Create instance
							mrm.donnellyGroup.run.utilities.LinkEnhancer = new mrm.lib.utilities.LinkEnhancer(true, false, true, true);

							//re-sIFR
							sIFR.replaceCoreAssets();
						}
					}
				}
			}
		}
	}
);
