////////////////////////////////////////////////////////////////
// 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 = {};


// ***************************************
// Main Page Initializer
// ***************************************
$j(function() {
	// Setup the side search
	HNSITE.Modules.InventoryHosting.Browse.SideSearch.Init({
		inventoryColumn: '#vehicles', 
		panelHeader: 'h4'
	});
	
	$j('#sortby').attr('onchange', '').change(function(){
		HNSITE.Modules.InventoryHosting.Browse.SortBy(this);
	});
	$j('#compareTextLink,#cmpchecked').attr('onclick', '').click(function(){
		HNSITE.Modules.InventoryHosting.Browse.CompareVehicles('input[name=compare]', '#vehicles', this);
	});

	$j('#side-search').css('visibility', 'visible');
});


// ***************************************
// Define our InventoryHosting.Browse namespace
// ***************************************
HNSITE.Modules.InventoryHosting.Browse = {};

// <summary>
// View the users checked vehicles side by side on the comparison page
// </summary>
HNSITE.Modules.InventoryHosting.Browse.CompareVehicles = function(element, parent, link) {
	var compareUrl = $j('#bwUrl').html() + 'compare.asp?compare=';
	var results = HNSITE.UI.Checkboxes.Count(element, parent);
	if (results.checked > 1 && results.checked < 5) {
		location.href = compareUrl + HNSITE.UI.Checkboxes.Values(element, parent, function(cbThis) {
			return cbThis.checked;
		}).join('&compare=');
	} else {
		$j(link).attr('title','Error: Choose two to four vehicles to compare.');
		HNSITE.UI.Tooltips.TipOver(link);
		setTimeout(function() {
			HNSITE.UI.Tooltips.TipOut(link);
		}, 2000);
	}
};

// <summary>
// Functionality for the sort by drop box to change to its provided urls 
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SortBy = function(element) {
	location.href = $j(element).val();
};


// ***************************************
// Define our InventoryHosting.SideSearch class
// ***************************************
HNSITE.Modules.InventoryHosting.Browse.SideSearch = {};

// <summary>
// Initializer for the side search
// Mandatory settings:
//    inventoryColumn (string): jQuery selector identifying the corresponding container to the side search to aid with UI height issues
// Optional settings:
//    textItemLimit (int): amount of characters to display of a text criteria item before ellipsing
//    panelHeader (string): html tag being used as the headers for each panel, should be a header tag (1-6)
//    linkBuildingOrder (array): order in which parameters are arranged in links, should manually match paging file
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.Init = function(options) {
	var self = this, 
		sideSearch = $j("#side-search");
		
	// Check mandatory settings
	if (typeof options.inventoryColumn != 'string') {
		alert('Inventory column selector missing from side search initialization settings');
		return;
	}
	var jInventoryColumn = $j(options.inventoryColumn);
	if (jInventoryColumn.length != 1) {
		// This is being shown in extremely specific cases on a certain site. Re-enable when they fix their side
		// alert('Inventory column specified in side search initialization settings was not found');
		return;
	}
	// Check meta setting options
	var optIsBothEnabled = (sideSearch.children("input.search-options-type").val().toLowerCase() == 'both') ? true : false;
	var optHideTypeChange = (sideSearch.children("input.search-options-hide-switch-type").val().toLowerCase() == 'true') ? true : false;
	var optHideResetSearch = (sideSearch.children("input.search-options-hide-reset-search").val().toLowerCase() == 'true') ? true : false;
	var accordionOrder = (sideSearch.children("input.search-options-order").val().length ) ? sideSearch.children("input.search-options-order").val().split('|') : [];
	var defaultOpenSection = '#side-search div.search-by-'+sideSearch.children("input.search-options-default-section").val();
	sideSearch.children("input").remove();
	// Prepare init options and save
	options = options || {};
	var defaults = {
		textItemLimit: 13, 
		panelHeader: 'h3', 
		linkBuildingOrder: ['featured', 'type', 'keywords', 'year', 'price', 'distance', 'make', 'model', 'trim', 'body', 'location', 'miles', 'epa', 'l100km', 'fuel', 'hybrid', 'special', 'anycolor', 'extcolor', 'intcolor', 'trans', 'drivetrain', 'certified', 'certified', 'dateinstock', 'sortby'], 
		enableBothType: optIsBothEnabled,
		accordionOrder: accordionOrder,
		showTypeSwitch: !optHideTypeChange,
		showResetSearch: !optHideResetSearch
	};
	options = $j.extend(defaults, options);
	sideSearch.data("search-options", options);
	
	// Reorder accordion before everything else so panels left out do not get processed
	if( options.accordionOrder.length ) {
		// Wrap each side-search-section and its header that comes immediately previous to it in a div, order those by 
		// 	search parameter and unwrap, then remove all side-search-sections still wrapped.
		
		sideSearch.find('div.side-search-section').each(function() {
			var className = this.className.replace(/.*search-by-(\w+).*/i,'$1') + ' reorder',
				sideSearchSection = $j(this).prev().andSelf();
			
			sideSearchSection.wrapAll('<div class="'+className+'"></div>');
		});
		
		$j.each( options.accordionOrder, function(index, value) {
			var reorderElem = sideSearch.find('div.reorder.'+value), firstReorder = sideSearch.find('div.reorder').first();
			
			if( reorderElem.length ) {
				// If you do .insertBefore using the same element twice, it disappears into a black hole
				if( reorderElem.get(0) != firstReorder.get(0) ) {
					reorderElem.insertBefore( firstReorder );
				}
				
				reorderElem.children().unwrap();
			}
		});
		
		sideSearch.find('div.reorder').remove();
	}
	
	defaultOpenSection = ( defaultOpenSection.length ) ? $j(defaultOpenSection).prev().get(0) : 0;

	
	// Find greatest panel height and if the corresponding inventory container wrap is less than our potentially greatest accordion
	// height state then set the heights equal to prevent annoying page shifting issues on changing panels from the animation
	var longestPanelHeight = 0, longestAccordionState = 0, TransformHeaderDampeningHeight = 12, PanelChangeAnimationDampening = 2.75;
	sideSearch.children(".side-search-section").each(function() {
		var thisHeight = $j(this).innerHeight();
		longestPanelHeight = (longestPanelHeight < thisHeight) ? thisHeight : longestPanelHeight;
	});

	if (jInventoryColumn.innerHeight() < longestPanelHeight)
		jInventoryColumn.height(longestPanelHeight);

	// Ellipsis any long text values and make them trigger the checkbox events
	sideSearch.find("> .side-search-section > .checkbox-item-wrapper > a")
		.live("click", function(e) {
			e.preventDefault();
			$j(this).prev().trigger("click", ['anchor']);
		})
		.each(function(index) {
			var me = $j(this);
			var limit = me.attr("data-text-limit") || options.textItemLimit;
			var origText = me.text();
			if (origText.length <= limit) {
				me.removeAttr("title");
			} else {
				var name = origText.left(origText.indexOf(' ('));
				var countLength = origText.length - name.length;
				name = name.ellipsis(limit - countLength);
				me.addClass("ellipsed").text(name + origText.right(countLength));
			}				
		});
		
	// Create our accordion panels and wireup our events
	sideSearch
		.delegate("a.ellipsed", "mouseenter", HNSITE.UI.Tooltips.TipOver)
		.delegate("a.ellipsed", "mouseleave", HNSITE.UI.Tooltips.TipOut)
		.accordion({
			header: options.panelHeader, 
			icons: {
				header: "ui-icon-circle-arrow-e",
				headerSelected: "ui-icon-circle-arrow-s"
			},
			active: (HNSITE.Data.Cookies.HasCookie('sideSearchOpenedTab')) ? Number(HNSITE.Data.Cookies.GetCookie('sideSearchOpenedTab')) : defaultOpenSection,
			autoHeight: false, 
			collapsible: true, 
			change: function(event, ui) { 
				// Store newly selected header index in cookie
				var index = $j(this).children(options.panelHeader).index(ui.newHeader[0]);
				HNSITE.Data.Cookies.Create('sideSearchOpenedTab', String(index), {expires: 7, path: '/'});
				// Move search action options to new tab content
				if ((ui.newContent).children(".side-search-actions-wrap").length == 0)
					$j("#side-search > .side-search-section > ul.search-actions").appendTo(ui.newContent[0]);
			}
		})
		.find("> .side-search-section:has(.checkbox-item-wrapper)").data('panel-type', 'checkbox').each(function(index) {
			var selectedCriteria = $j(this).find("> .checkbox-item-wrapper > input:checked").length;
			$j(this).prev().children("a").text(function(index, text) {
				return text + ' (' + String(selectedCriteria) + ' selected)';
			});
		})
		.find("> .checkbox-item-wrapper").delegate("input:checkbox", "click", self.CheckboxSearch);
	
	sideSearch.find("> .side-search-section:has(.text-search-wrapper)").data('panel-type', 'text').each(function() {
		if( $j(this).find("> .text-search-wrapper input[value!='']").length ) {
			$j(this).prev().children("a").text(function(index, text) {
				return text + ' (is set)';
			});
		}
	});
	
	// Wire up special case stock search
	sideSearch.find("> .search-by-stock button.find-stock").bind("click", HNSITE.Modules.InventoryHosting.Browse.SideSearch.StockSearch)
	.parents(".search-by-stock").find(".text-search-wrapper input:first")
		.keydown(function(event) {
			if (event.which == 13) {
				sideSearch.find("> .search-by-stock button.find-stock").click();
			}
		})
		.ajaxComplete(function (e, xhr, options) {
			var data;
			
			if( options.url.indexOf("stock-number-search.asp") >= 0 ) {
				if( xhr.status == 200 ) {
					try {
						data = $j.parseJSON( xhr.responseText.match(/[{].*[}]/)[0] );
					} catch(error) {
						data = { exists: false };
					}
					
					if( !data.exists ) {
						// None found
						$j(this).attr('title','This stock does not exist.');
						
						HNSITE.UI.Tooltips.TipOver( '#side-search .search-by-stock .text-search-wrapper input:first' );
						setTimeout(function() {
							HNSITE.UI.Tooltips.TipOut( '#side-search .search-by-stock .text-search-wrapper input:first' );
						}, 1500);
					}
				} else {
					// Show error
					$j(this).attr('title','Server error. Please try again.');
					
					HNSITE.UI.Tooltips.TipOver( '#side-search .search-by-stock .text-search-wrapper input:first' );
					setTimeout(function() {
						HNSITE.UI.Tooltips.TipOut( '#side-search .search-by-stock .text-search-wrapper input:first' );
					}, 1500);
				}
			}
		});
	
	// Wire up special case type panel
	sideSearch.find("> .search-by-type button.find-type").bind("click", HNSITE.Modules.InventoryHosting.Browse.SideSearch.TypeSearch);
	
	// Create sliders
	var rangeSliders = sideSearch.find("> .side-search-section > .range-slider").each(function(index) {
		self.CreateSlider(this);
	});
	
	// Create side search action options starting inside the opening accordion panel
	// Create our html structure
	var startActions = sideSearch.find("> .side-search-section:visible");
	if(!startActions.length) {
		// Safari bug - certain conditions can't find any visible sections, default to first
		startActions = sideSearch.find("> .side-search-section").first();
	}
	var searchActionsListWrap = HNSITE.Element.Build(startActions[0], 'ul', { 'class': 'search-actions' });
	var searchActionsResetPanelWrap = HNSITE.Element.Build(searchActionsListWrap, 'li', { 'class': 'ui-state-default' });
	var searchActionsResetPanelInner = HNSITE.Element.Build(searchActionsResetPanelWrap, 'a', { 'href': 'javascript:void(0);', 'class': 'reset-panel ui-icon ui-icon-close', 'title': 'Reset Only This Section' });
	if (options.showResetSearch) {
		var searchActionsResetEntireWrap = HNSITE.Element.Build(searchActionsListWrap, 'li', { 'class': 'ui-state-default' });
		var searchActionsResetEntireInner = HNSITE.Element.Build(searchActionsResetEntireWrap, 'a', { 'href': 'javascript:void(0);', 'class': 'reset-entire-search ui-icon ui-icon-arrowreturnthick-1-w', 'title': 'Reset Entire Search' });
	}
	// Create the "switch type" button for changing from new and used (and both if the option is set where we use a drop down menu instead since 3 states in that case instead of 2)
	if (options.showTypeSwitch) {
		var searchActionsSwitchTypeWrap = HNSITE.Element.Build(searchActionsListWrap, 'li', { 'class': 'ui-state-default' });
		if (options.enableBothType === true) {
			var searchActionsSwitchTypeInner = HNSITE.Element.Build(searchActionsSwitchTypeWrap, 'a', { 'href': 'javascript:void(0);', 'class': 'switch-type ui-icon ui-icon-shuffle', 'title': 'Switch Type' });
		}
		else {
			var typeMatch = String(location.href).toLowerCase().match(/type_(new|both|used)\//i),
				currentType = ($j.isArray(typeMatch)) ? typeMatch[1] : "used", 
				switchToType = (currentType == 'used') ? 'New' : 'Used';
			var searchActionsSwitchTypeInner = HNSITE.Element.Build(searchActionsSwitchTypeWrap, 'a', { 'href': 'javascript:void(0);', 'class': 'switch-type ui-icon ui-icon-shuffle', 'title': 'Switch to ' + switchToType + ' Vehicles' });
		}
	}
	// Events consistent for all action options
	sideSearch.find("> .side-search-section > ul.search-actions")
		.delegate("li", "mouseover mouseout", function() {
			$j(this).toggleClass("ui-state-hover");
		})
		.children("li").delegate("a", "mouseover", HNSITE.UI.Tooltips.TipOver).delegate("a", "mouseout", HNSITE.UI.Tooltips.TipOut);
	// Wireup custom events for each individual action option
	$j(startActions).find("> ul.search-actions > li > a.reset-panel").bind("click", self.RemoveParamsByName);
	$j(startActions).find("> ul.search-actions > li > a.reset-entire-search").bind("click", self.ResetEntireSearch);
	$j(startActions).find("> ul.search-actions > li > a.switch-type").bind("click", self.TypeChanger);
};

// <summary>
// Stock seach method that checks a pseudo-webservice to see if stock exists before posting search
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.StockSearch = function(e) {
	var self = $j(this), stock = self.parents(".search-by-stock").find("input[name=stock]").val(),
		baseUrl = HNSITE.Modules.InventoryHosting.Browse.SideSearch.GetBaseSearchUrl(['view']),
		webServiceUrl = "",
		params = {
			backwebID: $j('#bwId').html(),
			stock: stock.trim()
		};
	
	if( $j('#bwCommon').length ) {
		webServiceUrl = $j('#bwCommon').html();
	}
	
	$j.ajax({
		dataType: "json",
		url: webServiceUrl + 'Common/webservice/stock-number-search.asp',
		data: params,
		success: function(data){
			if (data.exists) {
				baseUrl = baseUrl.concat( "type_"+data.type.toLowerCase()+"/stock_"+stock+"/" );
				location.href = baseUrl;
			}
		},
		// IE is having major issues with window.XMLHttpRequest. Forcing to MS XML.
		xhr: function() {
			if ( document.compatMode && document.all ) {
				return new window.ActiveXObject("Microsoft.XMLHTTP");
			} else {
				return new window.XMLHttpRequest();
			}
		}
	});
};

// <summary>
// Type search method that allows a type panel to exist
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.TypeSearch = function(e) {
	var type = $j(this).parents(".search-by-type").find("select[name=type]").val(),
		baseUrl = HNSITE.Modules.InventoryHosting.Browse.SideSearch.GetBaseSearchUrl(["view"]);
		
	location.href = baseUrl + "type_{0}/".format(type);
};

// <summary>
// Create a slider bar for numeric range value criteria using meta data present in markup
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.CreateSlider = function(that) {
	var startVals = [], rangeSlider = $j(that), 
		paramName = rangeSlider.children("input.param-name").val(), paramPresent = rangeSlider.children("input.param-present").val().toLowerCase(), 
		rangeStep = Number(rangeSlider.children("input.range-step").val()), reParamMatch = new RegExp(paramName + '_[0-9]+_[0-9]+[\/]{1}', 'gi'), 
		relationalMin = Number(rangeSlider.children("input.relational-min").val()), relationalMax = Number(rangeSlider.children("input.relational-max").val());
	
	// Get our starting slider range values
	if (paramPresent == 'true') {
		// Get starting value using the users range selection if its set else we use the min and max for the relational selection
		var paramLow = Number(rangeSlider.children("input.param-value-low").val()), paramHigh = Number(rangeSlider.children("input.param-value-high").val());
		startVals.push( (relationalMin > paramLow) ? relationalMin : paramLow );
		startVals.push( (relationalMax < paramHigh) ? relationalMax : paramHigh );
		// Also while here mark this panel as set by updating panel header text
		rangeSlider.closest(".side-search-section").prev().children("a").text(function(index, text) {
			return text + ' (is set)';
		});
	}
	else {
		startVals.push(relationalMin);
		startVals.push(relationalMax);
	}
	
	// Store any settings we need elsewhere and remove meta data from DOM
	rangeSlider.closest(".side-search-section").data('panel-type', 'range');
	rangeSlider
		.data('has-changed', 'false')
		.data('param-present', paramPresent)
		.data('start-values', startVals)
		.children("input").remove();
		
	// Transform sliders and set initial text helpers for panels
	var displayRangeText = function(min, max) {
		rangeSlider.parent().find(".slider-range-summary").text(function(index) {
			if (paramName.toLowerCase() == 'price')
				return 'Vehicles from ' + HNSITE.Utils.FormatCurrency(min) + ' to ' + HNSITE.Utils.FormatCurrency(max);
			else if (paramName.toLowerCase() == 'epa')
				return 'Vehicles from ' + HNSITE.Utils.FormatNumber(min) + ' to ' + HNSITE.Utils.FormatNumber(max) + ' mpg';
			else if (paramName.toLowerCase() == 'l100km')
				return 'Vehicles from ' + HNSITE.Utils.FormatNumber(min) + ' to ' + HNSITE.Utils.FormatNumber(max) + ' L/100km';
			else if (paramName.toLowerCase() == 'year')
				return 'Vehicles from ' + min + ' to ' + max;
			else
				return 'Vehicles from ' + HNSITE.Utils.FormatNumber(min) + ' to ' + HNSITE.Utils.FormatNumber(max);
		});
	};
	
	// IE8 issue when startVals[0] == startVals[1]
	//	jquery.ui.slider.js does calculations to find where handles should be and comes up with "NaN%" and applies style "left: NaN%" that IE8 chokes on
	//	version 1.8.2: lines 629,655
	if( $j.browser.msie && startVals[0] == startVals[1] ) {
		// If min == max, then even adding to startVals will keep the handles in the same spot. must increase the range to be > 0
		if( relationalMin == relationalMax ) {
			relationalMax++;
		}
		
		// This situation only happens when the startVals == min || startVals == max
		if( startVals[0] == relationalMin ) {
			startVals[1]++;
		} else if( startVals[0] == relationalMax) {
			startVals[0]--;
		}
	}
	
	rangeSlider.slider({
		range: true,
		step: rangeStep, 
		min: relationalMin,
		max: relationalMax,
		values: startVals,
		slide: function(event, ui) {
			displayRangeText(ui.values[0], ui.values[1]);
		}, 
		change: function(event, ui) {
			rangeSlider.data('has-changed', 'true');
		}
	});

	displayRangeText(startVals[0], startVals[1]);
	
	rangeSlider.siblings(".slider-range-actions").children("button.update-range").bind("click", function(e) {
		HNSITE.Modules.InventoryHosting.Browse.SideSearch.Loader.Show(this);
		location.href = HNSITE.Modules.InventoryHosting.Browse.SideSearch.CompileSearchUrl();
	}).end().children("button.reset-range").bind("click", function(e) {
		HNSITE.Modules.InventoryHosting.Browse.SideSearch.Loader.Show(this);
		location.href = String(location.href).toLowerCase().replace(reParamMatch, '');
	});
};

// <summary>
// Generates the correct parameter and transfers user to the new search url that is generated by a checkbox criteria panel
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.CheckboxSearch = function(e, source) {
	if ($j("#side-search").data('is-loading') == 'true') return;
	
	// Handle the actual checking of the checkbox when event is triggered from text instead of clicking the checkbox itself
	if (source == 'anchor') {
		var thisCheckbox = $j(this);
		if (thisCheckbox.is(":checked"))
			thisCheckbox.removeAttr('checked');
		else
			thisCheckbox.attr('checked', 'checked');
	}
	// Collect data for selected criteria
	HNSITE.Modules.InventoryHosting.Browse.SideSearch.Loader.Show(this);
	var param = $j(this).attr("name"), value = String($j(this).val()).trim().replace(/\s+/g, "_");
	// Build new url with our selected criteria attached
	var currentUrl = String(location.href).toLowerCase(), parameterInsert = param.toLowerCase() + '_' + value.toLowerCase() + '/';
	if (currentUrl.indexOf(parameterInsert) >= 0) {
		// Already exists so request is to remove parameter from search url
		var reParam = new RegExp(parameterInsert, 'gi');
		currentUrl = currentUrl.replace(reParam, '');
		location.href = currentUrl;
	}
	else {
		location.href = HNSITE.Modules.InventoryHosting.Browse.SideSearch.CompileSearchUrl();
	}
};

// <summary>
// Create our loading screen and indicators for use before redirecting to a new search url. Only to be used 
// before a redirect due to the unload events to prevent history back problems with caching.
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.Loader = {
	Show: function(that) {
		$j("#side-search").data('is-loading', 'true');
		$j('<div class="loading-screen hnsite-ui-loading-large-screen"></div>').prependTo( $j(that).closest(".side-search-section")[0] )
			.css({
				"opacity": "0.75",
				"height": $j(that).parents('.side-search-section').outerHeight(false)
			}).show();
		$j("body").css('cursor', 'wait');
		$j(window).unload(function() {
			// Prevents all the usability issues with clicking back in browser
			HNSITE.Modules.InventoryHosting.Browse.SideSearch.Loader.Hide();
			if ($j(that).is(":checkbox")) 
				$j(that).removeAttr('checked');
		});
	}, 
	Hide: function() {
		$j("#side-search").data('is-loading', 'false');
		$j("#side-search").find("> .side-search-section > .loading-screen").remove();
		$j("body").css('cursor', 'auto');
	}
};

// <summary>
// Remove all parameters from the current search url for the panel containing the element to which this function is bound
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.RemoveParamsByName = function(e) {
	var parentPanel = $j(this).closest(".side-search-section"), currentUrl = String(location.href).toLowerCase();
	var paramName = '', paramNameMatches = parentPanel[0].className.match(/search-by-([a-zA-Z])+/i), panelType = parentPanel.data('panel-type');
	if (paramNameMatches == null) 
		return false;
	else
		paramName = String(paramNameMatches[0].split("-")[2]).toLowerCase();
	var reTextParam = new RegExp(paramName + '_([^_\/\ ]+_?)+[\/]{1}', 'gi'), reRangeParam = new RegExp(paramName + '_[0-9]+_[0-9]+[\/]{1}', 'gi');
	if (currentUrl.indexOf('/' + paramName + '_') >= 0) {
		HNSITE.Modules.InventoryHosting.Browse.SideSearch.Loader.Show(this);
		location.href = currentUrl.replace((panelType === 'range') ? reRangeParam : reTextParam, '');
	}
};

// <summary>
// Reset the entire searching leaving only the 'view' and 'type' parameters
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.ResetEntireSearch = function(e) {
	HNSITE.Modules.InventoryHosting.Browse.SideSearch.Loader.Show(this);
	var currentUrl = String(location.href).toLowerCase();
	var resetUrl = HNSITE.Modules.InventoryHosting.Browse.SideSearch.GetBaseSearchUrl(['type', 'view']);
	location.href = resetUrl;
};

// <summary>
// Returns the base portion of the browse page url to start building a search url from the beginning
// Options: 
//    includeList (array): set list of static parameters so we can choose whether to include in the base url
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.GetBaseSearchUrl = function(includeList) {
	if (!$j.isArray(includeList)) includeList = [];
	var currentUrl = String(location.href).toLowerCase();
	// Account for any debug pages like browse_dev
	var baseUrl = /http:\/\/[\w.%\/-]+[\/]browse[\w-]*[\/]/i.exec(currentUrl);
	if ($j.inArray("type", includeList) > -1) {
		var matchType = currentUrl.match(/type_(new|both|used)\//i);
		if (matchType != null) {
			baseUrl = baseUrl + 'type_' + matchType[1] + '/';
		} else {
			baseUrl = baseUrl + 'type_used/';
		}
	}
	if ($j.inArray("view", includeList) > -1) {
		var matchView = currentUrl.match(/view_(detailed|auction|text)\//i);
		if (matchView != null) {
			baseUrl = baseUrl + 'view_' + matchView[1] + '/';
		} else {
			baseUrl = baseUrl + 'view_detailed/';
		}
	} else {
		baseUrl = baseUrl + 'view_detailed/';
	}
	return baseUrl;
};

// <summary>
// Scan every panel and create a new search url based on all the selections that exist. Using this method
// will let us arrange parameters in order each time for more consistent links for the user's eye. Also it will
// be final measure to prevent 0 result searches in situations where an item was checked like a make and more criteria 
// filtering removed that make from the list so its stuck in the search url since we cant control what stays in there.
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.CompileSearchUrl = function() {
	var sideSearch = $j("#side-search"), excludeParamsFromUrl = ['type', 'view'],
		compiledLink = this.GetBaseSearchUrl( excludeParamsFromUrl ),
		options = this.GetOptions(),
		urlParams = location.href.substr( location.href.indexOf('/inventory/browse/') + 18 ), 
		param = null,
		paramsInUrl = [];
		
	// Check url for params. Have a backup of all url params info so that if we cannot find a panel for it, we know what to reinsert into the url
	$j.each(urlParams.split("/"), function(index, fullParam) {
		if (fullParam.length) {
			fullParam = fullParam.split("_");
			param = fullParam[0];
			// Must be a valid parameter from linkBuildingOrder but not already built in GetBaseSearchUrl
			if ($j.inArray(param, options.linkBuildingOrder) > -1 && $j.inArray(param, excludeParamsFromUrl) == -1)
				paramsInUrl.push( { name: param, data: fullParam.join("_") } );
		}
	});
	
	// Iterate each parameter in our link ordering list and assemble the user selected values chosen
	var panel = null, panelType = null, isParamFoundInUrl = false, paramFoundInUrlIndex = -1;
	$j.each(options.linkBuildingOrder, function(index, paramName) {
		// Check if this panel exists
		panel = sideSearch.children('.search-by-' + paramName);
		if (panel.length == 0) {
			// If it does not exist, check if value was in the url to carry over the value to new search
			isParamFoundInUrl = false;
			paramFoundInUrlIndex = -1;
			$j.each(paramsInUrl, function(paramsInUrlIndex, paramsInUrlObject) {
				if (paramsInUrlObject.name == paramName) {
					isParamFoundInUrl = true;
					paramFoundInUrlIndex = paramsInUrlIndex;
					return false;
				}
			});
			if (!isParamFoundInUrl)
				return true;
			else
				panelType = "array";
		}
		else {
			// Since we found a matching panel, lets continue checking and build this piece of our link
			panelType = panel.data('panel-type');
		}
		
		if (typeof panelType == 'undefined')
			return true; // handles 'no criteria' panels
		else if (panelType.toLowerCase() == 'checkbox') {
			panel.find("> .checkbox-item-wrapper > input:checked").each(function(index) {
				compiledLink = compiledLink + paramName + '_' + this.value + '/';
			});
		}
		else if (panelType.toLowerCase() == 'text' && paramName != 'stock') {
			panel.find("> .text-search-wrapper > input:text").each(function() {
				if( this.name.length && this.value.length ) {
					compiledLink = compiledLink + this.name + '_' + this.value + '/';
				}
			});
		}
		else if (panelType == 'range') {
			var rangeSlider = panel.children(".range-slider"), startVals = rangeSlider.data('start-values'), 
				paramPresent = rangeSlider.data('param-present'), hasChanged = rangeSlider.data('has-changed'), 
				sliderMin = Number(rangeSlider.slider("values", 0)), sliderMax = Number(rangeSlider.slider("values", 1));
			if (hasChanged == 'true' && $j("#side-search > .side-search-section").index(panel[0]) == $j("#side-search").accordion("option", "active"))
				compiledLink = compiledLink + paramName + '_' + sliderMin + '_' + sliderMax + '/';
			else if (paramPresent == 'true')
				compiledLink = compiledLink + paramName + '_' + startVals[0] + '_' + startVals[1] + '/';
		} 
		else if (panelType == 'array') {
			compiledLink = compiledLink + paramsInUrl[paramFoundInUrlIndex].data + '/';
		}
	});
	return compiledLink;
};

// <summary>
// Handles the functionality behind the action button for changing the type from new to used or even both if enabled. If the both 
// option is not set then it just needs to reset the url to the appropriate type. If both is an option we create a drop down menu
// on the fly which presents all three choices.
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.TypeChanger = function(e) {
	var sideSearch = $j("#side-search"), 
		options = HNSITE.Modules.InventoryHosting.Browse.SideSearch.GetOptions(), 
		isCreated = $j("#side-search").data('isTypeMenuCreated'),
		currentType = String(location.href).toLowerCase().match(/type_(new|both|used)\//i)[1],
		listWrap,
		slideCallback = function() {
			// Hide the tooltip and undelegate so they cannot show while menu is up
			HNSITE.UI.Tooltips.TipOut("#side-search > .side-search-section:visible > ul.search-actions > li a.switch-type");
			
			sideSearch.find("> .side-search-section:visible > ul.search-actions > li:has(a.switch-type)")
				.undelegate("a", "mouseover", HNSITE.UI.Tooltips.TipOver)
				.undelegate("a", "mouseout", HNSITE.UI.Tooltips.TipOut);
			
			$j('body').bind('click.type-menu', function(event) {
				if (!$j(event.target).parent().hasClass('type-menu')) {
					$j(listWrap).slideUp(250);
					$j('body').unbind('click.type-menu');
					
					sideSearch.find("> .side-search-section:visible > ul.search-actions > li:has(a.switch-type)")
						.delegate("a", "mouseover", HNSITE.UI.Tooltips.TipOver)
						.delegate("a", "mouseout", HNSITE.UI.Tooltips.TipOut);
				}
			});
		};
	
	if (options.enableBothType === true) {
		if (isCreated == null) {
		 // create here and set this .data
			sideSearch.data('isTypeMenuCreated',true);
			
			listWrap = HNSITE.Element.Build(sideSearch.get(0), 'ul', { 'class': 'list ui-state-default type-menu' });
			var item1 = (currentType == 'new') ? HNSITE.Element.Build(listWrap, 'li', { 'class': 'list-item ui-state-active', 'rel': 'new' }) : 
												 HNSITE.Element.Build(listWrap, 'li', { 'class': 'list-item', 'rel': 'new' })
			var text1 = HNSITE.Element.BuildText(item1, 'New Vehicles');
			var item2 = (currentType == 'used') ? HNSITE.Element.Build(listWrap, 'li', { 'class': 'list-item ui-state-active', 'rel': 'used' }) : 
												  HNSITE.Element.Build(listWrap, 'li', { 'class': 'list-item', 'rel': 'used' })
			var text2 = HNSITE.Element.BuildText(item2, 'Used Vehicles');
			var item3 = (currentType == 'both') ? HNSITE.Element.Build(listWrap, 'li', { 'class': 'list-item ui-state-active', 'rel': 'both' }) : 
												  HNSITE.Element.Build(listWrap, 'li', { 'class': 'list-item', 'rel': 'both' })
			var text3 = HNSITE.Element.BuildText(item3, 'New and Used');
			sideSearch.find("> .side-search-section:visible > ul.search-actions > li:has(a.switch-type)")
					  .children("a.switch-type").triggerHandler("mouseout");
			$j(listWrap).children("li:not(.ui-state-active)").hover(
				function() { $j(this).toggleClass("ui-state-focus"); },
				function() { $j(this).toggleClass("ui-state-focus"); }
			).bind('click', function () {
				var switchUrl = HNSITE.Modules.InventoryHosting.Browse.SideSearch.GetBaseSearchUrl(['view']);
				switchUrl = switchUrl + 'type_' + $j(this).attr('rel') + '/';
				location.href = switchUrl;
			});
			$j(listWrap).css({
				'display': 'none', 
				'position': 'absolute', 
				'left': ($j(this).offset().left - 2) + 'px', 
				'top': ($j(this).offset().top + $j(this).height() + 1) + 'px',
				'zIndex': '1'
			}).slideDown(250, slideCallback);
		} else {
			listWrap = sideSearch.find('ul.type-menu');
			
			listWrap.css({
				'left': ($j(this).offset().left - 2) + 'px', 
				'top': ($j(this).offset().top + $j(this).height() + 1) + 'px'
			}).slideDown(250, slideCallback);
		}
		
	}
	else {
		var switchUrl = HNSITE.Modules.InventoryHosting.Browse.SideSearch.GetBaseSearchUrl(['view']),
		switchToType = (currentType == 'used') ? 'new' : 'used';
		
		switchUrl = switchUrl + 'type_' + switchToType + '/';
		location.href = switchUrl;
	}
};

// <summary>
// Return our saved options object
// </summary>
HNSITE.Modules.InventoryHosting.Browse.SideSearch.GetOptions = function() {
	return $j("#side-search").data("search-options");
};

