﻿// clears the input when clicking within it
function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
	thisfield.value = "";
	}
}

function colorMe(el){
	$(el).siblings().removeClass("current");
	if($(el).attr("id")=="twentyfive"){
		pageSize=25;
	}
	if($(el).attr("id")=="fifty"){
		pageSize=50;
	}
	if($(el).attr("id")=="hundred"){
		pageSize=100;
	}
	$(el).addClass("current");
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name, defaultVal) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return defaultVal;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
var retries=0;
var loadingIcon = "<div class=\"notice\"><img src=\"/images/loading.gif\" alt=\"loading...\"/></div>";


var firstLoadOnline = true;
var buildingIDS = false;
var showing =false;
var filterTimer;
var resultsTimer;
var categories_ids ="";
var solutions_ids ="";
var applications_ids ="";
var currPage=1;
var paginationFunc = function(){
	$("#resultSize").text(results);
	var pages=Math.round(results/pageSize)+((Math.round(results/pageSize)<(results/pageSize)) ? 1 : 0);
	currPage=Math.round(startIndex/pageSize)+1;
	if(currPage<1) currPage=1;
	var startPage=currPage-2;
	if(startPage<=0) startPage=1;
	var endPage=startPage+4;
	if(endPage>pages){
		startPage=pages-4;
		endPage=pages;
	}
	if(startPage<=0) startPage=1;
	if (pages<=1 || pageSize==0 || pageSize>results){
		$(".paginator").hide();
		if(results<=25) $(".perpageview").hide();
	}else{
		$(".perpageview").show();
	}
	$(".perpageview").show();
	
	if (pageSize!=0 && pageSize<results && pages>1){
		$(".paginator .pgPage").remove();
		$(".paginator").show();
		
		for(var i=Math.round(startPage);i<=Math.round(endPage);i++){
			$(".paginator .pgNext").before("<li class=\"pgPage\"><a href=\"#\">"+i+"</a></li>");
		}
		$(".paginator li a").each(function(el){
			if(currPage==this.firstChild.data) $(this).parent().addClass("pgCurrent");
		});
	}
	if(startIndex<1){
		$(".paginator .pgPrev, .paginator .pgPage:first-child").addClass("pgEmpty");
	}
	if(startIndex>=results-pageSize){
		$(".paginator .pgNext, .paginator .pgPage:last-child").addClass("pgEmpty");
	}
	$("#resultFrom").html((startIndex+1));
	$("#resultTo").html((startIndex+pageSize)< results ? (startIndex+pageSize*1) : results);
}
var productsFunc = function(data){
	$(".resultslist").html("");
	if(data.products){
		$.each(data.products, function(i, product){
			var relatedProducts ="";
			if(product.hasRelatedProducts){
				$.each(product.relatedProducts, function(i, relatedProduct){
					relatedProducts+="<div class=\"interestedlist\"><span class=\"name\">"+relatedProduct.productDisplayName+"</span>"+
					(relatedProduct.hasBuyInformations ? "<a class=\"infobutton silver-button buyinfo-button\" href=\"/" + LOCALE_COUNTRY +  "/" + relatedProduct.productURL + "/buyinformation.html\">" + data.workingcopy.buyinformation + "</a>" : (relatedProduct.hasContact ? "<a class=\"infobutton silver-button\" href=\""+"${locale.contactURL}"+"\">"+data.workingcopy.buycontact+"</a>" : "<span class=\"nolink\">&nbsp;</span>"))+
					(relatedProduct.hasOnline ? "<a class=\"infobutton red-button\" href=\"/"+ LOCALE_COUNTRY + "/"+relatedProduct.productURL+"/online.html\">"+data.workingcopy.buyonline+"</a>" : "<span class=\"nolink\">&nbsp;</span>")+
					(relatedProduct.hasOffline ? "<a class=\"infobutton greyblue-button\" href=\"/"+ LOCALE_COUNTRY + "/"+relatedProduct.productURL+"/offline.html\">"+data.workingcopy.buyoffline+"</a>" : "<span class=\"nolink\">&nbsp;</span>")+
					"<div class=\"clearb\">&nbsp;</div></div>"
				});
			}
			var evenCSS = "even";
			if((i % 2)!=0) evenCSS="odd";
					
			var html = "<div id=\"product_"+product.productid+"\" class=\""+evenCSS+"\">"+
			"<a class=\"name\">"+product.productDisplayName+"</a>"+				
			(product.hasBuyInformations ? "<a class=\"infobutton silver-button buyinfo-button\" href=\"/" + LOCALE_COUNTRY +  "/" + product.productURL + "/buyinformation.html\" onclick=\"dcsMultiTrack('WT.cg_n','WTB - Product Category events - " + product.productDisplayName + "','WT.cg_s','Buy Information - click','DCS.dcsuri',window.location.pathname+'BuyInformation','WT.ti','Product Category Buy Information click')\">" + data.workingcopy.buyinformation + "</a>" : 
				(product.hasContact ? "<a class=\"infobutton silver-button\" href=\""+encodeURI(product.localeContactUrl+"?productname="+product.productDisplayName+"&categoryname="+product.productCategoryName)+"\" onclick=\"dcsMultiTrack('WT.cg_n','WTB - Product Category events - " + product.productDisplayName + "','WT.cg_s','Contact 3M - click','DCS.dcsuri',window.location.pathname+'Contact3M','WT.ti','Product Category Contact 3M click')\">"+data.workingcopy.buycontact+"</a>" : "<span class=\"nolink\">&nbsp;</span>"))+
			(product.hasOnline ? "<a class=\"infobutton red-button\" href=\"/"+ LOCALE_COUNTRY + "/"+product.productURL+"/online.html\" " +
					"onclick=\"dcsMultiTrack('WT.cg_n','WTB - Product Category events - " + product.productDisplayName + "','WT.cg_s','Buy online - click','DCS.dcsuri',window.location.pathname+'ProductCategoryBuyOnline','WT.ti','Product Category Buy Online click')\">" + ((product.alternativeBuyOnline!="" && product.alternativeBuyOnline != null) ? product.alternativeBuyOnline :  data.workingcopy.buyonline) + "</a>" : "<span class=\"nolink\">&nbsp;</span>")+
			(product.hasOffline ? "<a class=\"infobutton greyblue-button\" href=\"/"+ LOCALE_COUNTRY + "/"+product.productURL+"/offline.html\" " +
					"onclick=\"dcsMultiTrack('WT.cg_n','WTB - Product Category events - " + product.productDisplayName + "','WT.cg_s','Buy offline - click','DCS.dcsuri',window.location.pathname+'ProductCategoryBuyOffline','WT.ti','Product Category Buy Offline click')\">" + ((product.alternativeBuyOffline!="" && product.alternativeBuyOffline != null) ? product.alternativeBuyOffline :  data.workingcopy.buyoffline) + "</a>" : "<span class=\"nolink\">&nbsp;</span>")+
			"<div class=\"clearb\">&nbsp;</div>"+
			"<div class=\"productdetails\"><p>"+product.productShortDesc+"</p>"+
			"<p class=\"deeplink\"><a target=\"_blank\" href=\""+product.productLink+"\">"+product.productLinkText+"</a></p>"+
			(relatedProducts!="" ? "<div id=\"interested\"><div class=\"interestedlist\"><span class=\"name\">"+ data.workingcopy.relatedProducts+ 
				"</span><div class=\"clearb\">&nbsp;</div></div>"+relatedProducts+"</div>" : "")+"</div></div>";
				
			$(".resultslist").append(html);
		});
	}
	if(data.resultSize){
		results=data.resultSize;
	}else{
		results=0;
	}
	refreshProducts();
	paginationFunc();
}
var onlineFunc = function(data){
	$(".resultslist").html("");
	if(data.distributors){
		$("#contact3MLinkId").attr('href', contact3MLink); // set 3m contact link for online view
		$.each(data.distributors, function(i, distributor){
			var evenCSS = "even";
			if((i % 2)!=0) evenCSS="odd";
			$(".resultslist").append("<div id=\"distributor_"+distributor.id+"\" class=\""+evenCSS+"\">"+
					"<a href=\"" + distributor.buyNowUrl + "\" class=\"onlinename\" target=\"_blank\"" +
					"onclick=\"dcsMultiTrack('WT.cg_n',WTwtbprod,'WT.cg_s','"+data.workingcopy.buy+" "+ data.workingcopy.online + " - "+ distributor.name +" - click','DCS.dcsuri',window.location.pathname+'BuyOnlineClick','WT.ti','Buy Online click','WT.si_cs','1','WT.si_n','wtbv2','WT.si_x','4')\">"+distributor.name+"</span></a>"+
					((distributor.buyNowUrl!=null && distributor.buyNowUrl!="") ? "<a class=\"infobutton silver-button buyinfo-button\" href=\""+distributor.buyNowUrl+"\" target=\"_blank\"" +
					"onclick=\"dcsMultiTrack('WT.cg_n',WTwtbprod,'WT.cg_s','"+data.workingcopy.buynow+" Button - " + distributor.name +" - click','DCS.dcsuri',window.location.pathname+'BuyNowButtonClick','WT.ti','"+distributor.name+" Button click','WT.si_cs','1','WT.si_n','wtbv2','WT.si_x','4')\"><span class=\"goto\">"+data.workingcopy.buynow+"</span><span class=\"url\">#</span></a>" : "") +
					"<div class=\"clearb\">&nbsp;</div></div>");
		});
	}
	if(data.resultSize){
		results=data.resultSize;
	}else{
		results=0;
	}
	$(".resultslist .productdetails").hide();
	paginationFunc();
}
var offlineFunc = function(data){
	$(".resultslist").html("");
	if ($("#promptUserDistributorFilter").val() != "true") {
		$("#filterprompt").hide();
		if(data.distributors){
			$("#contact3MLinkId").attr('href', contact3MLink); // set 3m contact link for online view
		$.each(data.distributors, function(i, distributor){
			var evenCSS = "even";
			if((i % 2)!=0) evenCSS="odd";
			var offices= "";
			$.each(distributor.offices, function(j, office){
				offices+="<div class=\"address\">"+
						"<p class=\"offaddress\">"+office.address1+"<br />\n"+
						(office.address2 != '' ? office.address2 + "<br />\n" : '' ) +
						(office.city != '' ? office.city + "<br />\n" : '' ) +
						(office.state != '' ? office.state + "<br />\n" : '' ) +
						(office.postCode != '' ? office.postCode + "<br />\n" : '' ) + "</p>\n"+
						"<div class=\"buttononblue\"><a href=\"#\" id=\"" + office.id + "\" class=\"map\"" +
						"onclick=\"dcsMultiTrack('WT.cg_n',WTwtbprod,'WT.cg_s','"+data.workingcopy.buy+" "+ data.workingcopy.offline + " - "+ distributor.name +" - View Map click','DCS.dcsuri',window.location.pathname+'BuyOfflineDetailViewMap','WT.ti','Buy Offline Distributors detail- View Map')\">"+data.workingcopy.viewmap+"</a></div>"+
						(distributor.hasHomePage ? "<div class=\"buttononblue\"><a href=\""+distributor.homePageUrl+"\" target=\"_blank\"" +
						"onclick=\"dcsMultiTrack('WT.cg_n',WTwtbprod,'WT.cg_s','"+data.workingcopy.buy+" "+ data.workingcopy.offline + " - "+ distributor.name +" - Visit Website click','DCS.dcsuri',window.location.pathname+'BuyOfflineDetailVisitWebsite','WT.ti','Buy Offline Distributors detail- Visit Website')\"><span class=\"goto\">"+data.workingcopy.visitwebsite+"</span><span class=\"url\">"+distributor.homePageUrl+"</span></a></div>" : "")  +
						"</div>"+
				"<div class=\"contacts\">"+
					(office.hasContactName ? "<p>"+data.workingcopy.name+": "+office.contactName+"<br/>" : "")+
					(office.hasContactPhone1 ? data.workingcopy.telephone+": "+office.contactPhone1+"<br/>"+
					(office.hasContactPhone2 ? office.contactPhone2 +"<br />" : "")   		: "")+
					(office.hasContactFax ? data.workingcopy.fax+": "+office.contactFax +"<br />" : "")+
					(office.hasEmail ? data.workingcopy.email+": <span id=\"office_"+office.id+"_email\">"+"<a href=\"mailto:"+office.contactEmailPerson+"@"+office.contactEmailHost+"?Subject=3M%20Where%20To%20Buy\">"+office.contactEmailPerson+"@"+office.contactEmailHost+"</a></span><br />" : "")+
					"</p></div>"
					// handles multiple regions for each office
					if(office.regions) {
						offices+="<div class=\"region\">";
						offices+="<p>";
						$.each(office.regions, function(k, regions) {
								var regionName= "<span>" + regions + "</span>" + "<br />";
								offices+=regionName;
						});
						offices+="</p>";
						offices+="</div>";
					}
					if(typeof(office.regions)=="undefined"){
						offices+="<div class=\"region\">";
						offices+="<span>"+"</span>";
						offices+="</div>";
					}
					
					((j<(distributor.offices.length-1)) ? offices+="<div class=\"rule\">&nbsp;</div>" : offices+="<div class=\"clearl\">&nbsp;</div>")
			});
			$(".resultslist").append("<div id=\"distributor_"+distributor.id+"\" class=\""+evenCSS+"\">"+
					"<a class=\"name\" \"onclick=\"dcsMultiTrack('WT.cg_n',WTwtbprod,'WT.cg_s','"+data.workingcopy.buy+" "+ data.workingcopy.offline + " - "+ distributor.name +" - show details','DCS.dcsuri',window.location.pathname+'ShowOfflineDetails','WT.ti','Show Offline Distributors detail','WT.si_cs','1','WT.si_n','wtbv2off','WT.si_x','4')\">"+distributor.name+"</a>"+
							"<div class=\"clearb\">&nbsp;</div>"+
							(offices=="" ? "" : "<div class=\"productdetails pad10 distoffice\">"+offices+"</div>")+
					"</div>");
			});
		}
	} else {
		$("#filterprompt").show();
		$("#promptUserDistributorFilter").val("false");
	}

	if(data.resultSize){
		results=data.resultSize;
	}else{
		results=0;
	}
	$(".resultslist .productdetails").hide();
	paginationFunc();
}
var filtersFunc = function(data){
	if(data.type!=="solution") $("#solution .filterlist").html("");
	if(data.type!=="application") $("#application .filterlist").html("");
	if (data.solutions != '') {
		//alert("got data.solution");
		$("#solution").show();
		if(data.solutions && data.type!=="solution"){
			$.each(data.solutions, function(i, solution){
				$("#solution .filterlist").append("<a"+(solution.selected ? " class=\"filteron\"":"")+" id=\"s_"+solution.id+"\" href=\"#\"><span class=\"lozenge\">"+solution.name+"</span></a>");
			});
		}
	} else {
		$("#solution").hide();
	}
	
	if (data.applications != '') {
		//alert("data.applications=" + data.applications);
		$("#application").show();
		if(data.applications && data.type!=="application"){
			$.each(data.applications, function(i, application){
				$("#application .filterlist").append("<a"+(application.selected ? " class=\"filteron\"":"")+" id=\"a_"+application.id+"\" href=\"#\"><span class=\"lozenge\">"+application.name+"</span></a>");
			});
		}
	} else {
		$("#application").hide();
	}
	
	startIndex=0;
	updateIDS();
	clearTimeout(resultsTimer);
	$(".resultslist").html(loadingIcon);
	resultsTimer=setTimeout("getResults();",1800);
}

var regionsFunc = function(data){
	$("#location").html("<option value=\"\">"+data.workingcopy.all+"</option>");
	if(data.regions){
		$.each(data.regions, function(i, region){
			$("#location").append("<option"+(region.selected ? " selected=\"selected\"": "" )+" value=\""+region.id+"\">"+region.name+"</option>");
		});
	}
}

var dealerTypesFunc = function(data){
	$("#dealertype").html("<option value=\"\">"+data.workingcopy.all+"</option>");
	if(data.dealerTypes){
		$.each(data.dealerTypes, function(i, dealerType){
			$("#dealertype").append("<option"+(dealerType.selected ? " selected=\"selected\"": "" )+" value=\""+dealerType.id+"\">"+dealerType.name+"</option>");
		});
	}
}
function hideSolutionsApplications(){
	if($("#resultskeyword").length==0){
		showSolutionsApplications();
	}
	showing=false;
}
function showSolutionsApplications(){
	var remove = $("div.filterhead div.expandfilters a").hasClass("expanded");
	if(remove){
		if (applications_ids != null && applications_ids.length > 0) {
			//alert("show APP. " + applications_ids);
			$("#application").show();
			showing=true;
		} else {
			$("#application").hide();
		}
		
		if (solutions_ids != null && solutions_ids.length > 0) {
			$("#solution").show();
			showing=true;
		} else {
			$("#solution").hide();
		}	
	}
	
}

function refreshProducts(){
	$(".resultslist .productdetails").hide();
	if($.trim($("#resultskeyword").text()).toLowerCase()==$.trim($(".resultslist").find("a.name:first").text().toLowerCase())){
		$(".resultslist a.name:first").click();
	}
	
	var validCategories = $('#category #filterset_1 .filteritem input').map(function(){return $(this).attr("id")+"_";}).get();
	var validSolutions = $('#category #filterset_2 .filteritem input').map(function(){return $(this).attr("id")+"_";}).get();
	var validApplications = $('#category #filterset_3 .filteritem input').map(function(){return $(this).attr("id")+"_";}).get();

	$.each(new String(window.location).split("#"), function(i, ref){
		
		$.each(new String(window.location).split("#"), function(i, ref){
			if(i==0 || ref=="") return;
			if (ref.indexOf("c_")!=-1 && $.inArray(ref,validCategories)==-1) remove(ref);
			if (ref.indexOf("s_")!=-1 && $.inArray(ref,validSolutions)==-1) remove(ref);
			if (ref.indexOf("a_")!=-1 && $.inArray(ref,validApplications)==-1) remove(ref);
		});
		
		//FIND
	});
}

function updateIDS(){
	if(buildingIDS) return;
}

function remove(ref){
	var newLocation = new String(window.location).replaceAll("#"+ref,"");
	if(newLocation.indexOf("#")==-1) newLocation = newLocation + "#";
	window.location = newLocation;
}
// encode URI is needed for JSON ajax call, otherwise wrong parameters are passed to the server
function getResults(){
	if(new String(window.location).indexOf("buyinformation.html")!=-1){
		$("#contact3MLinkId").attr('href', encodeURI(contact3MLink)); // set 3m contact link for online view
	}
	if(pageSize!=undefined && pageSize!=0) {
		if(startIndex!=undefined && startIndex>0) {
			
		}
		$(".resultslist").html(loadingIcon);
		if(new String(window.location).indexOf("offline.html")==-1 && new String(window.location).indexOf("online.html")==-1){
			var productsUrl="/"+ LOCALE_COUNTRY + 
							"/products.json?searchTerms="+$("#resultskeyword").text()+
							"&pageSize="+pageSize+"&startIndex="+startIndex+
							"&categories="+categories_ids.substring(0, categories_ids.length-1)+
							"&solutions="+solutions_ids+
							"&applications="+applications_ids+
							"&sortBy="+$("#sortby").val();
			$.getJSON(encodeURI(productsUrl), productsFunc);
		}else{
			if(new String(window.location).indexOf("offline.html")!=-1){
				var sortBy = $("#sortby").val()
				if(!sortBy) {
					sortBy="";
				}			
				var offlineProductsUrl="offline.json?categories="+categories_ids.substring(0, categories_ids.length-1)+
										"&solutions="+solutions_ids+
										"&applications="+applications_ids+
										"&pageSize="+pageSize+
										"&startIndex="+startIndex+
										"&sortBy="+sortBy+
										"&location="+$("#location").val()+
										"&dealerType="+$("#dealertype").val();
				$.getJSON(encodeURI(offlineProductsUrl), offlineFunc);
			}else{
				var sortBy = $("#sortby").val()
				if(!sortBy) {
					sortBy="";
				}						
				var onlineProductsUrl="online.json?categories="+categories_ids.substring(0, categories_ids.length-1)+
									  "&solutions="+solutions_ids+
									  "&applications="+applications_ids+
									  "&pageSize="+pageSize+
									  "&startIndex="+startIndex+
									  "&sortBy="+sortBy+
									  "&dealerType="+$("#dealertype").val();
				$.getJSON(encodeURI(onlineProductsUrl), onlineFunc);
			}
		}
	}
}

//encode URI is needed for JSON ajax call, otherwise wrong parameters are passed to the server
function getResultsCategoriesChanged(){
	if(pageSize!=undefined && pageSize!=0) {
		startIndex=0;
		$(".resultslist").html(loadingIcon);
		if(new String(window.location).indexOf("offline.html")==-1 && new String(window.location).indexOf("online.html")==-1){
			var productsUrl="/"+ LOCALE_COUNTRY + 
							"/products.json?searchTerms="+$("#resultskeyword").text()+
							"&pageSize="+pageSize+"&startIndex="+startIndex+
							"&categories="+categories_ids.substring(0, categories_ids.length-1)+
							"&solutions="+solutions_ids+
							"&applications="+applications_ids+
							"&sortBy="+$("#sortby").val();
			$.getJSON(encodeURI(productsUrl), productsFunc);
		}else{
			if(new String(window.location).indexOf("offline.html")!=-1){
				var offlineProductsUrl="offline.json?categories="+categories_ids.substring(0, categories_ids.length-1)+
										"&solutions="+solutions_ids+
										"&applications="+applications_ids+
										"&pageSize="+pageSize+
										"&startIndex="+startIndex+
										"&sortBy="+$("#sortby").val()+
										"&location="+$("#location").val()+
										"&dealerType="+$("#dealertype").val();
				$.getJSON(encodeURI(offlineProductsUrl), offlineFunc);
			}else{
				var onlineProductsUrl="online.json?categories="+categories_ids.substring(0, categories_ids.length-1)+
									  "&solutions="+solutions_ids+
									  "&applications="+applications_ids+
									  "&pageSize="+pageSize+
									  "&startIndex="+startIndex+
									  "&sortBy="+$("#sortby").val()+
									  "&dealerType="+$("#dealertype").val();
				$.getJSON(encodeURI(onlineProductsUrl), onlineFunc);
			}
		}
	}
}

function filterChanged(type){
	//if(type!=="category"){$("#category .filterlist").html(loadingIcon);
	if(!showing && type==="category") showSolutionsApplications();
	if(type!=="solution") $("#solution .filterlist").html(loadingIcon);
	if(type!=="application") $("#application .filterlist").html(loadingIcon);
	var urlToEncode="/"+ LOCALE_COUNTRY + 
					"/categories.json?type="+type+
					"&searchTerms="+$("#resultskeyword").text()+
					"&categories="+categories_ids.substring(0, categories_ids.length-1)+
					"&solutions="+solutions_ids.substring(0, solutions_ids.length-1)+
					"&applications="+applications_ids.substring(0, applications_ids.length-1);
	$.getJSON(encodeURI(urlToEncode), filtersFunc);

	//alert("solutions=" + solutions_ids.length)
	//alert("applications=" + applications_ids.length)
	
}

function regionChanged(){
	var urlToEncode="locations.json?location="+$("#location").val()+"&dealerType="+$("#dealertype").val();
	if(new String(window.location).indexOf("offline.html")!=-1)	$.getJSON(encodeURI(urlToEncode), dealerTypesFunc);
}

function dealerTypeChanged(){
	var urlToEncode="distributortypes.json?location="+$("#location").val()+"&dealerType="+$("#dealertype").val();
	if(new String(window.location).indexOf("offline.html")!=-1) $.getJSON(encodeURI(urlToEncode), regionsFunc);
}

// add replaceAll to JS Strings
String.prototype.replaceAll = function(pcFrom, pcTo){
	var i = this.indexOf(pcFrom);
	var c = this;
	
	while (i > -1){
		c = c.replace(pcFrom, pcTo); 
		i = c.indexOf(pcFrom);
	}
	return c;
}

var mapwindow;

//  -- BEGIN JQUERY CODE
$(document).ready(function(){
	
$("div.filteritem input").live("click",function(e){
	if($(this).is(":checked")){
		if(new String(window.location).indexOf("#"+$(this).attr("id")+"_")==-1){
			window.location = new String(window.location+"#"+$(this).attr("id")+"_").replaceAll("##","#");
		}
	}else{
		var newLocation = new String(window.location).replaceAll("#"+$(this).attr("id")+"_","");
		if(newLocation.indexOf("#")==-1){
			newLocation = newLocation + "#";
		}
		window.location = newLocation;
	}
	//clearTimeout(resultsTimer);
	//updateIDS();
	if($(this).parent().parent().attr("id")=="category") filterChanged("category");
	if($(this).parent().parent().attr("id")=="solution") filterChanged("solution");
	if($(this).parent().parent().attr("id")=="application") filterChanged("application");
	//e.preventDefault();
});

// click filter box label 
$("div.filteritem div").live("click",function(e){
	if($(this).parent().find("input").is(":checked")) {
		$(this).parent().find("input").removeAttr('checked');
	} else {
		$(this).parent().find("input").attr('checked', 'true');
	}
	
	var id = $(this).parent().find("input").attr("id");
	if($(this).parent().find("input").is(":checked")){
		if(new String(window.location).indexOf("#"+id+"_")==-1){
			window.location = new String(window.location+"#"+id+"_").replaceAll("##","#");
		}
	}else{
		var newLocation = new String(window.location).replaceAll("#"+id+"_","");
		if(newLocation.indexOf("#")==-1){
			newLocation = newLocation + "#";
		}
		window.location = newLocation;
	}
	//categories_ids += $(this).parent().find("input").attr("id").replaceAll("c_", "") + ",";
	// uncheck all checkboxes
	/*$("div.filteritem input").each(function(i){
		$(this).removeAttr('checked');
		// remove from window location
		
		if(new String(window.location).indexOf("#"+$(this).attr("id")+"_")!==-1){
			var newLocation = new String(window.location).replaceAll("#"+$(this).attr("id")+"_","");
			if(newLocation.indexOf("#")==-1){
				newLocation = newLocation + "#";
			}
			window.location = newLocation;
		}
	});
	
	if(new String(window.location).indexOf("#"+$(this).parent().find("input").attr("id")+"_")==-1){
		window.location = new String(window.location+"#"+$(this).parent().find("input").attr("id")+"_").replaceAll("##","#");
	}*/
	if($(this).parent().parent().parent().parent().attr("id")=="category") {
		//filterChanged("category");
	}
	categories_ids="";
	$("div.filteritem input").each(function(i){
		if($(this).parent().find("input").is(":checked")){
			categories_ids=categories_ids+$(this).parent().find("input").attr("id")	.replaceAll("c_","")+",";		
		}
	});
	getResultsCategoriesChanged();
});

$("div.filterselector a.selectall").click(function(e){
	// toggle on.
	$(this).parent().parent().parent().find("div.filteritem input").attr('checked', true);
	
	$(this).parent().parent().parent().find("div.filteritem input").each(function(i) {
		var id = $(this).attr("id");
		if($(this).is(":checked")){
			if(new String(window.location).indexOf("#"+id+"_")==-1){
				window.location = new String(window.location+"#"+id+"_").replaceAll("##","#");
			}
		}else{
			var newLocation = new String(window.location).replaceAll("#"+id+"_","");
			if(newLocation.indexOf("#")==-1){
				newLocation = newLocation + "#";
			}
			window.location = newLocation;
		}
	});
	//$(this).parent().parent().parent().find("div.filteritem input").click();
	e.preventDefault();
});

$("div.filterselector a.selectnone").click(function(e){
	// toggle off.
	$(this).parent().parent().parent().find("div.filteritem input").attr('checked', false);
	
	$(this).parent().parent().parent().find("div.filteritem input").each(function(i) {
		var id = $(this).attr("id");
		if($(this).is(":checked")){
			if(new String(window.location).indexOf("#"+id+"_")==-1){
				window.location = new String(window.location+"#"+id+"_").replaceAll("##","#");
			}
		}else{
			var newLocation = new String(window.location).replaceAll("#"+id+"_","");
			if(newLocation.indexOf("#")==-1){
				newLocation = newLocation + "#";
			}
			window.location = newLocation;
		}
	});
	
	e.preventDefault();
});

$("#wtb #filterSearch div.wtbbutton input").click(function(e){
	categories_ids="";
	solutions_ids="";
	applications_ids="";
	$("#category #filterset_1 .filteritem input:checked").each(function(i){
		categories_ids=categories_ids+$(this).attr("id").replaceAll("c_","")+",";		
	});
	$("#category #filterset_2 .filteritem input:checked").each(function(i){
		solutions_ids=solutions_ids+$(this).attr("id").replaceAll("s_","")+",";
	});
	$("#category #filterset_3 .filteritem input:checked").each(function(i){
		applications_ids=applications_ids+$(this).attr("id").replaceAll("a_","")+",";
	});
	getResultsCategoriesChanged();
});

$(".resultslist a.name,.resultslist a.nameon").live("click",function(e){
	if ($(this).is(".name")) {
		$(this).removeClass("name").addClass("nameon");
		$(this).siblings(".productdetails").slideDown("150");
	}else{
		$(this).removeClass("nameon").addClass("name");
		$(this).siblings(".productdetails").slideUp("150");
	}
	e.preventDefault();
});

$(".resultslist a.namelink,.resultslist a.nameonlink").live("click",function(e){
	if ($(this).is(".namelink")) {
		$(this).removeClass("namelink").addClass("nameonlink");
		$(this).text(workingcopyhidedetails); 
		$(this).siblings(".productdetails").slideDown("150");
	}else{
		$(this).removeClass("nameonlink").addClass("namelink");
		$(this).text(workingcopyviewdetails);
		$(this).siblings(".productdetails").slideUp("150");
	}
	e.preventDefault();
});

$("div.filterhead div.expandfilters a").click(function(e){
	clearTimeout(filterTimer);
	var remove = $(this).hasClass("expanded");
	$("div#filters div.filterboxes div.filterlist").hide();
	if(remove){
		$(this).removeClass("expanded");
	}else{
		$(this).addClass("expanded");
		$("div#filters div.filterboxes").show();
	}
	
	if(showing){
		$("div#filters div.filter").slideToggle("350");
	}else{		
		$("div#filters #category").slideToggle("350");		
	}
	
	filterTimer=setTimeout("$(\"div#filters div.filterboxes div.filterlist\").show();", 350);
	
	/*if(remove){
		filterTimer=setTimeout("$(\"div#filters div.filterboxes div.filterlist\").show(); $(\"div#filters div.filterboxes\").hide();", 350);
	}else{
		filterTimer=setTimeout("$(\"div#filters div.filterboxes div.filterlist\").show();", 350);
	}*/
	e.preventDefault();
});

$("a.help").click(function(e){
	var anchor = new String(window.location.href);
	if(anchor.indexOf("/search/")==-1 && anchor.indexOf("/products")==-1){
		anchor = anchor.substring(anchor.lastIndexOf("/")+1, anchor.lastIndexOf("."))
	}else{
		anchor = "filtering";
	}
	if(anchor=="index" || !results) anchor = "searching";
	window.location.href="/"+LOCALE_COUNTRY+"/help.html#"+anchor;
	e.preventDefault();
});

$("#sortby").change(function(e){
	updateIDS();
	startIndex=0;
	getResults();
	e.preventDefault();
});
$("#location").change(function(e){
	updateIDS();
	startIndex=0;
	getResults();
	regionChanged();
	e.preventDefault();
});
$("#dealertype").change(function(e){
	updateIDS();
	startIndex=0;
	getResults();
	dealerTypeChanged();
	e.preventDefault();
});

$("a.print").click(function(e){
	window.print();
	e.preventDefault();
});

$(".map").live("click",function (e) {
	if(mapwindow) mapwindow.close();
	mapwindow = window.open(ROOT+"/"+LOCALE_COUNTRY+"/map.html?id="+$(this).attr("id").replaceAll("office_",""), "mapwindow", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbar=0,resizable=0,width=700,height=470", false);
	e.preventDefault();
});

// prevents searching for the default text in the search box.
$("form#wtbsearch,form#keywordSearchForm").submit(function(e){
	if($(this).find("#q").val().indexOf(defaultKeywordsText)>=0){
		$(this).find("#q").val($(this).find("#q").val().replaceAll(defaultKeywordsText,""));
	}
	return true;
});

$('.filterheading h3 a, .filterheading a.arrowopen').click(function() {
	filterset = $('#' + $(this).parent().parent().attr('rel'));
	
	filterset.slideToggle('350');
	
	if($(this).parent().parent().hasClass('filteropen')) {
		//Turn arrow to side
		$(this).parent().parent().removeClass('filteropen').addClass('filterclose');
		hideSearchBtn();
	} else {
		//turn arrow down
		$(this).parent().parent().removeClass('filterclose').addClass('filteropen');
		showSearchBtn();
	}
	return false;
});

function hideSearchBtn(){
	 if($('#sections div').hasClass('filterclose') && $('#solutions div').hasClass('filterclose') && $('#appliactions div').hasClass('filterclose'))
	 {
		 $("div.button_container").hide();
	 }
	 
}

function showSearchBtn(){
	 $("div.button_container").show();
}

$("div#filters div.filterboxes").hide();
$("div#filters div.filter").hide();
refreshProducts();

buildingIDS=true;
categories_ids ="";
solutions_ids ="";
applications_ids ="";

$("#category #filterset_1 .filteritem input").each(function(i){
	if(new String(window.location).indexOf("#"+$(this).attr("id")+"_")!=-1)	 {
		categories_ids=categories_ids+$(this).attr("id").replaceAll("c_","")+",";
		this.checked = true;
	}
});
$("#category #filterset_2 .filteritem input").each(function(i){
	if(new String(window.location).indexOf("#"+$(this).attr("id")+"_")!=-1) {
		solutions_ids=solutions_ids+$(this).attr("id").replaceAll("s_","")+",";
		this.checked = true;
	}
});
$("#category #filterset_3 .filteritem input").each(function(i){
	if(new String(window.location).indexOf("#"+$(this).attr("id")+"_")!=-1) {
		applications_ids=applications_ids+$(this).attr("id").replaceAll("a_","")+",";
		this.checked = true;
	}
});

buildingIDS=false;

$(".paginator a").live("click",function(e){
	if(!$(this).parent().hasClass("pgCurrent") && !$(this).parent().hasClass("pgEmpty")){
		if($(this).parent().hasClass("pgPage")){
			var newPageNum = this.firstChild.data;
			startIndex=(newPageNum-1)*pageSize;
			$(".paginator li").removeClass("pgCurrent");
			$(".paginator li a").each(function(el){
				if(newPageNum==this.firstChild.data) $(this).parent().addClass("pgCurrent");
			});
		}else{
			$(".paginator li").removeClass("pgCurrent");
			if($(this).parent().hasClass("pgPrev")){
				startIndex-=pageSize;
				if(startIndex<0) startIndex=1;
			}else{
				startIndex+=pageSize;
			}
			var newPageNum = (startIndex/pageSize)+1;
			$(".paginator li a").each(function(el){
				if(newPageNum==this.firstChild.data) $(this).parent().addClass("pgCurrent");
			});
		}
		if(startIndex>0||startIndex+pageSize<results){
			$(".paginator li").removeClass("pgEmpty");
		}
		if(startIndex<1){
			$(".paginator .pgPrev, .paginator .pgPage:first-child").addClass("pgEmpty");
		}
		if(startIndex>=results-pageSize){
			$(".paginator .pgNext, .paginator .pgPage:last-child").addClass("pgEmpty");
		}
		getResults();
	}
	e.preventDefault();
});

$("#perpageview").change(function() {
	pageSize = $("#perpageview").val();
	if(pageSize<currPageSize){
		var itemsToRemove = $(".resultslist").children("div").length-pageSize;
		for(i=0;i<itemsToRemove;i++){
			$(".resultslist > div:last-child").remove();
		}
		paginationFunc();
	}else{
		getResults();
	}
	currPageSize=pageSize;
	//createCookie("3mwtb_pageSize",pageSize,0);
});

/*$(".perpageview span").click(function(e){
	colorMe(this);
	if(pageSize<currPageSize){
		var itemsToRemove = $(".resultslist").children("div").length-pageSize;
		for(i=0;i<itemsToRemove;i++){
			$(".resultslist > div:last-child").remove();
		}
		paginationFunc();
	}else{
		getResults();
	}
	currPageSize=pageSize;
	createCookie("3mwtb_pageSize",pageSize,0);
	e.preventDefault();
});*/
if(window.results===undefined) results=0;
if(window.currPageSize!==undefined){
	pageSize=25;
	$("#twentyfive").click();
	/*pageSize=readCookie("3mwtb_pageSize",currPageSize);
	  if(pageSize==currPageSize){
		switch(pageSize){
		case "25":
			colorMe($("#twentyfive"));
			break;
		case "50":
			colorMe($("#fifty"));
			break;
		case "100":
			colorMe($("#hundred"));
			break;
		}
	}else{
		switch(pageSize){
			case "25":
				$("#twentyfive").click();
				break;
			case "50":
				$("#fifty").click();
				break;
			case "100":
				$("#hundred").click();
				break;
		}
	}*/	
	paginationFunc();
}
getResults();
$("div#filters").show();
$("div.resultshead").show();

$("div#wtbtabs ul.ui-tabs-nav li.ui-tabs-selected").removeClass('ui-state-default');

});
//-- END JQUERY CODE
