////////////////////////////////////////////////////////////////
// HomeNet JS Core Site Library
// HomeNet Inventory Hosting
// (c) 2010, HomeNet Automotive LLC
////////////////////////////////////////////////////////////////

// ***************************************
// Define our Modules.InventoryHosting namespace
// ***************************************
if (typeof HNSITE == 'undefined') HNSITE = {};
if (typeof HNSITE.Modules == 'undefined') HNSITE.Modules = {};
HNSITE.Modules.InventoryHosting = {};


// ***************************************
// Define our InventoryHosting.Search namespace
// ***************************************
HNSITE.Modules.InventoryHosting.Search = {};

// <summary>
// Holds configuration settings for the search widget so that in the case of needing to create a custom search box 
// we can just define certain selectors and add pre-defined classes to the html so it will wireup to different markup
// without any problems of needed to edit all the initialization code in here. This is meant to be flexible so for example  
// a "parent" doesnt need to the exact parent but just some close/approximate parent to narrow our DOM searching for any children.
// </summary>
HNSITE.Modules.InventoryHosting.Search.Configuration = {
	RootSearchBoxID: '#search-module', 
	Tabs: {
		Parent: 'ul.tabs', 
		Children: 'li.tab', 
		ClassPrefix: 'tab-'
	},
	Panels: {
		Parent: 'div.panels', 
		Children: 'div.panel',
		ClassPrefix: 'panel-'
	}, 
	ClassSuffix: {
		Search: 'search', 
		ShopByPayment: 'payment', 
		ShopByMpg: 'mileage', 
		NewArrivals: 'arrivals', 
		AdvancedSearch: 'advanced'
	}
};

// <summary>
// Provide a panel suffix name and return the jQuery selector for its corresponding content panel
// </summary>
HNSITE.Modules.InventoryHosting.Search.GetPanelByName = function(panelSuffixName) {
	var config = this.Configuration, isPanelValid = false;
	panelSuffixName = panelSuffixName.toLowerCase();
	$j.each(config.ClassSuffix, function(key, value) {
		if (value.toLowerCase() == panelSuffixName)
			isPanelValid = true;
	});
	if (!isPanelValid) 
		return null;
	else
		return $j(config.RootSearchBoxID).find(config.Panels.Parent).find(config.Panels.Children + '.' + config.Panels.ClassPrefix + panelSuffixName).first();
};

// <summary>
// Search page initializer for setting up all our functionality
// </summary>
HNSITE.Modules.InventoryHosting.Search.Init = function() {
	var that = this, 
		config = that.Configuration;
	
	// Setup the tabs functionality
	$j(config.RootSearchBoxID).find(config.Panels.Parent).find(config.Panels.Children).slice(1).css("display", "none");
	$j(config.RootSearchBoxID).find(config.Tabs.Parent).find(config.Tabs.Children).live("click", function() {
		// Gather selectors for the current and requested tab button and correlating content container
		var newTabContent = that.GetPanelByName($j(this).attr("rel"));
		if (newTabContent.css("display") == 'block') return false;
		var oldActiveTabHandle = $j(this).closest(config.Tabs.Parent).find(".active").first(),
			oldTabContent = that.GetPanelByName(oldActiveTabHandle.attr("rel"));
		// Toggle all classes and slide out the old content and in with the new
		oldActiveTabHandle.removeClass("active");
		$j(this).addClass("active");
		oldTabContent.fadeOut(400, function() {
			newTabContent.fadeIn(120);
		});
		return false;
	});
	
	// Setup the search panel's basic search
	var jSearchPanel = that.GetPanelByName('search');
	jSearchPanel.find(".make-grouping select:first").bind("change", HNSITE.Modules.InventoryHosting.Search.BasicSearch.LoadModel);
	jSearchPanel.find(".submit-grouping button.basic-search:first").bind("click", HNSITE.Modules.InventoryHosting.Search.BasicSearch.Post);
	HNSITE.Modules.InventoryHosting.Search.BasicSearch.Init();
	
	// Setup the advanced search
	var jAdvancedPanel = that.GetPanelByName('advanced');
	HNSITE.Modules.InventoryHosting.Search.AdvancedSearch.Reload();
	HNSITE.Modules.InventoryHosting.Search.AdvancedSearch.Init();
	jAdvancedPanel.find("button.advanced-search").bind("click", HNSITE.Modules.InventoryHosting.Search.AdvancedSearch.Post);
	
	$j(config.RootSearchBoxID).find(config.Panels.Parent).delegate("ul.row-highlightable > li", "mouseenter mouseleave click", function(e) {
		if (e.type == 'mouseover')
			$j(this).addClass("hover");
		else if (e.type == 'mouseout')
			$j(this).removeClass("hover");
		else if (e.type == 'click') {
			$j(this).removeClass("hover");
			location.href = $j(this).children("a").attr("href");
		}
	});

	
	//$j("a.tracker").bind("click", HNSITE.Portal.Tracking.PopularLinks); -- figure out/test this later
};

// <summary>
// Basic search page methods to load selectbox data, construct url, and redirect to browse page.
// </summary>
HNSITE.Modules.InventoryHosting.Search.BasicSearch = {
	
	// Preloads makes into make dropdown
	Init: function () {
		var jSearchPanel = HNSITE.Modules.InventoryHosting.Search.GetPanelByName('search'),
			selectMake = jSearchPanel.find(".make-grouping select:first")[0],
			jsonPostData = {
				'return': 'make_standard',
				'groupby': 'make_standard',
				'param_new-used': jSearchPanel.find(".type-grouping input:first").val()
			};
		
		$j.getJSON('/framework/data-services/json-query.asp', jsonPostData, function(responseData) {
			HNSITE.Utils.SelectBox.Empty(selectMake);
			HNSITE.Utils.SelectBox.Add(selectMake, "Any Make", "");
			$j.each(responseData, function(index, value) {
				if (value.make_standard.length)
					HNSITE.Utils.SelectBox.Add(selectMake, value.make_standard, value.make_standard);
			});
		});
	},
	
	// Use as onchange for make dropdown to load correct models
	LoadModel: function() {
		var jSearchPanel = HNSITE.Modules.InventoryHosting.Search.GetPanelByName('search'),
			selectModel = jSearchPanel.find(".model-grouping select:first")[0],
			make = jSearchPanel.find(".make-grouping select:first").val(), 
			jsonPostData = {
				'return': 'model_standard',
				'groupby': 'model_standard',
				'param_make_standard': make, 
				'param_new-used': jSearchPanel.find(".type-grouping input:first").val()
			};
		
		if (make.length) {
			$j.getJSON('/framework/data-services/json-query.asp', jsonPostData, function(responseData) {
				HNSITE.Utils.SelectBox.Empty(selectModel);
				HNSITE.Utils.SelectBox.Add(selectModel, "Any Model", "");
				$j.each(responseData, function(index, value) {
					if (value.model_standard.length) {
						// This must be html decoded.. if more instances found, create html encode/decode class?
						value.model_standard = value.model_standard.replace("&amp;", "&");
						HNSITE.Utils.SelectBox.Add(selectModel, value.model_standard, value.model_standard);
					}
				});
			});
		}
	},
	
	// Loop through values, construct url, and redirect
	Post: function() {
		var jSearchPanel = HNSITE.Modules.InventoryHosting.Search.GetPanelByName('search'),
			searchUrl = "/inventory/browse/", 
			zipParam = "distance_[zip]_[distance]/", 
			searchParam = "", 
			type = jSearchPanel.find(".type-grouping input:first").val();
		
		// Always want type first in the url
		if (!type)
			searchUrl = searchUrl.concat("type_used/");
		else 
			searchUrl = searchUrl.concat("type_" + type + "/");
		
		if (HNSITE.UI.Validation.SimpleValidate({ context: jSearchPanel[0] })) {
			jSearchPanel.find('.label-field-grouping input,select').not('[name=type]').each(function(){
				if (!this.value.blank()) {
					searchParam = HNSITE.Utils.BrowsePageEscape(this.value.toLowerCase());
					if (this.type == 'radio' || this.type == 'checkbox') {
						if (this.checked) 
							searchUrl = searchUrl.concat(this.name + '_' + searchParam + '/');
					} 
					else if (this.name == 'distance' || this.name == 'zip') 
						zipParam = zipParam.replace("[" + this.name + "]", searchParam);
					else 
						searchUrl = searchUrl.concat(this.name + '_' + searchParam + '/');
				}
			});
			
			if (zipParam.indexOf("[") == -1)
				searchUrl = searchUrl.concat(zipParam);
			
			window.location = searchUrl;
		}
		
		return false;
	}
	
};

HNSITE.Modules.InventoryHosting.Search.AdvancedSearch = {
	
	Reload: function() {
		var jAdvancedPanel = HNSITE.Modules.InventoryHosting.Search.GetPanelByName('advanced'),
			formData = jAdvancedPanel.find("form[name='advanced-search']").serialize();
			
		$j.ajax({
			data: formData,
			type: 'POST',
			url: '/inventory/search/search.advanced-tab.asp',
			success: function(data) {
				jAdvancedPanel.find('.loadin').html(data);
				jAdvancedPanel.find('.zip-code').keydown(function(event) {
					if (event.which == 13) {
						HNSITE.Modules.InventoryHosting.Search.AdvancedSearch.Post();
						return false;
					}
				});
				jAdvancedPanel.find('input:not(:hidden),select').attr('disabled', '');
			}
		});
	},
	
	Post: function() {
		var jAdvancedPanel = HNSITE.Modules.InventoryHosting.Search.GetPanelByName('advanced'),
			searchUrl = "/inventory/browse/", 
			zipParam = "distance_[zip]_[distance]/", 
			regex = HNSITE.UI.Validation.Regex.QuickTests, 
			replaceZipParam = "",
			searchTermMin = "", 
			searchTermMax = "";
		
		if (HNSITE.UI.Validation.SimpleValidate({ context: jAdvancedPanel[0] })) {
			jAdvancedPanel.find('input,select').not('.dual-select,.no-post').each(function() {
				var searchValue = "";
				if (!this.value.blank()) {
					searchValue = HNSITE.Utils.BrowsePageEscape(this.value);
					if (this.type == 'radio' || this.type == 'checkbox') {
						if (this.checked)
							searchUrl = searchUrl.concat( this.name + '_' + searchValue + '/' );
					} 
					else if (this.name == 'distance' || this.name == 'zip') {
						replaceZipParam = "[" + this.name + "]";
						zipParam = zipParam.replace( replaceZipParam, searchValue );
					} 
					else
						searchUrl = searchUrl.concat( this.name + '_' + searchValue + '/' );
				}
			});
			// Custom handling for year ranges
			searchTermMin = HNSITE.Data.UrlEncode( $j('#hnsite-search-year-min').val() );
			searchTermMax = HNSITE.Data.UrlEncode( $j('#hnsite-search-year-max').val() );
			if (regex.IsInteger(searchTermMin) && regex.IsInteger(searchTermMax))
				searchUrl = searchUrl.concat( 'year_' + searchTermMin + '_' + searchTermMax + '/' );
			// Custom handling for price ranges
			searchTermMin = HNSITE.Data.UrlEncode( $j('#hnsite-search-price-min').val() );
			searchTermMax = HNSITE.Data.UrlEncode( $j('#hnsite-search-price-max').val() );
			if (regex.IsInteger(searchTermMin) && regex.IsInteger(searchTermMax))
				searchUrl = searchUrl.concat( 'price_' + searchTermMin + '_' + searchTermMax + '/' );
			// Custom handling for zipcode
			if (zipParam.indexOf("[") == -1)
				searchUrl = searchUrl.concat( zipParam );
				
			// Redirect to our new link that we constructed
			window.location = searchUrl;
		}
		return false;
	},
	
	Init: function() {
		var jAdvancedPanel = HNSITE.Modules.InventoryHosting.Search.GetPanelByName('advanced');
		
		jAdvancedPanel.delegate('input,select', 'change', function() {
			var self = $j(this);
			if (!self.hasClass('no-reload')) {
				if (self.hasClass('dual-select')) {
					var id = this.id;
					if (id.indexOf('Min') >= 0)
						id = id.replace('Min','Max');
					else
						id = id.replace('Max','Min');
					if (self.val() && $j('#' + id).val())
						HNSITE.Modules.InventoryHosting.Search.AdvancedSearch.Reload();
				}
				else
					HNSITE.Modules.InventoryHosting.Search.AdvancedSearch.Reload();
			}
			return true;
		});
	}
	
};

