// var AdvancedSearch = null;

// Register the namespace for AdvancedSearch.
Type.registerNamespace('Reynolds.CL.Web');

// Setup the NewUsedChecks enum.
Reynolds.CL.Web.NewUsedChecks = function(){};
Reynolds.CL.Web.NewUsedChecks.prototype = {
	New 	  : 1,
	Used 	  : 2,
	Certified : 4,
	All 	  : 7
}

Reynolds.CL.Web.NewUsedChecks.registerEnum("Reynolds.CL.Web.NewUsedChecks");

function showAdvancedSearch()
{
	if(!javaLoaded){return;}

	ShowAdvancedSearch();
}

function showAdvancedSearchWithDefaults(makeID, typeValue)
{
	if(!javaLoaded){return;}

	//set make
	if (!isNaN(parseInt(makeID))) {
		AdvancedSearch.selectMake(parseInt(makeID));
	}

	//set vehicle type
	AdvancedSearch.set_lotType(typeValue);

	//show popup
	ShowAdvancedSearch();
}

function hideAdvancedSearch()
{
	AdvancedSearch.hide();
}

var _showAdvancedSearchHandler = null;
function ShowAdvancedSearch()
{
	if(!javaLoaded) {
		_showAdvancedSearchHandler = Function.createDelegate(this, ShowAdvancedSearch);
		Sys.Application.add_load(_showAdvancedSearchHandler);
	}
	else {
		if (_showAdvancedSearchHandler) {
			Sys.Application.remove_load(_showAdvancedSearchHandler);
			_showAdvancedSearchHandler = null;
		}
		if (AdvancedSearch.show) AdvancedSearch.show();
	}
}

Reynolds.CL.Web.AdvancedSearch = function(element) {
	Reynolds.CL.Web.AdvancedSearch.initializeBase(this, [element]);

	// Properties
	this._tabs = null;
	this._selectedTabId = null;
	this._avZipWM = "Enter ZIP";
	this._lotType = Reynolds.CL.Web.NewUsedChecks.All;
	this._zipTextBox = null;
	this._buttonIds = null;
	this._advancedSS = null;
	this._selectedCategories = '';
	this._hiddenFieldIds = null;
	this._elements = null;
	this._searchVehicle = null;
	this._openDDL = null;

	// Handlers
	this._pageRequestManager = null;
    this._pageBeginRequestHandler = null;
    this._pageEndRequestHandler = null;
	this._checkKeyHandler = null;
	this._zipOnFocusHandler = null;
	this._zipOnBlurHandler = null;
	this._dealerOnClick = null;
}

// Create the prototype for AdvancedSearch.
Reynolds.CL.Web.AdvancedSearch.prototype = {
    initialize : function() {
		Reynolds.CL.Web.AdvancedSearch.callBaseMethod(this, 'initialize');

		// Set up properties
		advClientId = this.get_id();

		// Set up events
        this._pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
        this._pageBeginRequestHandler = Function.createDelegate(this, this._onBeginRequest);
        this._pageEndRequestHandler = Function.createDelegate(this, this._onEndRequest);

		if (this._pageRequestManager != null) {
            this._pageRequestManager.add_beginRequest(this._pageBeginRequestHandler);
            this._pageRequestManager.add_endRequest(this._pageEndRequestHandler);
        }

		this._checkKeyHandler = Function.createDelegate(this, this._onAdvSearchKeyPress);
		$addHandler(this.get_element(), 'keypress', this._checkKeyHandler);

		this._zipOnFocusHandler = Function.createDelegate(this, this._onZipFocus);
		this._zipOnBlurHandler = Function.createDelegate(this, this._onZipBlur);
		$addHandlers(this.get_zipTextBox(), {
			'focus' : this._zipOnFocusHandler,
			'blur' : this._zipOnBlurHandler },
			this);

		if (null != this.get_elements().CheckDealer) {
			this._dealerOnClick = Function.createDelegate(this, this._onDealerClick);
			$addHandler(this.get_elements().CheckDealer, 'click', this._dealerOnClick);
		}

		// Initialize Zip and Tabs.
		this._onZipBlur();
		this._setHiddenFieldValue("VehicleTypes", this.get_selectedCategories());

		// Set global accessor
		AdvancedSearch = this;
	},

	dispose : function() {
		$clearHandlers(this.get_element());

		if (this._pageRequestManager) {
            if (this._pageBeginRequestHandler) {
                this._pageRequestManager.remove_beginRequest(this._onBeginRequest);
                this._pageEndRequestHandler = null;
            }
            if (this._pageEndRequestHandler) {
                this._pageRequestManager.remove_endRequest(this._onEndRequest);
                this._pageEndRequestHandler = null;
            }
            this._pageRequestManager = null;
        }

		$clearHandlers(this.get_zipTextBox());

		if (this._dealerOnClick) {
			$removeHandler(this.get_elements().CheckDealer, 'click', this._dealerOnClick);
			this._dealerOnClick = null;
		}

		Reynolds.CL.Web.AdvancedSearch.callBaseMethod(this, 'dispose');
	},

	// Public Methods
	changeTab : function(tabName) {
		var tabCount = this.get_tabs().length;
		var prevTab = null;
		var foundTab = false;

		for (var i = 0; i < tabCount; i++) {
			if (this.get_tabs()[i].selected) prevTab = this.get_tabs()[i];

			if ((null == tabName && this.get_tabs()[i].selected) || this.get_tabs()[i].name == tabName)
			{
				this._setTabVisibility(this.get_tabs()[i], true);
				foundTab = true;
			}
			else
			{
				this._setTabVisibility(this.get_tabs()[i], false);
			}
		}

		// The tabName was invalid, show the previous tab or the first tab.
		if (!foundTab) {
			if  (prevTab)
				this._setTabVisibility(prevTab, true);
			else
				this._setTabVisibility(this.get_tabs()[0], true);
		}
	},

	updateMakeList : function() {
		this._setHiddenFieldValue("VehicleTypes", this.get_selectedCategories());
		this._saveSearchVehicle();
		showDIV('makeListBkg');
		$get(this.get_buttonIds().MakeListUpdate).click();
	},

	show : function(tabName) {
		hideDIV('advError');
		if (containsCssClass(this.get_element(), 'hide'))
		{
			showShadowBox(this.get_id(), false);
			if ($get('hiddenIE7')) {
				// IE7 has some issues with the new search.
				// We just have to make a change to the inner container
				// to force IE7 to display the contents properly.
				if (containsCssClass('advancedSearch', 'advIE7ToggleContentFix'))
					removeCssClass('advancedSearch', 'advIE7ToggleContentFix');
				else
					addCssClass('advancedSearch', 'advIE7ToggleContentFix');
			}

			this._fixAdvancedPNG();
		}

		this.changeTab(tabName);
	},

	hide : function() {
		if (this._openDDL) {
			hideDIV(this._openDDL);
			this._openDDL = null;
		}
		hideShadowBox(this.get_id());
	},

	selectMake : function(makeId) {
		var el = $get("MakeCheck_" + makeId);

		// The checkbox will handle adding the make to the SearchVehicle.
		if (el && !el.checked) {el.click();}
	},

	toggleAllModels : function(checkbox, make, models) {
		for (var model in models) {
			if (model) this.toggleSearchVehicleValues(checkbox, make, model, models[model]);
		}
		this.get_searchVehicle().findMake(make).IsAllModels = checkbox.checked;
	},

	toggleSearchVehicleValues : function (checkbox, make, model, cfmodel, trim) {
		if (checkbox.checked) {
			if (trim)
				this.get_searchVehicle().addTrim(make, model, cfmodel, trim);
			else if (cfmodel)
				this.get_searchVehicle().addCFModel(make, model, cfmodel);
			else if (model)
				this.get_searchVehicle().addModel(make, model);
			else if (make)
				this.get_searchVehicle().addMake(make);

			if ((model || cfmodel || trim) && this.get_searchVehicle().findMake(make)) {
				var root = findParentByClass(checkbox, 'AspNet-TreeView-Root');
				if (root) {
					this.get_searchVehicle().findMake(make).IsAllModels =
						root.getElementsByTagName('input')[0].checked;
				}
			}
		} else {
			var process = true;
			if (this.get_searchVehicle().findMake(make))
				this.get_searchVehicle().findMake(make).IsAllModels = false;

			if (process && trim) {
				cfmodel = this.get_searchVehicle().removeTrim(make, model, cfmodel, trim);
				if (cfmodel && cfmodel.Trims && 0 < cfmodel.Trims.length) {
					process = false;
				}
			}
			if (process && cfmodel) {
				model = this.get_searchVehicle().removeCFModel(make, model, cfmodel);
				if (model && model.CFModels && 0 < model.CFModels.length) {
					process = false;
				}
			}
			if (process && model) {
				make = this.get_searchVehicle().removeModel(make, model);
				if (0 == make.Models.length) make.IsAllModels = true;
			}

			if ((!model && !cfmodel && !trim) && make) {
				this.get_searchVehicle().removeMake(make);
			}
		}
	},

	enableModelPanel : function(checkbox, makeId, label, modelListBtn, panel) {
		this.toggleSearchVehicleValues(checkbox, makeId);
		this.anyDistanceSearch();
		if (checkbox.checked) {
			addCssClass(label, 'selected');
			addCssClass(label, 'greyBorder');
			this._fetchModelList(modelListBtn);
		} else {
			removeCssClass(label, 'selected');
			removeCssClass(label, 'greyBorder');
			if (null != label.documentClickHandler) {
				label.documentClickHandler();
				$removeHandler(document, 'click', label.documentClickHandler);
				label.documentClickHandler = null;
			}
			if (panel) {
				var c = panel.getElementsByTagName('input')[0];
				if (c && typeof (CascadeCheckmarks) == 'function') {
					c.checked = false;
					var e = {srcElement: c};
					CascadeCheckmarks(e);
				}
			}
		}
		return true;
	},

	toggleModelPanel : function(label, makeId, checkbox, panel, modelListBtn) {
		if (checkbox.checked) {
			this._fetchModelList(modelListBtn);
			toggleDIV(panel);

			if ($get('hiddenIE')) {
				if ($get('hiddenIE7')) {
					// IE7 has some issues with the new search.
					// The panel is not autosizing the first time when its hidden.
					if (!containsCssClass(panel, "hide")) {
						addCssClass(panel, "block");
						// Just toggling the display to block is not enough.
						// IE7 requires us to access the element so it can autosize.
						var divBnds = Sys.UI.DomElement.getBounds(panel);
						removeCssClass(panel, "block");
					}
				} else {
					addCssClass(panel, 'modelListIEFix');
				}
			}

			if (null == label.documentClickHandler) {
				label.documentClickHandler = function(e) {
					if (null == e || (!isChildOrEqual(label, e.target) && !isChildOrEqual(panel, e.target))) {
						hideDIV(panel);
					}
				};
				$addHandler(document, 'click', label.documentClickHandler);
			}
		}
		else {
			checkbox.checked = true;
			this.enableModelPanel(checkbox, makeId, label, modelListBtn, panel);
		}
	},

	search : function() {
		if(this._validate())
		{
			var id = this.get_id();

			// We are not using viewstate with this control. Save values that cannot already be retrieved
			// as part of the form in the code behind.
			this._saveSearchVehicle();

			this.hide();
			fnShowSearchingProgress();
			$get(this.get_buttonIds().Search).click();
		}

		return false;
	},

	toggleDDL : function(label, elementId) {
		var elm = $get(elementId);
		if (elm) {
			toggleDIV(elm);
			if (!containsCssClass(elm, "hide")) this._openDDL = elm;

			if (!elm.documentClickHandler) {
				elm.documentClickHandler = function(e) {
					if (null == e || (!isChildOrEqual(label, e.target) && !isChildOrEqual(elm, e.target))) {
						hideDIV(elm);
						this._openDDL = null;
					}
				};
				$addHandler(document, 'click', elm.documentClickHandler);
			}
		}
	},

	selectOtherValue : function(checkbox, label, multipleSelectedDisplay) {
		var checks = checkbox.parentNode.parentNode.getElementsByTagName("input");
		var count = checks.length;
		var checkedCount = 0;
		var firstValue = null;

		for (var i = 0; i < count; i++) {
			if ('checkbox' == checks[i].type && checks[i].checked)
			{
				if (!firstValue)
				{
					firstValue = checks[i].parentNode.getElementsByTagName("label")[0].innerHTML;
				}
				checkedCount += 1;
			}
		}

		if (1 == checkedCount) {
			label.innerHTML = firstValue;
		}
		else if (1 < checkedCount) {
			label.innerHTML = getAttributeValue(label, "multipleselected");
		}
		else  {
			label.innerHTML = getAttributeValue(label, "noneselected");
		}
	},

	anyDistanceSearch : function() {
		var distance = 0;
		var elm = this.get_elements().RangeDDL;
		hideDIV("asreqMakeModel");
		if (0 < elm.selectedIndex)
		{
			distance = elm.options[elm.selectedIndex].value;
		}
		if (1000 < distance && 0 >= this.get_searchVehicle().Makes.length)
		{
			showDIV("asreqMakeModel");
			this.changeTab("MakeModel");
		}
	},

	// Private Methods
	_fetchModelList : function(modelListBtn) {
		if (!modelListBtn.cached) {
			showDIV('makeListBkg');
			this._saveSearchVehicle();
			this._setHiddenFieldValue("VehicleTypes", this.get_selectedCategories());
			modelListBtn.click();
		}
	},

	_saveSearchVehicle : function() {
		this._setHiddenFieldValue('SearchCriteria',
			Sys.Serialization.JavaScriptSerializer.serialize(AdvancedSearch.get_searchVehicle()));
	},

	_validate : function() {
		valid = true;
		var elm;
		var elmFocus = null;
		var id = this.get_id();

		// Check the zip code value.
		hideDIV("asreqZip");
		hideDIV("aserrCat");
		hideDIV("asreqMakeModel");
		elm = this.get_zipTextBox();

		if (null == this.get_elements().CheckDealer || !this.get_elements().CheckDealer.checked)
		{
			if((0 == elm.value.length) || this._avZipWM == elm.value)
			{
				valid = false;
				showDIV("asreqZip");
				elmFocus = elm;
			}
			else
			{
				if (!g_regexZip.test(elm.value))
				{
					showDIV("aserrZip");
					valid = false;
					elmFocus = elm;
				}
			}

			elm = this.get_elements().RangeDDL;
			var distance = 0;
			if (0 < elm.selectedIndex)
				distance = elm.options[elm.selectedIndex].value;

			if (1000 < distance && 0 >= this.get_searchVehicle().Makes.length)
			{
				valid = false;
				showDIV("asreqMakeModel");
				this.changeTab("MakeModel");
			}
		}

		if (!this.get_elements().CheckNew.checked &&
			!this.get_elements().CheckUsed.checked &&
			!this.get_elements().CheckCertified.checked &&
			'' == this.get_selectedCategories())
		{
			showDIV("aserrCat");
			valid = false;
			elmFocus = this.get_elements().CheckNew;
			this.changeTab("Category");
		}

		if(null != elmFocus)
		{ elmFocus.focus(); }

		return valid;
	},

	_fixAdvancedPNG : function() {
		if ($get('hiddenIE6')) {
			if(null == this._advancedSS) {
				this._advancedSS = new SuperSleight();
			}

			this._advancedSS.limitTo(AdvancedSearch.get_id());
			this._advancedSS.run();
		}
	},

	_setHiddenFieldValue : function(fieldName, value) {
		var field = $get(this.get_hiddenFieldIds()[fieldName]);
		if (null != field) {field.value = value;}
	},

	_getHiddenFieldValue : function(fieldName) {
		var field = $get(this.get_hiddenFieldIds()[fieldName]);
		var retValue = null;
		if (null != field) {retValue = field.value;}

		return retValue;
	},

	_setTabVisibility : function(tab, show) {
		if (true === show) {
			addCssClass(tab.id, 'selected');
			showDIV(tab.contentId);
			tab.selected = true;
		}
		else {
			removeCssClass(tab.id, 'selected');
			hideDIV(tab.contentId);
			tab.selected = false;
		}
	},

	_processLotType : function(lotType) {
		var id = this.get_id();

		if (null == lotType || 0 == lotType) lotType = Reynolds.CL.Web.NewUsedChecks.New;

		if (lotType >= Reynolds.CL.Web.NewUsedChecks.Certified) {
			this.get_elements().CheckCertified.checked = true;
			lotType -= Reynolds.CL.Web.NewUsedChecks.Certified;
		}
		else {
			this.get_elements().CheckCertified.checked = false;
		}
		if (lotType >= Reynolds.CL.Web.NewUsedChecks.Used) {
			this.get_elements().CheckUsed.checked = true;
			lotType -= Reynolds.CL.Web.NewUsedChecks.Used;
		}
		else {
			this.get_elements().CheckUsed.checked = false;
		}
		if (lotType >= Reynolds.CL.Web.NewUsedChecks.New) {
			this.get_elements().CheckNew.checked = true;
			lotType -= Reynolds.CL.Web.NewUsedChecks.New;
		}
		else {
			this.get_elements().CheckNew.checked = false;
		}
	},

	// Handlers
	_onAdvSearchKeyPress : function(evt) {
		// evt is a Sys.UI.DomEvent object

		if (mapKeyToAction(evt))
		{
			this.search();
			setFixValidation();
			return false;
		}
	},

	_onBeginRequest : function(sender, args) {
		showDIV('advProgress');
		hideDIV('advError');
	},

	_onEndRequest : function(sender, args) {
		hideDIV('advProgress');
		hideDIV('makeListBkg');
		if (args.get_error() && isChildOrEqual(this.get_element(), sender._postBackSettings.sourceElement)) {
			showDIV('advError');
			args.set_errorHandled(true);
		}
	},

	_onZipFocus : function() {
		if(this.get_zipTextBox().value == this._avZipWM)
		{
			this.get_zipTextBox().value = '';
			removeCssClass(this.get_zipTextBox(), "grey");
		}
	},

	_onZipBlur : function() {
		if(this.get_zipTextBox().value == '')
		{
			this.get_zipTextBox().value = this._avZipWM;
			addCssClass(this.get_zipTextBox(), "grey");
		}
	},

	_onDealerClick : function() {
		if (!this.get_elements().CheckDealer.checked)
		{
			this.get_elements().RangeDDL.disabled = false;
			this.get_zipTextBox().disabled = false;
		}
		else
		{
			this.get_elements().RangeDDL.disabled = true;
			this.get_zipTextBox().disabled = true;
		}
	},

	// Public Properties
	get_tabs : function() {
		return this._tabs;
	},

	set_tabs : function(value) {
		if (this._tabs !== value) {
			this._tabs = value;
			this.raisePropertyChanged('tabs');
		}
	},

	get_lotType : function() {
		var id = this.get_id();
		var lotType = 0;
		if (this.get_elements().CheckCertified.checked) {
			lotType += Reynolds.CL.Web.NewUsedChecks.Certified;
		}
		if (this.get_elements().CheckUsed.checked) {
			lotType += Reynolds.CL.Web.NewUsedChecks.Used;
		}
		if (this.get_elements().CheckNew.checked) {
			lotType += Reynolds.CL.Web.NewUsedChecks.New;
		}

		if (0 == lotType) lotType = Reynolds.CL.Web.NewUsedChecks.New;
		return lotType;
	},

	set_lotType : function(value) {
		if (this.get_lotType() !== value) {
			this._processLotType(value);
			this.raisePropertyChanged('lotType');
			this.updateMakeList();
		}
	},

	get_zipTextBox : function() {
		return this._zipTextBox;
	},

	set_zipTextBox : function(value) {
		if (this._zipTextBox !== value) {
			this._zipTextBox = value;
			this.raisePropertyChanged('zipTextBox');
		}
	},

	get_buttonIds : function() {
		return this._buttonIds;
	},

	set_buttonIds : function(value) {
		if (this._buttonIds !== value) {
			this._buttonIds = value;
			this.raisePropertyChanged('buttonIds');
		}
	},

	get_hiddenFieldIds : function() {
		return this._hiddenFieldIds;
	},

	set_hiddenFieldIds : function(value) {
		if (this._hiddenFieldIds !== value) {
			this._hiddenFieldIds = value;
			this.raisePropertyChanged('hiddenFieldIds');
		}
	},

	get_elements : function() {
		return this._elements;
	},

	set_elements : function(value) {
		if (this._elements !== value) {
			this._elements = value;
			this.raisePropertyChanged('elements');
		}
	},

	get_searchVehicle : function() {
		return this._searchVehicle;
	},

	set_searchVehicle : function(value) {
		if (this._searchVehicle !== value) {
			if(typeof (SearchVehicle) != 'undefined') {
				this._searchVehicle = new SearchVehicle(value);
			}
			else {
				this._searchVehicle = value;
			}
			this.raisePropertyChanged('searchVehicle');
		}
	},

	get_selectedCategories : function() {
		var checks = $get('advVehicleTypeList').getElementsByTagName("input");
		var count = checks.length;
		var checkedValues = '';
		var first = true;

		for (var i = 0; i < count; i++) {
			if ('checkbox' == checks[i].type && checks[i].checked)
			{
				if (first)
				{
					checkedValues += checks[i].value;
					first = false;
				}
				else
				{
					checkedValues += ('.' + checks[i].value);
				}
			}
		}
		return checkedValues;
	}
}

function PopulateMaxYear()
{
	// Save the selected max year before repopulating.
	selectedMax = $get(advClientId + "_ddlMaxYear").value;

	// Mark the drop down as "Loading".
	SetDDLInnerHtml(advClientId + "_ddlMaxYear", "<option>[Loading...]</option>");
	$get(advClientId + "_ddlMaxYear").disabled = true;

	Reynolds.CL.Web.WebServices.VehicleFunctions.GetMaxYearDDList(
		$get(advClientId + "_ddlMinYear").value, WSKey,
		GetMaxYearsSuccess,
		GetMaxYearsFailure, selectedMax);
}

// Years drop down list successfully received from web service.
function GetMaxYearsSuccess(result, context)
{
	SetDDLInnerHtml(advClientId + "_ddlMaxYear", result);
	$get(advClientId + "_ddlMaxYear").disabled = false;
	// Restore the max selection if it exists.
	fnSetDDLByValue(advClientId + "_ddlMaxYear", context);
}

// Failure trying to get max years drop down list from web service.
function GetMaxYearsFailure(err)
{
	alert(err.get_message());

	$get(advClientId + "_ddlMaxYear").innerHTML = "";
	$get(advClientId + "_ddlMaxYear").disabled = false;
}

function PopulateMaxPrice()
{
	// Save the selected max Price before repopulating.
	selectedMax = $get(advClientId + "_ddlMaxPrice").value;

	// Mark the drop down as "Loading".
	$get(advClientId + "_ddlMaxPrice").disabled = true;

	Reynolds.CL.Web.WebServices.VehicleFunctions.GetMaxPriceDDList(
		$get(advClientId + "_ddlMinPrice").value, WSKey,
		GetMaxPricesSuccess,
		GetMaxPricesFailure, selectedMax);
}

// Trims drop down list successfully received from web service.
function GetMaxPricesSuccess(result, context)
{
	SetDDLInnerHtml(advClientId + "_ddlMaxPrice", result);
	$get(advClientId + "_ddlMaxPrice").disabled = false;
	// Restore the max selection if it exists.
	fnSetDDLByValue(advClientId + "_ddlMaxPrice", context);
}

// Failure trying to get max price drop down list from web service.
function GetMaxPricesFailure(err)
{
	alert(err.get_message());

	$get(advClientId + "_ddlMaxPrice").innerHTML = "";
	$get(advClientId + "_ddlMaxPrice").disabled = false;
}

// Register the class as a type that inherits from Sys.UI.Control.
Reynolds.CL.Web.AdvancedSearch.registerClass('Reynolds.CL.Web.AdvancedSearch', Sys.UI.Control);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

