var StateManager;


$(document).ready(document_Ready);


function document_Ready()
{
	/*var options = $(".options");
	var languageOpened;
	var mouseOver;
	$("#sizeSelect").click(function() {
		mouseOver = true;
		sizeOpened = false;
		if($(".options").is(":hidden")){
			$('#defaultSizeSelect').css('backgroundImage','url(/graphics/store/detail/sizeSelectOpened.gif)');
			$('#sizeSelect').css('height', 'auto');
			
			for(i = 0; i < options.length; i++) {
				$("#selection"+i).slideDown("fast");	
			}
			//languageOpened = true;
			//setTimeout("listenForClose()", 2000)
			$("#sizeSelect").bind("mouseleave", function(e){
				for(i = 0; i < options.length; i++) {
					$("#selection"+i).slideUp("fast");	
				}
				$('#defaultSizeSelect').css('backgroundImage','url(/graphics/store/detail/sizeSelect.gif)');
				$('#sizeSelect').css('height','14px');
			});
		}	
	});*/
	
	// uncheck all hidden custom-checkbox checkboxes
	// checkboxes are named according to their tab (criteria_men, criteria_women, etc)
	// the carrot indicates that the NAME attribute starts with 'criteria' ... which they all do
	$("input:checkbox[name^='criteria']:checked").attr("checked", false);
	
	initialzieVariables();
	assignEventListeners();
	processURL();
}



function initialzieVariables()
{
	initQuickView();
	
	StateManager = EXANIMO.managers.StateManager;
	StateManager.initialize();
	StateManager.history = [];
	StateManager.historyIndex = 0;
	StateManager.disregardFromHistory = false;
    // Define what happens when the state changes.
	setInterval(history_Check, 500);
}



function assignEventListeners()
{
	$(".customedCheckboxGroup").bind("click", customedCheckbox_Click);
	$(".customedCheckboxGroup").bind("select", customedCheckbox_Select)
	$(".colorInput").bind("click", colorInput_Click);
	$(".colorInput").bind("select", colorInput_Select);
	$(".StoreNav").bind("click", StoreNav_Click);
	$(".ProductSearchResultLink").bind("click", ProductSearchResultLink_Click);
	$("#resetFormLink").bind("click", resetFormLink_Click)
	$(".filterTab").click(filterTab_Click);
}

function filterTab_Click()
{
	var tabName = $(this).attr("Tab");
	var tabNameLower = tabName.toLowerCase();
	var tab = $(this).next("div[Tab='"+ tabName +"']");
	var autoSelect = parseInt(tab.attr("AutoSelect")) == 1;
	
	var child = $($(tab.children("div")[0]).children("div")[0]).children()[0]
	var child = $(child);
	if(child.attr("selected") == null)
	{
		child.attr("selected", "false");
	}
	
	if(autoSelect && tab.attr("State") == "Closed" && !toBoolean(child.attr("selected")))
	{
		child.trigger("click");
	}
	else
	{
		openBrowserTab(tabNameLower);
	}
}


function toBoolean(val)
{
	if(val == null){ return false; }
	var val = $.trim(val.toString())
	return val != "" && val == "true";
}


function history_Add()
{
	StateManager.setState(location.hash.replace(/#/g,""));
	StateManager.history.push(location.hash);
	StateManager.historyIndex++;
}


function history_Check()
{
	if(StateManager.history.length > 0 && StateManager.history[--StateManager.historyIndex] != location.hash)
	{
		StateManager.disregardFromHistory = true;
		//alert(StateManager.history[StateManager.history.length-1] + "\n\nurl: " + location.hash);
		//StateManager.history.pop();
		processURL();
	}
}


function resetFormLink_Click()
{
	location.hash = "#";
	unselectAllCriteria();
	// promotions needs to be run separately due to unique functionality
	unselectAllCriteria("promotions");
	processURL();
	return false;
}


function ProductSearchResultLink_Click()
{
	var sender = $(this);
	
	var wsj = new webStore();
	wsj.setCallbackHandler(function(result){ ProductSearchResultLink_Result(result, sender) });
	wsj.setErrorHandler(function(){ ProductSearchResultLink_Error(sender) });
	
	wsj.setSessionVariables({SearchString:location.hash});
	
	return false;
}
function ProductSearchResultLink_Result(result, sender)
{
	location.href = sender.attr("href");
}
function ProductSearchResultLink_Error(sender)
{
	// nothing
}


function StoreNav_Click()
{
	// get current search data
	var currentSearch = serializeUrlCriteria();
	for(var type in currentSearch)
	{
		unselectAllCriteria(type);
	}
	
	location.hash = "#" + $(this).attr("href").split("#")[1];
	processURL();
	
	// stop the native url-changing caused by href
	return false;
}




var menFilters = [];
var womenFilters = [];
var industryFilters = [];
var layerFilters = [];
var climateFilters = [];
var fabricFilters = [];
var colorFilters = [];

var criteria = {};
criteria.men = [];
criteria.women = [];
criteria.industry = [];
criteria.layer = [];
criteria.climate = [];
criteria.fabric = [];
criteria.color = [];

var qvstars;



function colorInput_Select()
{
	var sender = $(this);
	var row = sender.parents(".Row");
	var tab = row.parent();
	
	var values = {};
	values.Tab = tab.attr("Tab");
	values.Display = row.attr("Display");
	values.CheckboxImage = row.attr("CheckboxImage");
	values.Checkbox = row.attr("Checkbox");
	values.OptionID = row.attr("OptionID");
	
	var objects = {};
	objects.CheckBox = $("#" + values.Checkbox);
	objects.CheckBoxImage = $("#" + values.CheckboxImage);
	objects.TabBar = $("#" + values.Tab.toLowerCase() + "Bar");
	
	
	var checkboxChecked = objects.CheckBox.attr("checked");
	if(checkboxChecked)
	{
		objects.CheckBoxImage.removeClass("selectedSwatchStyle");
		removeCriteria(values.Tab, values.Display);
	}
	else
	{
		objects.CheckBoxImage.addClass("selectedSwatchStyle");
		addCriteria(values.Tab, values.Display);
	}
	objects.CheckBoxImage.attr("selected", !checkboxChecked);
	objects.CheckBox.attr('checked', !checkboxChecked);
	
	// if target's tab isn't expanded -- expand it
	if(!objects.TabBar.hasClass("selected"))
	{
		openBrowserTab("color")
	}
}


function colorInput_Click()
{
	var sender = $(this);
	var row = sender.parents(".Row");
	var tab = row.parent();
	
	var values = {};
	values.Tab = tab.attr("Tab");
	values.Display = row.attr("Display");
	values.CheckboxImage = row.attr("CheckboxImage");
	values.Checkbox = row.attr("Checkbox");
	values.OptionID = row.attr("OptionID");
	
	var objects = {};
	objects.CheckBox = $("#" + values.Checkbox);
	objects.CheckBoxImage = $("#" + values.CheckboxImage);
	objects.TabBar = $("#" + values.Tab.toLowerCase() + "Bar");
	
	objects.CheckBoxImage.trigger("select");
	
	criteria["color"] = $("input:checkbox[name='Color']:checked").getValue().split(",");
	if(criteria["color"].length == 1 && Array(criteria["color"])[0] == "")
	{
		criteria["color"] = [];
	}
	
	generateHash();
	processURL();
}


function customedCheckbox_Select()
{
	var sender = $(this);
	var row = sender.parents(".Row");
	var tab = row.parent();
	
	var values = {};
	values.Tab = tab.attr("Tab");
	values.ProductDisplay = row.attr("Display");
	values.CheckboxImage = row.attr("CheckboxImage");
	values.Checkbox = row.attr("Checkbox");
	values.SearchID = row.attr("SearchID");
	
	var objects = {};
	objects.CheckBox = $("#" + values.Checkbox);
	objects.CheckBoxImage = $("#" + values.CheckboxImage);
	objects.TabBar = $("#" + values.Tab.toLowerCase() + "Bar");
	
	
	// handle selecting/highlighting
	var checkboxChecked = objects.CheckBox.attr("checked");
	
	if(checkboxChecked)
	{
		objects.CheckBoxImage.attr("src", "/graphics/Icons/customedCheckbox"+values.Tab+".gif");
		removeCriteria(values.Tab, values.ProductDisplay);
	}
	else
	{
		if(sender.attr("IsRadio") != null)
		{
			unselectAllCriteria("promotions", false);
		}
		objects.CheckBoxImage.attr("src", "/graphics/Icons/customedCheckbox"+values.Tab+"_ON.gif");
		addCriteria(values.Tab, values.ProductDisplay);
	}
	objects.CheckBoxImage.attr("selected", !checkboxChecked);
	objects.CheckBox.attr('checked', !checkboxChecked);
	
	// select hidden checkboxes and assign to criteria based on tab
	var tabLower = values.Tab.toLowerCase();
	criteria[tabLower] = $("input[name='criteria_"+ tabLower +"']:checked").getValue().split(",");
	if(criteria[tabLower].length == 1 && Array(criteria[tabLower])[0] == "")
	{
		criteria[tabLower] = [];
	}
	// clean duplicates
	criteria[tabLower] = uniqueArrayNumbers(criteria[tabLower]);
	
	// if target's tab isn't expanded -- expand it
	if(!objects.TabBar.hasClass("selected"))
	{
		openBrowserTab(values.Tab.toLowerCase())
	}
}



function getCustomCheckboxFamily(boxObj)
{
	var sender = boxObj;
	var row = sender.parents(".Row");
	var tab = row.parent();
	
	var values = {};
	values.Tab = tab.attr("Tab");
	values.ProductDisplay = row.attr("Display");
	values.CheckboxImage = row.attr("CheckboxImage");
	values.Checkbox = row.attr("Checkbox");
	values.SearchID = row.attr("SearchID");
	
	var objects = {};
	objects.Row = row;
	objects.Tab = tab;
	objects.CheckBox = $("#" + values.Checkbox);
	objects.CheckBoxImage = $("#" + values.CheckboxImage);
	
	var data = {
		"values" : values,
		"objects" : objects
	};
	
	return data;
}



function customedCheckbox_Click()
{
	var cbData = getCustomCheckboxFamily($(this));
	var objects = cbData.objects;
	var row = objects.Row;
	
	// fire SELECT event to highlight box -- this is handled separately so that highlighting can be done without
	// firing a full CLICK event
	objects.CheckBoxImage.trigger("select");
	
	
	// check IsClearance first because clearance is both IsPromotion and IsClearance
	// but promotions are just IsPromotion
	if(row.attr("IsClearance") != null)
	{
		filterByPromotion( row.attr("PromotionID") );
	}
	else if(row.attr("IsPromotion") != null)
	{
		filterByPromotion( row.attr("PromotionID") );
		unselectAllCriteria("clearance");
	}
	else
	{
		unselectAllCriteria("promotions");
		unselectAllCriteria("clearance");
	}
	
	
	generateHash();
	processURL();
	
}


function filterByPromotion(promotionId)
{
	unselectAllCriteria();
	var promotionBox = $(".promotion[PromotionId=" + promotionId + "]");
	var cbData = getCustomCheckboxFamily(promotionBox);
	
	//alert(cbData.objects.CheckBox.attr("id"));
}



function getAllTabs()
{
	// promotions not included due to its unique functionality
	return ["men","women","industry","layer","climate","fabric","color"];
}


/*
 *  Unselect all search criteria in search-nav in a given tab
 */
function unselectAllCriteria(tabName, collapseTargetTab)
{
	var tabs = getAllTabs();
	if(tabName != null)
	{
		tabs = [tabName];
	}
	
	for (var i in tabs) 
	{
		var tab = tabs[i];
		var allCriteria = getCriteriaValuesByTab(tab);
		for (var j in allCriteria) 
		{
			var searchDiv = $("div[SearchID='" + allCriteria[j] + "']");
			var img = searchDiv.children(".Col").children("img");
			
			if (toBoolean(img.attr("selected"))) 
			{
				img.trigger("select");
			}
		}
	}
	
	if (collapseTargetTab == null || collapseTargetTab)
	{
		collapseEmptyTabs();
	}
}


/*
 *  Generates and assigns browser hash from current search criteria
 */
function generateHash()
{
	var hashString = "#";
	
	for(var tab in criteria)
	{
		var results = criteria[tab];
		if (results.length > 0) 
		{
			hashString += tab + "(" + results + ")|";
		}
	}
	// drops the last pipe (|) separator and assigns string to browser hash
	
	
	if(hashString == "#")
	{
		location.hash = "#";
	}
	else
	{
		location.hash = hashString.substring(0, hashString.length-1);
	}
	
	// fill in results count
	updateResultsReturnedLabels();
}


/*
 *  Updated number of results returned from search and displays
 */
function updateResultsReturnedLabels()
{
	$("#searchResultsCount").text( $(".Filter_ShownSearchResult").length );
	if($(".Filter_ShownSearchResult").length == 0)
	{
		$("#NoResultsDiv").show();
	}
	else
	{
		$("#NoResultsDiv").hide();
	}
}



/*
 *  Given an array of numbers, returns array with duplicate numbers filtered out
 */
function uniqueArrayNumbers(arr)
{
	var tmpArr = [];
	for(var i=0; i < arr.length; i++)
	{
		if($.inArray(arr[i], tmpArr) == -1)
		{
			tmpArr.push(arr[i]);
		}
	}
	return tmpArr;
}


/*
 *  Closes any tabs with no selected criteria
 */
function collapseEmptyTabs()
{
	var tabs = $("div[Tab]");
	$.each(tabs, function()
	{
		var tab = $(this);
		var cboxes = tab.children("input:checkbox:checked");
		if(cboxes.length == 0)
		{
			var bar = $("#" + tab.attr("Tab").toLowerCase() + "Bar");
			if(bar.hasClass("selected"))
			{
				bar.trigger("click");
			}
		}
	});
}


/*
 * Return an array of the search criteria id's in a given tab
 */
function getCriteriaValuesByTab(tab)
{
	var cboxes = $(".customedCheckbox_" + tab.toLowerCase());
	
	var values = [];
	$.each(cboxes, function()
	{
		values.push($(this).val())
	});
	
	return values;
}


// returns object containing attributes associated with search tabs (men, women, industry, etc)
// and their associated search criteria based on parsing the current URL hash
function serializeUrlCriteria()
{
	if(location.hash == "#" || location.hash == "")
	{
		$(".result").show();
		$(".result").addClass("Filter_ShownSearchResult");
		return;
	}
	var urlCriteria = location.hash.replace(/#/g,'').split("|");
	
	var serializedObj = {};
	for(var i=0; i < urlCriteria.length; i++)
	{
		// ex: layer(12,13)
		// from the search map the type of filter and it's values can be expressed out
		var searchMap = urlCriteria[i];
		var startOfValues = searchMap.indexOf("(");
		var type = searchMap.substring(0, startOfValues  );
		var values = searchMap.substring(startOfValues+1, searchMap.length-1).split(",")
		
		if(values[0] == "*")
		{
			values = getCriteriaValuesByTab(type)
		}
		
		// assign values to flagged object
		serializedObj[type] = values;
	}
	
	return serializedObj;
}



function processURL()
{
	// generate an object containing tab name attributes and an array of selected search/filter criteria
	var urlCriteria = serializeUrlCriteria();
	
	if($(urlCriteria).attr("clearance") != null)
	{
		urlCriteria["promotions"] = urlCriteria["clearance"];
	}
	
	if(urlCriteria == null)
	{
		// if there are no results: stop and make sure the results label notes the correct amount of products showing
		$("div[ProductID]").addClass("Filter_ShownSearchResult");
		$("#promotionBannerContainer").hide();
		hidePromotionalyRelatedMaterial();
		$(".Filter_ShownSearchResult").show();
		updateResultsReturnedLabels();
		return;
	}
	
	
	// get products from ProductID attribute instead of "result" class due to bug in IE 7 and/or 6
	// hide all resulting products before configuring and initiating searches and filters
	var products = $("div[ProductID]");
	products.hide();
	products.removeClass("Filter_ShownSearchResult");
	
	var filteredResults = [];
	// when criteria is checked off, its tab name (men, women, industry, etc.) creates an attribute in urlCriteria
	for (var type in urlCriteria)
	{
		// due to its even more custom look and feel (and "option" status), color has a separate filter flag
		var filterFlag = "Filter_Criteria_";
		switch(type)
		{
			case "color":
				filterFlag = "Filter_Option_";
			break;
			case "promotions":
			case "clearance":
				filterFlag = "Filter_Promotion_";
			break;
		}
		
		var idFlag = "SearchID";
		switch(type)
		{
			case "color":
				idFlag = "OptionID";
			break;
		}
		
		var tab = urlCriteria[type];
		if (tab != null) 
		{
			// create a temp array where search-resulting product id's will go
			var tmpArr = [];
			for (var i = 0; i < tab.length; i++) 
			{
				// grab search-nav item
				var searchDiv = $("div["+ idFlag +"='" + tab[i] + "']");
				var img = searchDiv.children(".Col").children("img");
				
				// if the search-nav item isn't selected, SELECT (but not CLICK) it
				if(!toBoolean(img.attr("selected")))
				{
					img.trigger("select");
				}
				
				// filter search results based on criteria/filter type
				var resultsForThisCriteria = $("." + filterFlag + tab[i]);
				/*
				for(var j=0; j < resultsForThisCriteria.length; j++)
				{
					// all the possible product id's that match the criteria's filter are stored in this array
					// which is then stored in the filteredResults array
					var res = $(resultsForThisCriteria[j]);
					tmpArr.push(res.attr("ProductID"));
				}
				*/
				$.each(resultsForThisCriteria, function()
				{
					var id = $(this).attr("ProductID");
					tmpArr.push(id);
				});
			}
			filteredResults.push(tmpArr);
		}
	}
	
	// each array (per tab) in the filtereedResults array represents the products being searched not filtered
	// the following code takes the searched results (on a per tab basis) and filters them (on a cross-tab basis)
	
	// because this is a filter, the most focused products are going to come from the array with the fewest products
	// find the smallest array
	var smallestArray = [];
	var smallestArrayIndex = 0;
	for (var m in filteredResults) 
	{
		if(smallestArray.length == 0 || filteredResults[m].length < smallestArray.length)
		{
			smallestArray = filteredResults[m];
			smallestArrayIndex = m;
		}
	}
	// remove smallest array from filteredResults -- this will be used as a comparison tool
	filteredResults[smallestArrayIndex] = null;
	
	// for each product id in the comparison array (smallest array), check to see if that id exists in any other tab
	for (var s in smallestArray) 
	{
		var idToCheck = smallestArray[s];
		for (var m in filteredResults) 
		{
			if(filteredResults[m] != null)
			{
				// if one of the id's from the comparison array is found in any of the other arrays, it is removed
				// from the comparison array -- this is the cross-tab filtration
				if($.inArray(idToCheck, filteredResults[m]) == -1)
				{
					smallestArray[s] = null;
					break;
				}
			}
		}
	}
	
	// once the filtration is complete, the comparison array now has the purest (un-repeated) list of product ids
	// that best match the search criteria and the cross-tab filtering
	// for each element in the array (each product id, if not null due to the filtering), grab the div
	// representing the product in the search results, display it, and flag it as a shown result for tabulation
	for(var p in smallestArray)
	{
		var pid = smallestArray[p];
		if(pid != null)
		{
			$("div[ProductID='"+ pid +"']").addClass("Filter_ShownSearchResult").show();
		}
	}
	
	// if the selection is a promotion -- hide regular results
	$("#promotionBannerContainer").hide();
	
	if(urlCriteria["promotions"] != null)
	{
		var standardItems = $(".standard_item");
		standardItems.hide();
		standardItems.removeClass("Filter_ShownSearchResult");
		
		if(urlCriteria.promotions.length > 1)
		{
			criteria.promotions = [urlCriteria.promotions.reverse()[0]];
			generateHash();
			processURL();
			//unselectAllCriteria("promotions");
		}
		// strip P from id (used to differenciate from other search/options) to get promo id
		var id = urlCriteria.promotions[0].replace(/P/g,"");
		if (urlCriteria["clearance"] == null)
		{
			var headerImg = $(".promotion[PromotionID=" + id + "]").attr("PromotionHeaderImage");
			$("#promotionBanner").attr("src", headerImg);
			$("#promotionBannerContainer").show();
		}
	}
	else
	{
		hidePromotionalyRelatedMaterial();
	}
	
	// update label which displaces result tabulation
	updateResultsReturnedLabels();
	
	// add url to history for back-stepping
	if (!StateManager.disregardFromHistory) 
	{
		history_Add();
	}
}


function dumpObject(obj)
{
	var output = "";
	for(var prop in obj)
	{
		output += prop + ":" + obj[prop] + "\n";
	}
	alert(output);
}


function hidePromotionalyRelatedMaterial()
{
	$(".promotion_clearance_only").hide();
	$(".promotion_clearance_only").removeClass("Filter_ShownSearchResult");
	//$(".promotion").hide();
	//$(".promotion").removeClass("Filter_ShownSearchResult");
	$("div[ProductID][PromotionID]").hide();
	$("div[ProductID][PromotionID]").removeClass("Filter_ShownSearchResult");
}




/*
function csCheckboxSearch(ID1, ID2, tab, filterName){
	if($(ID1).attr('checked') == false){
		$(ID1).attr('checked', true);
		$(ID2).attr("src", "/graphics/Icons/customedCheckbox"+tab+"_ON.gif");
		addCriteria(tab, filterName);
	}
	else{
		$(ID1).attr('checked', false);
		$(ID2).attr("src", "/graphics/Icons/customedCheckbox"+tab+".gif");
		removeCriteria(tab, filterName);
	}
}
*/

/*
function colorCheckBox(ID1, ID2, tab, filterName){
	if($(ID1).attr('checked') == false){
		$(ID1).attr('checked', true);
		//$(ID2).attr("src", "/graphics/Icons/customedCheckbox"+tab+"_ON.gif");
		$(ID2).addClass("selectedSwatchStyle");
		addCriteria(tab, filterName);
	}
	else{
		$(ID1).attr('checked', false);
		//$(ID2).attr("src", "/graphics/Icons/customedCheckbox"+tab+".gif");
		$(ID2).removeClass("selectedSwatchStyle");
		removeCriteria(tab, filterName);
	}
}
*/

/*
var runSearch = function() {
	$('#ajaxLoader').show();
	$.ajax({
		type: "POST",
		url: "/store/CFCs/webStore.cfc",
		dataType: "json",
		data: {
		   method: 'searchProducts',
		   criteria: $("input[@name='criteria']:checked").getValue()
		},
	success: processRes
	});
}



var processRes = function(results) {
	var newHTML = "";
		if (results.length > 0) {
			$.each(results, function(i, retProducts){					 
   				newHTML += '<div class="result"><div class="imageContainer" id="imageContainer' + i + '"><a href="javascript:;" class="quickViewBtn" onclick="showQuickView(' + retProducts.PRODUCTID + ');"></a><a href="/Store/Products/' + retProducts.URLNAME + '&criteria=' + $("input[@name='criteria']:checked").getValue() + '"><img src="' + retProducts.THUMBFILE + '" class="prodImage" id="prodImage' + i + '" width="94" height="106" alt="' + retProducts.PRODUCTNAME + '" /></a></div><div class="infoContainer"><h2><a href="/store/Products/' + retProducts.URLNAME + '">' + retProducts.PRODUCTNAME + '</a></h2><h4>' + formatCurrency(retProducts.PRICE) + '</h4><a href="javascript:;"  class="moreColors">more colors</a></div></div>';
		});
		$('#resultsContainer').html(newHTML);
		initQuickViewBtn();
	}
	else{
		newHTML+="No products found matching your search";
		$('#resultsContainer').html(newHTML);
	}
	
	$('#ajaxLoader').fadeOut('slow');
	
}
*/


function formatCurrency(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function displayCriteria()
{
	if(menFilters.length > 0)
	{
		$("#menFilters").html(menFilters.join(", "));
		$("#menFiltersContainer").show();
	}
	if(womenFilters.length > 0)
	{
		$("#womenFilters").html(womenFilters.join(", "));
		$("#womenFiltersContainer").show();
	}
	if(industryFilters.length > 0)
	{
		$("#industryFilters").html(industryFilters.join(", "));
		$("#industryFiltersContainer").show();
	}
	if(layerFilters.length > 0)
	{
		$("#layerFilters").html(layerFilters.join(", "));
		$("#layerFiltersContainer").show();
	}
	if(climateFilters.length > 0)
	{
		$("#climateFilters").html(climateFilters.join(", "));
		$("#climateFiltersContainer").show();
	}
	if(fabricFilters.length > 0)
	{
		$("#fabricFilters").html(fabricFilters.join(", "));
		$("#fabricFiltersContainer").show();
	}
	if(colorFilters.length > 0)
	{
		$("#colorFilters").html(colorFilters.join(", "));
		$("#colorFiltersContainer").show();
	}
}

function addCriteria(tab, filterName)
{
	switch(tab.toLowerCase())
	{
		case "men":
			menFilters.push(filterName);
		break;
		case "women":
			womenFilters.push(filterName);
		break;
		case "industry":
			industryFilters.push(filterName);
		break;
		case "layer":
			layerFilters.push(filterName);
		break;
		case "climate":
			climateFilters.push(filterName);
		break;
		case "fabric":
			fabricFilters.push(filterName);
		break;
		case "color":
			colorFilters.push(filterName);
		break;
	}
	
	displayCriteria();
	$("#searchResultsContainer #noResults").hide();
}

function removeCriteria(tab, filterName)
{
	switch(tab.toLowerCase())
	{
		case "men":
			for (i=0; i < menFilters.length; i++){
				if(menFilters[i] == filterName){
					menFilters.splice(i, 1);
				}
			}
			if(menFilters.length == 0){
				$("#menFiltersContainer").hide();
			}
		break;
		case "women":
			for (i=0; i < womenFilters.length; i++){
				if(womenFilters[i] == filterName){
					womenFilters.splice(i, 1);
				}
			}
			if(womenFilters.length == 0){
				$("#womenFiltersContainer").hide();
			}
		break;
		case "industry":
			for (i=0; i < industryFilters.length; i++){
				if(industryFilters[i] == filterName){
					industryFilters.splice(i, 1);
				}
			}
			if(industryFilters.length == 0){
				$("#industryFiltersContainer").hide();
			}
		break;
		case "layer":
			for (i=0; i < layerFilters.length; i++){
				if(layerFilters[i] == filterName){
					layerFilters.splice(i, 1);
				}
			}
			if(layerFilters.length == 0){
				$("#layerFiltersContainer").hide();
			}
		break;
		case "climate":
			for (i=0; i < climateFilters.length; i++){
				if(climateFilters[i] == filterName){
					climateFilters.splice(i, 1);
				}
			}
			if(climateFilters.length == 0){
				$("#climateFiltersContainer").hide();
			}
		break;
		case "fabric":
			for (i=0; i < fabricFilters.length; i++){
				if(fabricFilters[i] == filterName){
					fabricFilters.splice(i, 1);
				}
			}
			if(fabricFilters.length == 0){
				$("#fabricFiltersContainer").hide();
			}
		break;
		case "color":
			for (i=0; i < colorFilters.length; i++){
				if(colorFilters[i] == filterName){
					colorFilters.splice(i, 1);
				}
			}
			if(colorFilters.length == 0){
				$("#colorFiltersContainer").hide();
			}
		break;
	}
	
	if(menFilters.length == 0 && womenFilters.length == 0 && industryFilters.length == 0 &&layerFilters.length == 0 && climateFilters.length == 0 && fabricFilters.length == 0 && colorFilters.length == 0){
		$("#searchResultsContainer #noResults").show();
	}
	
	displayCriteria();
}


function initQuickView()
{
	qvstars = new RatingStarGroup();
	qvstars.forceSplitSnapping = false;
	qvstars.allowInteractivity = false;
	
	var starsContainer = $("#quickViewRatingStars");
	starsContainer.css("marginLeft", -10);
	starsContainer.append(qvstars.getControl());
	
	initQuickViewBtn();
}


function initQuickViewBtn(){
	
	$(".imageContainer").bind("mouseover", function(e){
		$("#"+e.currentTarget.id +" .quickViewBtn").show();										
	});
	$(".imageContainer").bind("mouseleave", function(e){
		$("#"+e.currentTarget.id +" .quickViewBtn").hide();										
	});
	/*
	$(".prodImage").bind("mouseover", function(e){
		$("#"+e.currentTarget.id +" .quickViewBtn").show();										
	});
	*/
}

var altImagesTotal;
var processQVResult = function(result) {
	
	optionCombos = result.OPTIONSCOMBOS;
	
	$('#bigImage').attr('src',result.IMAGEFILE);
	$('#quickRightCol h3').html(result.PRODUCTNAME);
	if(formatCurrency(result.PRICE) == '$0.00'){
		$('#quickRightCol h4').html('');
	}
	else{
		$('#quickRightCol h4').html(formatCurrency(result.PRICE));
	}
	
	if (result.PROMOID == 0) 
	$('#viewFullDetailsBtn').attr('href','/store/Products/' + result.URLNAME);
	else
	$('#viewFullDetailsBtn').attr('href','/store/Products/' + result.URLNAME + '&pid=' + result.PROMOID);
	$('#productFeaturesBox').html(result.TEXT4);
	prodNumImages = result.TEXT2;
	
	$("#qvBigImage").html('');
	$("#qvBigImage").image('http://silverscapem.liquifire.com/silverscapem?source=url[file://'+result.SKUBASE+'-'+result.DEFAULTCOLORCODE+'-1.png]&scale=width[222],height[250],options[pad],fill[none]&optimize&sink=format[PNG]',function(){																																																																		
		$(this).parent('div').removeClass("loading");
		$(this).show();
	});
	
	altImagesTotal = result.TEXT2;
	for(var i = 1; i<= altImagesTotal; i++){
		$('#quickViewThumbContainer').append('<div class="thumbnailAlt" id="altImg'+i+'"><img src="http://silverscapem.liquifire.com/silverscapem?source=url[file://'+result.SKUBASE+'-'+result.DEFAULTCOLORCODE+'-'+i+'.png]&scale=width[26],height[31],options[pad],fill[none]&optimize&sink=format[PNG]" onclick="qvSwitchBigImg(\'http://silverscapem.liquifire.com/silverscapem?source=url[file://'+result.SKUBASE+'-'+result.DEFAULTCOLORCODE+'-'+i+'.png]&scale=width[222],height[250],options[pad],fill[none]&optimize&sink=format[PNG]\');"/></div>');
	}
	
	
	$("#quickViewNoReviewsLink").attr("href", $('#viewFullDetailsBtn').attr('href'));
	
	qvstars.setSelectedStarValue(result.REVIEWS.AVERAGERATING);
	if(parseFloat(result.REVIEWS.AVERAGERATING) == 0)
	{
		$("#quickViewRatingStarsNoReviews").show();
		$("#quickViewRatingStars").hide();
	}
	else
	{
		$("#quickViewRatingStarsNoReviews").hide();
		$("#quickViewRatingStars").show();
	}
	
	var colorHTML = "";
	//var sizeHTML = '<li><a id="defaultSizeSelect">SIZE</a></li>';
	var sizeHTML = '<div class="selectionContainer dkSelect" id="quickSizeSelect" onSelect=""><input type="hidden" class="selectedSize" name="size" id="size" value="" /><div class="dkDisplayedSelect"><img src="/graphics/select/selectOffLeft.gif" class="dkSelectLeftImg" /><div class="dkSelectedItem">Select</div><img src="/graphics/select/selectOffRight.gif" class="dkSelectRightImg" /></div><div class="dkOptionsContainer"><ul class="dkOptionsUl">';
	
	var optionArray;
	$('#color,#size').val('');
	if (result.OPTIONSSTRUCT.Colors) {
		$.each(result.OPTIONSSTRUCT.Colors.CHOICES, function(i, currentColor) { 
			
			if(currentColor.SKUCODE == result.DEFAULTCOLORCODE){
				$('#color').val(currentColor.VALUE);
				optionArray = result.OPTIONSCOMBOS[currentColor.VALUE].toString().split(',');
			}
			
			colorHTML += '<img src="' + currentColor.IMAGE1 + '" class="swatch swatchoption';
			
			if(result.DEFAULTCOLORCODE == currentColor.SKUCODE){
				colorHTML +=' selectedSwatchStyle';
				
			}
			colorHTML += '" alt="' + currentColor.TEXT +'" title="' + currentColor.TEXT + '" width="13" height="13" value="' + currentColor.VALUE + '" skubase="'+result.SKUBASE+'" skucode="'+currentColor.SKUCODE+'" />';	
		});		
	}
	
	
	if (result.OPTIONSSTRUCT.Sizes) {
		$.each(result.OPTIONSSTRUCT.Sizes.CHOICES, function(i, currentSize) {
			sizeHTML += '<li';
			if(ArrayIndexOf(optionArray,currentSize.VALUE.toString()) == -1){
				sizeHTML += ' style="display:none;"';
			}
			sizeHTML += '><span class="item" id="' + currentSize.VALUE + '"><span class="dkhoverLeft"></span><span class="dkhoverMiddle">' + currentSize.TEXT + '</span><span class="dkhoverRight"></span></span></li>';
			//sizeHTML += '<li class="options" id="selection' + i + '"><a href="javascript:;" onClick="selectSize(';
			//sizeHTML += "'" + currentSize.VALUE + "','#selection" + i + "','" + currentSize.TEXT + "'";
			//sizeHTML += ');return false;">' + currentSize.TEXT + '</a></li>';
		});
	}
	sizeHTML += '</ul></div><div class="clear"></div></div>';
	
	$("#swatchContainer").html(colorHTML);
	$("#sizeSelector").html(sizeHTML);
	$(".swatchoption").unbind("click");
	$(".swatchoption").bind("click", function(e){
		qvChangeColor(e);
	});
	$('#addToCart').unbind('click');
	if (result.TEXT6 != '1') {
		if (result.SENDPRICE) {
			$('#addToCart').click(function() {
				addItemToCart(result.PRODUCTID, result.PRICE);					  
			});
		} else {
			$('#addToCart').click(function() {
				addItemToCart(result.PRODUCTID);					  
			});
		}
	} else {
		$('#addToCart').click(function() {
			alert('This product is not available for purchase over the DRIFIRE webstore. Please contact a DRIFIRE sales representative at 1.800.419.3671 for more information.');						  
		});
	}
	$('#addToRegistryBtn').unbind('click');
	if (result.TEXT6 != '1') {
		$('#addToRegistryBtn').click(function() {
			saveItemToRegistry(result.PRODUCTID);
		});
	} else {
		$('#addToRegistryBtn').click(function() {
		alert('This product is not available for purchase over the DRIFIRE webstore. Please contact a DRIFIRE sales representative at 1.800.419.3671 for more information.');
		});
	}
	$("#quickAjaxloader").hide();
	$("#quickViewInnerContainer").show();
	
	tooltip();
	initCustomSelects();
	initSelectWidths(0);
}

var qvSwitchBigImg = function(image) {
	$("#qvBigImage").html('');
	$("#qvBigImage").image(image,function(){																																																																		
		$(this).parent('div').removeClass("loading");
		$(this).show();
	});
}

/*
if(!Array.indexOf){
	Array.prototype.indexOf = function(obj){
	    for(var i=0; i<this.length; i++){
	        if(this[i]==obj){
	            return i;
	        }
	   }
	   return -1;
	}
}
*/
function qvChangeColor(e){
	$(".selectedSwatchStyle").removeClass("selectedSwatchStyle");
	colorName = $(e.currentTarget).attr("alt");
	$('#color').val($(e.currentTarget).attr("value"));
	$("#colorSelection").html(colorName);
	$(e.currentTarget).addClass("selectedSwatchStyle");
	
	var skubase = $(e.currentTarget).attr("skubase");
	var skucode = $(e.currentTarget).attr("skucode");
	
	
	
	$("#qvBigImage").html('');
	$("#qvBigImage").image('http://silverscapem.liquifire.com/silverscapem?source=url[file://' + skubase + '-' + skucode + '-1.png]&scale=width[222],height[250],options[pad,fit,limit],fill[transparent]&transparent=color[white]&optimize&sink=format[PNG]',function(){																																																																		
			$(this).parent('div').removeClass("loading");
			$(this).show();
	});
	var thtml = "";
	//updateAltImages
	for (i=1;i<=altImagesTotal;i++)  {
		$("#altImg" + i).html('');
		$("#altImg" + i).image('http://silverscapem.liquifire.com/silverscapem?source=url[file://' + skubase + '-' + skucode + '-' + i + '.png]&scale=width[26],height[31],options[pad,fit,limit],fill[transparent]&transparent=color[white]&optimize&sink=format[PNG]',function(){																																																																/* $("#alt" + i).attr('onclick',"switchBigImage('http://silverscapem.liquifire.com/silverscapem?source=url[file://" + skubase + "-" + skucode + "-' + i + '.png]&scale=width[349],height[467],options[pad,fit,limit],fill[transparent]&transparent=color[white]&sink=format[PNG,JPG,GIF],quality[80]');");*/
	$(this).parent('div').removeClass("loading");
	$(this).show();
			});$("#altImg" + i).attr('imageNum',i);
		$("#altImg" + i).unbind('click');
		$("#altImg" + i).click(function(e) {
			e = e || window.event;
			var obj = e.target || e.srcElement;
			qvSwitchBigImg('http://silverscapem.liquifire.com/silverscapem?source=url[file://' + skubase + '-' + skucode + '-' + $(obj.parentNode).attr('imageNum') + '.png]&scale=width[222],height[250],options[pad,fit,limit],fill[transparent]&transparent=color[white]&optimize&sink=format[PNG]');
			});
	}	
	
	$('.dkOptionsUl li').css('display' ,'block');
	var optionList = optionCombos[$(e.currentTarget).attr("value")];
	var optionsArray = optionList.toString().split(',');
	$.each($('.dkOptionsUl li'), function(){
		var spanId = $(this).children("span").attr('id');
		if(ArrayIndexOf(optionsArray,spanId) == -1){
			$(this).hide();
		}
	});
	
	
	
}

function showQuickView(id, promotionId){
	//$('#ajaxLoader').show();
	$("#quickViewThumbContainer").html('');
	$('#bigImage').attr('src','');
	$("#quickViewContainer").show();
	
	/*$("#quickViewContainer").modal({opacity:0,onClose: function (dialog) {
	  dialog.data.fadeOut('normal', function () {
		$.modal.close(); // must call this!
	  });
}}
								   );*/
	//$("#quickViewInnerContainer").show();
	var ws = new webStore();
	ws.setCallbackHandler(processQVResult);
	ws.setErrorHandler(myErrorHandler);
	ws.getProductDetail(id, promotionId);
	return false;
}

function sizingChart(){
	var sizingChart = window.open('#SizingChart','Sizing Chart','width=625,height=143,scrollbars=no,menubar=no,resizable=no,toolbar=no,location=no,status=no, location=no');
	sizingChart.document.write('<img src="/graphics/store/sizingChart.gif" width="610" height="128" alt="Sizing Chart" />');
}

function ArrayIndexOf(arr, value)
{
	var inArray = false;
	for(var i in arr)
	{
		if(arr[i] == value)
		{
			inArray = true;
			break;
		}
	}
	
	return inArray;
}

