
(function($) {
	$(document).ready(function() {

		// Bind quickfinder open/close
		var qfCloseTimer = null;
		var disableCloseByMouseout = false;
		$("#header #quickfinder").hover(function() {
			clearTimeout(qfCloseTimer);
			$(this).addClass("hover");
			$(this).find(".selections").css("display", "block");
			$("#quickfinder").unbind(".quickfinderClose").one("click.quickfinderClose", function() {
				disableCloseByMouseout = true;
			});
		}, function() {
			var that = this;
			qfCloseTimer = setTimeout(function() {
				if (!disableCloseByMouseout) {
					$(that).removeClass("hover");
					$(that).find(".selections").css("display", "none");
					disableCloseByMouseout = false;
		}
			}, 50);
		});
		
		// Close quickfinder when user clicks away from it
		$(document).bind("click.quickfinder", function(e) {
			if (!$(e.target).is("#quickfinder") && $(e.target).parents("#quickfinder").size() == 0) {
				$("#header #quickfinder .selections").css("display", "none");
				disableCloseByMouseout = false;
			}
		});
			
		// Get the initial quickfinder state. 
		// Always assumed that we have the selectbox for sectionNumber rendered by the jsp.
		updateQuickfinder($("#quickfinder .select:first")[0]);
			
		// initialize the select boxes, add "selectbox" behavior to our stylized psuedo-selectboxes
		$("#quickfinder .select").selectbox(function(opt, val) {
			updateQuickfinder($(this).parents(".select:first"));
		});
		
		// Bind submit and reset controls
		$("#quickfinder .submit").click(function(e) {
			if ($("#quickfinder .prod-count").text().indexOf(": 0") >= 0) {
				window.document.location = 'category.htm?' + $.param(getQuickfinderState());
			}else {
				window.document.location = 'filterresults.htm?' + $.param(getQuickfinderState());
			}
			e.preventDefault();
		});
	
		$("#quickfinder .reset").click(function(e) {
			updateQuickfinder($("#quickfinder .select:first")[0]);
			e.preventDefault();
		});
		
	});
			
	function updateQuickfinder(updatedSelectBox) {
		var quickfinder = $("#quickfinder");
		var indexUpdated = quickfinder.find(".select").index(updatedSelectBox);
		quickfinder.find(".select:gt(" + indexUpdated + ")").setSelected("").css("visibility", "hidden");
		var qfState = getQuickfinderState();
			
		getQuickfinderData(qfState, function(data) {
			// Remove all existing selectboxes, except for the first original one, we'll clone it
			// to create others
			quickfinder.find(".select").not(":first").remove();
	
			// Create and populate the category select
			if (data.quickfinder.category.option.length > 1) {
				var selectbox = $("#quickfinder .select:first").clone();
				selectbox.attr('id','');
				var selectOption = selectbox.find(".option:first").clone();
				selectbox.find(".option").remove();
				selectbox.find(".name").text("categoryNumber");
	
				for (var i = 0; i < data.quickfinder.category.option.length; i++) {
					var option = data.quickfinder.category.option[i];
					var name = option.name;
					if (i == 0) {
						name = "Select Product Type";
        }
					var val = option.value;
					if (val == 'ALL') {
						val = "";
		}
		
					selectOption = selectOption.clone();
					selectOption.find(".displayText").text(name);
					selectOption.find(".value").text(val);
					selectbox.append(selectOption);
		}
	
				quickfinder.find(".select:last").after(selectbox);
				selectbox.selectbox(function(opt, val) {
					updateQuickfinder($(this).parents(".select:first"));
				});
				selectbox.setSelected(qfState.categoryNumber);
	}
	
			// Create and populate the other attribute select boxes, if any
			if (data.quickfinder.attributes) {
				for (var i = 0; i < data.quickfinder.attributes.length; i++) {
					var attributeData = data.quickfinder.attributes[i].attributeList;
					if (!attributeData) {
						continue;
        }
		
					selectbox = $("#quickfinder .select:first").clone();
					selectbox.attr('id','');
					selectOption = selectbox.find(".option:first").clone();
					selectbox.find(".option").remove();
					selectbox.find(".name").text("filter_" + i);
	
					for (var j = 0; j < attributeData.length; j++) {
						var option = attributeData[j];
						var name = option.name;
						if (j == 0) {
							var title = data.quickfinder.titles[i].entry;
							if (title) { 
								name = name + " " + title ;
	}
			}
						var val = option.value;

						selectOption = selectOption.clone();
						selectOption.find(".displayText").text(name);
						selectOption.find(".value").text(val);
						selectbox.append(selectOption);
		}
		
					quickfinder.find(".select:last").after(selectbox);
					selectbox.selectbox(function(opt, val) {
						updateQuickfinder($(this).parents(".select:first"));
					});
					selectbox.setSelected(qfState["filter_" + i]);
					}
					}
	
			// update the prod count
            quickfinder.find(".prod-count").text("Products: " + data.quickfinder.productcount);
            
            if (data.quickfinder.productcount == 0) {
            	quickfinder.find(".prod-count").css("display", "none");
            	quickfinder.find(".reset").css("margin-top", "20px");
		} else {
            	quickfinder.find(".prod-count").css("display", "block");
            	quickfinder.find(".reset").css("margin-top", "");
		}
		
            // Hide submit button if no category is selected
			if (qfState.categoryNumber && qfState.categoryNumber != null) {
				quickfinder.find(".bottom-bar").css("display", "block");
				quickfinder.find(".reset").css("display", "");
			} else {
				quickfinder.find(".bottom-bar").css("display", "none");
				quickfinder.find(".reset").css("display", "none");
					}
		});
					}
		
	function getQuickfinderState() {
		var data = {};
		$("#quickfinder .select").each(function() {
			var name = $(this).find(".name").text();
			var val = $(this).getSelected();
			if (val != null && val != "") {
				data[name] = val;
				}
		});
		return data;
			}
	
	function getQuickfinderData(requestParams, onSuccess) {
		$.ajax({
			url : "/onlinecatalog/getquickfindervalues.htm",
			data : requestParams,
			dataType : "json",
			cache : false,
			success : function(data) {
				if ($.isFunction(onSuccess)) {
					onSuccess(data);
				}
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
			}
		});
		}
				
				
})(jQuery);
		
	
// jquery extension to apply selectbox behavior to specially crafted divs.
(function($) {
	var NAMESPACE = "gorilla.selectbox";
	var registeredSelectBoxes = [];
	$.data(NAMESPACE + ".selectboxes", registeredSelectBoxes);
	
	$.fn.extend({
		selectbox : function(onchange) {
			if (registeredSelectBoxes == null) {
				registeredSelectBoxes = [];
				$.data(NAMESPACE + ".selectboxes", registeredSelectBoxes);
				}
			this.each(function() {
				registeredSelectBoxes.push(this);
				$(this).click(function(e) {
					if (isSelectBoxOpen(this)) {
						var selectedOption = $(e.target);
						if (!selectedOption.is(".option:not(.displayed)")) {
							selectedOption = $(e.target).parents(".option:first");
			}
						if (selectedOption.is(".option:not(.displayed)")) {
							$(this).find(".option").removeClass("selected");
							selectedOption.addClass("selected");
							
							var selectedOpt = selectedOption.children(".displayText:first").text();
							var selectedVal = selectedOption.children(".value:first").text();
							if ($.isFunction(onchange)) {
								setTimeout(function() {
									onchange.call(selectedOption[0], selectedOpt, selectedVal);
								},10);
		}
				}
						closeSelectBox(this);
		} else {
						openSelectBox(this);
				}
					e.preventDefault();
				});
			});
				
            return this;
		},
		setSelected :  function(val) {
			if (!val || val == null || val == "") {
				val = "";
					}
			this.each(function() {
				closeSelectBox(this);
				$(this).find(".option").removeClass("selected displayed");
				$(this).find(".option").each(function() {
					if ($(this).find(".value").text() == val) {
						$(this).addClass("selected displayed");
					}
				});
				
				if ($(this).find(".option.selected").size() == 0) {
					$(this).find(".option:first").addClass("selected displayed");
				}
			});
            return this;
		},
		getSelected : function() {
			return $(this).find(".option.selected .value").text();
            return this;
 			}
		
	});
	
	
	function openSelectBox(selectBox) {
		if (isSelectBoxOpen(selectBox)) {
			return;
				}
		$(registeredSelectBoxes).each(function() {
			closeSelectBox(this);
		});

		var selectBox = $(selectBox);
		
		// Display the default option at the top of the select box when opened.
		selectBox.find(".option").css("display", "block");
		var selected = selectBox.find(".option.selected");
		selected.removeClass("displayed");
		var tmpOption = selected.clone();
		tmpOption.removeClass("option selected").addClass("displayed");
		selectBox.prepend(tmpOption);
		
		// insert a placeholder in place of the select box since we are going to absolutely position it
		var placeholder = selectBox.clone();
		selectBox.after(placeholder);
				
		selectBox.data(NAMESPACE + ".position", selectBox.css("position"));
		selectBox.data(NAMESPACE + ".top", selectBox.css("top"));
		selectBox.data(NAMESPACE + ".left", selectBox.css("left"));
		selectBox.data(NAMESPACE + ".z-index", selectBox.css("z-index"));
		selectBox.data(NAMESPACE + ".height", selectBox.css("height"));
		selectBox.data(NAMESPACE + ".placeholder", placeholder);
				
		var position = selectBox.position();
		selectBox.css({
			"position" : "absolute",
			"top" : position.top + "px",
			"left" : position.left + "px",
			"height" : "auto",
			"z-index" : "1"
		});
		selectBox.addClass("opened");
		
		selectBox.find(".option").hover(function() {
			$(this).addClass("mouseover");
		}, function() {
			$(this).removeClass("mouseover");
		});
	
	
		setTimeout(function() {
			$(document).one("click." + NAMESPACE, function(e) {
				if ($(e.target).parents(selectBox).size() == 0) {
					return;
		}
				closeSelectBox(selectBox);
			});
			selectBox.find(".option.selected").addClass("mouseover");
		}, 20);
	}
	
	function closeSelectBox(selectBox) {
		if (!isSelectBoxOpen(selectBox)) {
			return;
	}
		var selectBox = $(selectBox);
		selectBox.find(".option").css("display", "");
		selectBox.find(".displayed").remove();
		selectBox.find(".selected").addClass("displayed");
	
		selectBox.find(".option").removeClass("mouseover").unbind('mouseenter mouseleave');
	
		selectBox.css({
			"position" : selectBox.data(NAMESPACE + ".position"),
			"top" : selectBox.data(NAMESPACE + ".top"),
			"left" : selectBox.data(NAMESPACE + ".left"),
			"height" : selectBox.data(NAMESPACE + ".height"),
			"z-index" : selectBox.data(NAMESPACE + ".z-index")
		});
	
		selectBox.data(NAMESPACE + ".placeholder").remove();
		selectBox.removeClass("opened");
	
		$(document).unbind("click." + NAMESPACE);
	}
	
	function isSelectBoxOpen(selectBox) {
		return $(selectBox).hasClass("opened");
	}
})(jQuery);
	
