var mytimer = {};
var ajaxCalling = false;

function StartFilterAction()
{
	if(ajaxCalling == false)
	{
		$.clearTimer(mytimer);
		mytimer = $.timer(1000,function(){
			ajaxCalling = true;
			ReloadPage(CreateFilters(), CreatePriceFilter(), CreateTextSearch(), CreateProductSize(), 1, $("#pageSize").attr("value"),0);
		},function(){});
	}
}
function StartReloadAction()
{
	if(ajaxCalling == false)
	{
		ReloadPage(CreateFilters(), CreatePriceFilter(), CreateTextSearch(), CreateProductSize(), $("#currentPage").attr("value"), $("#pageSize").attr("value"),1);
	}
}
function ClearFilters()
{
	$(".filter-child-link.checked, .filter-parent-link.checked").removeClass("checked").addClass("unchecked");
	$("#filter-first").attr("value","");
	window.location.hash = "";
}
function ClearFiltersPlus()
{
	$("#filter-plus-price-from option").removeAttr("selected").eq(0).attr("selected","selected");
	$("#filter-plus-price-to option").removeAttr("selected").filter(":last").attr("selected","selected");
	$("#filter-plus-price-max").attr("value","");
}
function CreateTextSearch()
{
	hash = $.deparam.fragment();
	var textsearch = "";
	if(hash.search != undefined) {
		textsearch = hash.search;
	}
	return textsearch;
}
function CreateProductSize()
{
	hash = $.deparam.fragment();
	var productsize = "";
	if(hash.productsize != undefined) {
		productsize = hash.productsize;
	}
	return productsize;
}
function CreateFilters()
{
	filter = ""
	$(".filters-group").each(function(){
		subfilter = ""
		firstSubFilter = true
		$(this).find(".filter-child-item:has(a.checked) span.filter-id").each(function(){
			if(!firstSubFilter)
			{
				subfilter += "-"
			}
			else
			{
				firstSubFilter = false;	
			}
			
			id = $(this).text();
			if(id.length == 1)
			{
				id = "0" + id;	
			}
			
			subfilter += id;
		});
		
		if(subfilter.length > 0)
		{
			filter += "("+subfilter+")";
		}
	});
	
	return filter;
}
function CreatePriceFilter()
{
	if($("#filter-plus-price-from option:not(:first):selected").size() > 0 || $("#filter-plus-price-to option:not(:last):selected").size() > 0)
	{
		return "" + $("#filter-plus-price-from option:selected").attr("value") + "-" + $("#filter-plus-price-to option:selected").attr("value")
	}
	
	return "";
}
function DefaultLoad()
{
	ReloadPageHash($.deparam.fragment());
}
function ReloadPageHash(hash)
{
	filter = "";
	page = 1;
	size = 18;
	price = "";
	productsize = "";
	textsearch = "";
	brand = 0;

	if(hash.filter != undefined){
		filter = hash.filter;
	}	
	if(hash.page != undefined) {
		page = hash.page;
	}	
	if(hash.size != undefined) {
		size = hash.size;
	}	
	if(hash.first != undefined) {
		if($("#filters-group-"+hash.first).size() > 0) {
			SetFirstByElement($("#filters-group-"+hash.first));
		}
	}
	if(hash.price != undefined){
		price = hash.price;	
	}
	if(hash.productsize != undefined){
		productsize = hash.productsize;	
	}
	if(hash.search != undefined) {
		textsearch = hash.search;
	}

	if(hash.brand != undefined){
		brand = hash.brand;	
	}
	ReloadPage(filter, price, textsearch, productsize, page, size, 0, brand);
}

function ReloadPage(filter, pricefilter, textsearch, productsize, page, size,  productsOnly, brand)
{	
	//Close menu
	$(".sf-menu li").find("a.foldout").removeClass("foldoutHover");
	$(".sf-menu li").find(".mega").stop().hide();
		
	if(size == undefined)
	{
		size = 18;	
	}

	if(brand == undefined)
	{
		brand = 0;
		//var params = $.deparam.fragment();
		//if(params.brand != undefined){
		//	brand = params.brand;	
		//}else{
		//	brand = 0;
		//}
				

		myuniquenamebrands = $(".filter-group-brands .filter-child-link.checked");
		if(myuniquenamebrands.length == 1)
		{
			newbrand = myuniquenamebrands.siblings("span.filter-id").text();
			
			if(brand != newbrand)
			{
				brand = newbrand;
			}
		}

		myuniquenamebrands = $("#filters-group-337 .filter-child-link.checked");
			if(myuniquenamebrands.length == 1)
			{
				newbrand = myuniquenamebrands.siblings("span.filter-id").text();
				
				if(brand != newbrand)
				{
					brand = newbrand;
				}
			}
	}

	textsearch = textsearch.replace(/[^a-zA-Z_0-9\s]+/g, "");

	first = GetFirst();
	first = first.slice(first.lastIndexOf("-")+1);
	if(filter != "" || page != 1 || size != 18 || first != "" || price != "" || textsearch != "") {
		var hash = $.param({ 
			filter: filter,
			price: pricefilter,
			search: textsearch,
			productsize: productsize,
			page: page,
			size: size,
			first: first,
			brand: brand
		});
		//alert(hash);
		//if(window.location.hash != ("#" + hash))
		//{
			//alert(window.location.hash + '\n#' + hash);
			window.location.hash = hash;
			
			//Scroll 2 top off page
			$('html,body').scrollTop(0);
		//}

	}
	
	$.ajax({
		async: true,
		type: 'get',
		cache: true,
		data: {
			filter: filter,
			price: pricefilter,
			search: textsearch,
			productsize: productsize,
			page: page,
			size: size,
			brand: brand,
			type: "json",
			productsOnly: productsOnly ? '1' : '0',
			currency: $("input[@name='currency']:checked").val()
		},
		url: "/includes/incAjaxfilter.asp",
		dataType: "json",
		beforeSend: function(){PrepareContent()},
		success: function(data){SetContent(data);},
		error: function(data){SetError();},
		complete: function(){ajaxCalling = false;}
	});	
}
function SetError()
{
	$("#loadProducts").children().fadeOut().remove();
	$("#loadProducts").append($("<div></div>").addClass("product-error")
		.text("Tijdens de zoekopdracht is een fout opgetreden"));
	
	$("#products-loading").hide();
	$("#gray").unblock(); 
	$("#showroomfilter").unblock(); 
}
function PrepareContent()
{	
	productSettings =  {
		message: null, 
		overlayCSS: { 
			backgroundColor: "#FFFFFF",
			backgroundImage: "url('/img/products-loading.gif')",
			backgroundRepeat: "no-repeat",
			backgroundPosition: "50% 100px",
			cursor: "default"
		} 
	}
	
	filterSettings =  {
		message: null, 
		overlayCSS: { 
			backgroundColor: "#FFFFFF",
			backgroundImage: "url('/img/filter-loading.gif')",
			backgroundRepeat: "no-repeat",
			backgroundPosition: "50% 100px",
			cursor: "default"
		} 
	}
	
	if ( "https:" == document.location.protocol && $.browser.msie)
	{
		delete filterSettings.overlayCSS.backgroundImage;
		delete productSettings.overlayCSS.backgroundImage;
	}

	//Geblokte Functionaliteit (Geblokte Filter & Products View bij Ajax)
	$("#gray").block(productSettings); 
	$("#showroomfilter").block(filterSettings); 
}
function SetContent(data)
{
	if(data != undefined)
	{
		$("#loadProducts").children().fadeOut().remove()
		$("#loadProducts").append(data.products);
		
		$("#loadProducts .product-img-container a").each(function(){
			$(this).attr("href",$(this).attr("href") + "&refUrl=" + escape(document.location));
		});
		
		//Geblokte Functionaliteit (Geblokte Filter & Products View bij Ajax)
		$("#gray").unblock(); 
		$("#showroomfilter").unblock(); 
		
		$("#products-loading").hide();
	
		if($.isArray(data.filters))
		{
			SetFilters(data.filters);
		}
		
		if(data.filtersPlus != undefined)
		{
			SetFiltersPlus(data.filtersPlus);
		}
		
		SetHeader(data.header);
	}
	else
	{
		SetError();
	}
}
function SetFilters(filters)
{
	$.each(filters,function(index,filter){
		if($.isArray(filter.filters))
		{
			SetFilters(filter.filters);
		}
		else
		{
			EnableChildItem($("#filter-child-item-" + filter.sectionID),filter.nrOfProducts > 0);
			CheckChildLink($("#filter-child-link-" + filter.sectionID),(filter.checked == 1));
		}
	});
}
function SetFiltersPlus(filtersPlus)
{
	$("#filter-plus-price-from").empty();
	$("#filter-plus-price-to").empty();
	$(".filters-plus-group .ui-slider").remove();
	
	$.each(filtersPlus.price.options,function(index,option){
		var fromOption = $("<option></option>").attr("value",option.value).html(option.name);
		var toOption = fromOption.clone();
						
		$("#filter-plus-price-from").append(fromOption);
		$("#filter-plus-price-to").append(toOption);
	});
	
	if(!filtersPlus.price.selected.active)
	{
		$("#filter-plus-price-from option:first").attr("selected","selected");
		$("#filter-plus-price-to option:last").attr("selected","selected");
	}
	else
	{
		$("#filter-plus-price-from option[value="+filtersPlus.price.selected.min+"]").attr('selected', 'selected');
		$("#filter-plus-price-to option[value="+filtersPlus.price.selected.max+"]").attr('selected', 'selected');
	}
	
	$("#filter-plus-price-from-value").html($("#filter-plus-price-from option:selected").text());
	$("#filter-plus-price-to-value").html($("#filter-plus-price-to option:selected").text());
	
	$('#filter-plus-price-from, #filter-plus-price-to').selectToUISlider({
		labels: 0,
		labelSrc: "text",
		tooltip: false,
		sliderOptions: {
			change: function(e, ui) {
				$("#filter-plus-price-from-value").html($("#filter-plus-price-from option:selected").text());
				$("#filter-plus-price-to-value").html($("#filter-plus-price-to option:selected").text());

				StartFilterAction();
			}
		}
	}).hide();
}
function SetHeader(header)
{			
	if(header != undefined)
	{	
		if( header.id != $("#brand-header-id").attr("value") )
		{
			// Dit is een andere
			if($("#brand-header").is(":visible"))
			{
				// Hij is zichtbaar
				$("#brand-header").fadeOut("normal",function(){
					$("#brand-header").children().remove();
					$("#brand-header").html(header.Html);
					$("body").css(header.Css);			
					$("#brand-header").fadeIn();
				});
			}
			else
			{
				// Hij is niet zichtbaar
				$("#brand-header").children().remove();
				$("#brand-header").html(header.Html);
				$("body").css(header.Css);
				$("#loadHeader").slideDown();
			}
		}
		else
		{
			// Dit is de zelfde
			if(!$("#brand-header").is(":visible"))
			{
				$("#brand-header").children().remove();
				$("#brand-header").html(header.Html);
				$("body").css(header.Css);
				$("#loadHeader").slideDown();
			}				
		}
	}
	else
	{
		$("#loadHeader").slideUp();
		$("body").removeAttr("style");
	}
}
function IsAllChildrenChecked(parent)
{
	return !parent.siblings("ul").find("a.unchecked").size() > 0;
}
function IsAllChilrenEnabled(parentItem)
{
	return !parentItem.find(".filter-child-item:not(.filter-child-item-disabled)").size() > 0;
}
function EnableChildItem(childItem, setEnabled)
{		
	//Parent klik functionaliteit
	childItemsParent = childItem.parents(".filter-parent-item:first");
	
	if(setEnabled)
	{
		//Parent klik functionaliteit
		if(childItemsParent.length > 0){
			childItemsParent.removeClass("filter-child-item-disabled");
		}
		
		childItem.removeClass("filter-child-item-disabled");	
	}
	else
	{
		if(childItem.parents(GetFirst()).size() == 0)
		{
			childItem.addClass("filter-child-item-disabled");
			
			//Parent klik functionaliteit
			if(childItemsParent.length > 0 && IsAllChilrenEnabled(childItemsParent))
			{
				childItemsParent.addClass("filter-child-item-disabled");
			}
		}
	}
}
function CheckParentLink(parentLink, setChecked)
{
	searchClass = setChecked ? "unchecked" : "checked";
	replaceClass = !setChecked ? "unchecked" : "checked";
	
	var children = parentLink.siblings("ul")
		.find(".filter-parent-link, .filter-child-link");
		
	if(parentLink.hasClass(searchClass))
	{	
		//Parent klik functionaliteit	
		parentLink.removeClass(searchClass).addClass(replaceClass);															  
	}
	
	children.each(function(){
		if($(this).hasClass(searchClass))
		{
			$(this).removeClass(searchClass).addClass(replaceClass);	
		}
	});			
}
function CheckChildLink(childLink, setChecked)
{
	searchClass = setChecked ? "unchecked" : "checked";
	replaceClass = !setChecked ? "unchecked" : "checked";
	
	var parent = childLink.parents(".filter-parent-item:first").children(".filter-parent-link");
	childLink.removeClass(searchClass).addClass(replaceClass);
	
	if(setChecked)
	{	
		if(IsAllChildrenChecked(parent))
		{
			parent.removeClass(searchClass).addClass(replaceClass);
		}
	}
	else
	{
		parent.removeClass(searchClass).addClass(replaceClass);
	}
}
function SetFirstByElement(element)
{
	CheckFirstValid();
	if(GetFirst() == "") {
		if(element.hasClass("filters-group")){
			SetFirst(element.attr("id"));
		} else {								
			SetFirst(element.parents(".filters-group:first").attr("id"));
		}
	}
}
function SetFirst(id)
{
	if($("#" + id).find('.checked').size() > 0)
	{
		$("#filter-first").attr("value","#" + id);
	}
}
function GetFirst()
{
	return $("#filter-first").attr("value");
}
function ClearFirst()
{
	return $("#filter-first").attr("value","");
}	
function CheckFirstValid()
{
	if(GetFirst() != "") {
		if($(GetFirst()).find('.checked').size() == 0){
			ClearFirst();
		}
	}
}
	
$(document).ready(function(){
	if($(".ajaxfilter").length > 0)
	{
		$("select[name=prodsPerPageSelect]").live("change",function(){
			if(ajaxCalling == false)
			{
				$("#pageSize").attr("value",$(this).find(":selected").attr("value"));
				$("#currentPage").attr("value",1);
				StartReloadAction();
			}
		});
		$(".product:has(a)").live("click",function(){
			document.location = $(this).find("a:first").attr("href");	
		});
		$(".filter-parent-item:not(.filter-child-item-disabled) .filter-parent-link, .filter-parent-link.checked").live("click",function(){
			if(ajaxCalling == false)
			{
				//Geblokte Functionaliteit (Parent Items Klik)
				CheckParentLink($(this),$(this).hasClass("unchecked"));
				SetFirstByElement($(this));
				StartFilterAction();
			}
		});
		$(".filter-child-item:not(.filter-child-item-disabled) .filter-child-link, .filter-child-link.checked").live("click",function(){												
			if(ajaxCalling == false)
			{
				CheckChildLink($(this), $(this).hasClass("unchecked"));
				SetFirstByElement($(this));				
				StartFilterAction();
			}
		});
		$("#filters-clear").live("click",function(){
			if(ajaxCalling == false)
			{
				ClearFilters();
				ClearFiltersPlus();
				StartFilterAction();
			}
		});
		$(".paging-item:not(.paging-item-active)").live('click',function(){
			if(ajaxCalling == false)
			{
				if($(this).hasClass("paging-item-next"))
				{
					next = $(".paging-item-active").removeClass("paging-item-active").next();
					next.addClass("paging-item-active");
					
					$("#currentPage").attr("value",parseInt($("#currentPage").attr("value"))+1);
				}	
				else if($(this).hasClass("paging-item-previous"))
				{
					previous = $(".paging-item-active").removeClass("paging-item-active").prev();
					previous.addClass("paging-item-active");
					
					$("#currentPage").attr("value",parseInt($("#currentPage").attr("value"))-1);
				}
				else
				{
					if($(this).hasClass("paging-item-first"))
					{
						$("#currentPage").attr("value",1);
					}
					else if($(this).hasClass("paging-item-last"))
					{
						$("#currentPage").attr("value",$("#nrOfPages").attr("value"));
					}
					else
					{
						$("#currentPage").attr("value",$(this).text());
					}
					
					$(this).addClass("paging-item-active").siblings().removeClass("paging-item-active");
				}
				
				StartReloadAction();
			}
		});
		
		$("#showrooms a[href*='products.asp#'], #brands a[href*='products.asp#']").live('click',function(){
			ReloadPageHash($.deparam.fragment($(this).attr("href")));
		});
			
		DefaultLoad();
	}
});