﻿$(document).ready(function(){
	searchSuggest();
	filterSelectSubmit();
});

$(window).load(function(){
	//matchProductHeight();
});

function searchSuggest(){
	$(".filterSearch").keyup(function(){
		var search = $(this);
		var offset = search.offset();
		var term = search.val();
		$(".filterSearch").val(term);
		if (term.length <= 1){
			$("#filterSearchProducts").remove();
			return false;
		}
		"{'origin':'value'}"
		var categoryid = $("#filterCategoryID").val();
		if (categoryid == null) categoryid = 0;
		var sectionid = $("#filterSectionID").val();
		if (sectionid == null) sectionid = 0;
		var genreid = $("#filterGenreID").val();
		if (genreid == null) genreid = 0;
		var vectorid = $("#filterVectorID").val();
		if (vectorid == null) vectorid = 0;
		var manufacturerid = $("#filterManufacturerID").val();
		if (manufacturerid == null) manufacturerid = 0;
		var json = "{'SearchTerm':'" + term + "',"+
			"'CategoryID':" + categoryid + "," +
			"'SectionID':" + sectionid + "," +
			"'GenreID':" + genreid + "," +
			"'VectorID':" + vectorid + "," +
			"'ManufacturerID':" + manufacturerid + "}";
		$.ajax({
			type: "POST",
			contentType: "application/json; charset=utf-8",
			url: "SearchService.asmx/Search",
			data: json,
			dataType: "json",
			success: function(result){
				$("#filterSearchProducts").remove();
				if (result.d.length > 0){
					var list = $('<ul id="filterSearchProductsList" />');
					$.each(result.d, function(index, product){
						if (index % 2 == 0){
							list.append('<li class="odd"><a href="'+product.Url+'">'+product.Name+'</a></li>');
						} else {
							list.append('<li class="even"><a href="'+product.Url+'">'+product.Name+'</a></li>');
						}
					});
					list.append('<li><a href="search.aspx?SearchTerm='+term+'">See All Results</a>');
					$('<div id="filterSearchProducts" />').css({"position":"absolute","left":offset.left+1,"top":offset.top+20}).prepend(list).prependTo("body");
				}
			},
			error: function(xhr, msg){
				$("#filterSearchProducts").remove();
				//alert(xhr.responseText);
			}
		});
	}).blur(function(){
		setTimeout("searchHide()", 300);
	}).focus(function(){
		var offset = $(this).offset();
		$("#filterSearchProducts").css({"position":"absolute","left":offset.left+1,"top":offset.top+20}).show();
	});
};

function searchHide(){
	$("#filterSearchProducts").hide();
};

function filterSelectSubmit(){
	$('#filterForm select').change(function(){
		$('#filterForm').submit();
	});
};

function matchProductHeight(){
	$('.productRow').each(function(){
		var row = $('.product', $(this));
		var height = 0;
		row.each(function(index){
			var outerheight = $(this).outerHeight(true);
			if (outerheight > height){
				height = outerheight;
			}
		});
		row.height(height);
	});
};