// keep navigate method out of the jQuery document.Ready method
//  - avoids issues in FireFox
var currentPage = queryString('pge');
var pageSize = queryString('pgeSize');
var pageSort = queryString('sort');
var cid = parseInt(queryString('cid'));
var totalItems;
var state;
var parentID;
var arrRefineState;
var strQuery;
var countryId;
var hasNavigateFired = false;
var searchPageFirstLoad = true;
var isSearchPage = false;
var btmPagingClicked = false;
var historypointalreadycreated = false;
var stopCurrentRefinementLoading = false;

Sys.Application.add_navigate(function(sender, e) {
    if (getServiceAddress()) {

        hasNavigateFired = true;
        navigate(sender, e);

    }
});
$(document).ready(function() {
    initialOverlay();
    // set default values if undefined
    if (currentPage == undefined) {
        currentPage = getDefaultValue("pge");
    }
    if (pageSize == undefined) {
        pageSize = getDefaultValue("pgesize");
    }
    if (pageSort == undefined) {
        pageSort = getDefaultValue("sort");
    }

    $("select.filterSort").change(function() {
        sortOptionChanged($(this));
        return false;
    });

    $("ol.page-nos a").click(function() {
		pageNumbers(this)
        return false;
    });

	countryId = $("#countryId").val();
	totalItems = $("#resultsCount").html();

	if (pageSort == undefined) {
		pageSort = getParam($("select.filterSort option:selected").val(), "sort");
	}
	$("a.view-all").click(function() {
	    prepareForHistoryPoint($(this), -1);
	    if ($(this).parent().hasClass("bottom")) {
	        btmPagingClicked = true;
	    }
		return false;
	});
	$("a.view-paged").click(function() {
	    prepareForHistoryPoint($(this), -1);
	    if ($(this).parent().hasClass("bottom")) {
	        btmPagingClicked = true;
	    }
		return false;
	});
	$("a.view-max-paged").click(function() {
	    prepareForHistoryPoint($(this), -1);
		return false;
	});
	$("#controls > .control > ul > li > a").click(function() {
		if ($(this).hasClass("disabled")) {
			//nothing
		} else {
			if ($(this).hasClass("enabled") || $(this).hasClass("selected")) {
				disableControls();
				var parentID = $(this).parent("li").parent("ul").attr("id");
				currentPage = 0;
				prepareForHistoryPoint($(this), parentID);
			}
		}
		return false;
	});
	$("#controls .control  a.clear").click(function() {
		disableControls();
		currentPage = 0
		//parentID = null;
		prepareForHistoryPoint($(this), parentID);
		return false;
	});
	$("#controls a.clear-all").click(function() {
		disableControls();
		currentPage = 0;
		//parentID = null;
		prepareForHistoryPoint($(this), parentID);
		return false;
	});
	$("a.toggleControl").click(function() {
		$(this).toggleClass("closed");
		$(this).parent().parent().siblings(".attribute-items").toggle();
		$(this).blur();
		//should this create a history point?
		return false;
	});
	$("a.back-to-top").each(function() {
		var targetOffset = $("#top").offset().top;
		$(this).click(function(event) {
			event.preventDefault();
		    var scrollElement = 'html, body';
			$('html, body').each(function () {
				var initScrollTop = $(this).attr('scrollTop');
				$(this).attr('scrollTop', initScrollTop + 1);
				if ($(this).attr('scrollTop') == initScrollTop + 1) {
					scrollElement = this.nodeName.toLowerCase();
					$(this).attr('scrollTop', initScrollTop);
					return false;
				}    
			});
			$(scrollElement).animate({ scrollTop: targetOffset }, 0, function() {
				//location.hash = target;
			});
			return false;
		});
	});
	initializeSlider();
	$("a.selected").livequery(
		function() {
		    $(this).removeAttr("disabled");
		}
	);
    $("a.selected.enabled").livequery( //The is for IE6 and below, and bypasses some problems IE6 has with mulitple css classes
		function() {
		    $(this).addClass("selected-enabled");
		},
		function() {
		    $(this).removeClass("selected-enabled");
		}
	);
	var lastState = $("#hdnLastState").val();
	if(lastState != "" && !historypointalreadycreated) {
		createHistoryPoint($("#hdnLastState").val());
	}
    hideOverlay();
});

function scrollToTop() {
    var targetOffset = $("#top").offset().top;
    var scrollElement = 'html, body';
    $('html, body').each(function() {
        var initScrollTop = $(this).attr('scrollTop');
        $(this).attr('scrollTop', initScrollTop + 1);
        if ($(this).attr('scrollTop') == initScrollTop + 1) {
            scrollElement = this.nodeName.toLowerCase();
            $(this).attr('scrollTop', initScrollTop);
            return false;
        }
    });
    $(scrollElement).animate({ scrollTop: targetOffset }, 0, function() {
        //location.hash = target;
    });
    return false;
}

function sortOptionChanged(selectedOption) {
	pageSort = getParam(selectedOption.val(), "sort");
	currentPage = 0;
	createHistoryPoint(selectedOption.val(), -1);
}
function prepareForHistoryPoint(clickedElement, parentID) {
	createHistoryPoint(clickedElement.attr("href"), parentID);
	clickedElement.blur();
}
function createHistoryPoint(href, parentID) {
	var obj = getRefineStateAsHistoryObject(href, parentID);
	showOverlayAndCreateHistoryPoint(obj);
}

function navigate(sender, e){
	stopCurrentRefinementLoading = true;
	if(JSON.stringify(e.get_state()) == "{}") {
		//This is for when you do a hard refresh of the category page in IE - the navigate event fires even if there are no refinements.
	} else {
		historypointalreadycreated = true;
		parentID = e.get_state().parentID;
		state = e.get_state().state;
		cid = parseInt(queryString('cid'));
		if (e.get_state().pge != null) {
			currentPage = e.get_state().pge;
		} else {
			currentPage = getDefaultValue("pge");
		}
		if (e.get_state().pgeSize != null) {
			pageSize = e.get_state().pgeSize;
		} else {
			pageSize = getDefaultValue("pgesize");
		}
		if (e.get_state().sort != null) {
			pageSort = e.get_state().sort;
		} else {
			pageSort = getDefaultValue("sort");
		}

		strQuery = $("#hfQuery").val();
		maxResultCount = $("#maxResultCount").val();

		if (cid == null || (strQuery != '' && strQuery != null)) {
			cid = -1;
			isSearchPage = true;
		}
		if (state == null) {
			arrRefineState = null;
		} 
		else {
			arrRefineState = state.split("@");
		}
		loadItems(cid, state, arrRefineState, parentID, strQuery, currentPage, pageSize, pageSort, maxResultCount);
	}
}
function loadItems(cid, state, arrRefineState, parentID, strQuery, currentPage, pageSize, pageSort, maxResultCount) {
	if (cid == null) {
		return false;
	}
	if (strQuery == null) {
	   strQuery = "";
	}
	if (state != null) {
		var stateClean = cleanState(state);
		state = state.replace("&","@"); //This is needed for the ajax call. Not sure why it doesn't like stateClean
	} else {
		var stateClean = "";
	}

	//This has been taken out of the ajax call which means you can click stuff that should not be enabled
	selectLinks(arrRefineState);
	buildHrefs(stateClean, arrRefineState, cid, strQuery);
	buildClearHrefs(arrRefineState, cid, strQuery);
	//re-enable the controls
	enableControls();
	renderClearLinks(stateClean, arrRefineState);
	showSizeIfProductTypeSelected(arrRefineState);

	href = getServiceAddress();
	var ajaxManager = $.manageAjax({ manageType: 'abortOld', maxReq: 0 });

	ajaxManager.add({
	    type: "POST",
	    url: href,
	    beforeSend: function(xhr) {
	        xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
	    },
	    data: "{'cid':'" + cid + "', 'strQuery':'" + strQuery + "', 'strValues':'" + state + "', 'currentPage':'" + currentPage + "', 'pageSize':'" + pageSize + "','pageSort':'" + pageSort + "','countryId':'" + countryId + "','maxResultCount':'" + maxResultCount + "'}",
	    contentType: "application/json; charset=utf-8",
	    dataType: "json",
	    success: function(data) {
	        var dataTotalItems = data.d.pageStates[0].TotalItems;
	        if (dataTotalItems == "0") {
	            hideOverlay();
	            showNoItemsLightBox(parentID);
	        }
	        else {
                $("#maxResultCount").val(data.d.maxResultCount);
	            var dataCurrentPage = data.d.pageStates[0].CurrentPage;
	            var dataPageSize = data.d.pageStates[0].PageSize;
	            var dataPageSort = data.d.pageStates[0].PageSort;
	            if (parentID != null) {
	                var arr;
	                eval("arr=" + data.d.enabledAttributes);
	                $.each($("#controls > .control > ul"), function() {
	                    if (this["id"] != parentID ) {
	                        $(this).children("li").children("a").removeClass("enabled").attr("disabled", "disabled");
	                    }
	                    if(this["id"] == "Rf-700"){
	                        $(this).children("li").children("a").addClass("enabled").removeAttr("disabled");
	                    }
	                    
	                });
	                $.each(arr, function(i, control) {
	                    if (control) {
	                        $.each(control.AttributeItems, function(i, option) {
	                            option = option.replace("%26", "*");
	                            if (control.AttributeId != parentID) {
	                                $("#controls > .control").children("#Rf" + control.AttributeId).children("li").children("a[name=" + option + "]").addClass("enabled").removeAttr("disabled");
	                            }
	                        });
	                    }
	                });
	                //This is a special case for when there is only one refinement
	                if (arrRefineState != null && arrRefineState.length == 1) {
	                    refineID = arrRefineState[0].split("=")[0];
	                    $("#" + refineID + " > li > a").addClass("enabled").removeAttr("disabled");
	                }
	                //should this should go into a seperate function?
	                $("#controls > .control").removeClass("hidden");
	                $.each(arr, function(i, control) {
	                    if (control) {

	                        if (control.AttributeHidden) {
	                            $("#Rf" + control.AttributeId).parent().addClass("hidden");
	                        }
	                    }
	                });
	            } else {
	                $("#controls > .control > ul > li > a.enabled").removeClass("enabled").attr("disabled", "disabled");
	                $("#controls > .control > ul > li > a").addClass("enabled").removeAttr("disabled");
	            }

	            renderPaging(cid, dataTotalItems, dataCurrentPage, dataPageSize, dataPageSort, strQuery);
	            buildPagingHrefs(state, arrRefineState, cid, strQuery);
	            $("#resultsCount").text(dataTotalItems);
	            $(".total-items").text(dataTotalItems);
	            // hide the header
	            if(currentPage != "0") {
	                $("div.header_html").addClass("hide");
	            } else {
					$("div.header_html").removeClass("hide");
	            }
	            var itemLoadType = $("#itemLoadType").val();
	            var itemLoadSpeed = $("#itemLoadSpeed").val();
				renderItems("#items", "#itemTemplate", data.d, itemLoadType, itemLoadSpeed);
                
                hideOverlay();
	            	            
	            $("#hdnLastState").val(document.location.search + "&" + stateClean + "&pge=" + currentPage + "&pgeSize=" + pageSize + "&sort=" + pageSort);
	           
	            addProductTypeAnalytics(arrRefineState);
	        }
	        if (btmPagingClicked) {
	            scrollToTop();
	            btmPagingClicked = false;
	        }
	        
	        //Refresh Ad Banner - raise custom ajax-refresh event
			$(document).trigger("ajax-refresh");

	        //trigger event to resend analytics
            $(document).trigger("ajax-trigger-analytics");
	        
	    },
	    error: function(xhr, ajaxOptions) {
	        var errorTitle = xhr.statusText;
	        var errorText = "Your selection caused no results to be returned.<!-- " + xhr.status + " -->";
	        ajaxError(errorTitle, errorText,true);
	        if (btmPagingClicked) {
	            scrollToTop();
	            btmPagingClicked = false;
	        }
	    }
	});
}
function disableControls() {
	$("#slider").slider('disable').css("opacity","0.5");
	$("#controls > .control > ul > li > a").addClass("disabled");
}
function enableControls() {
	$("#controls > .control > ul > li > a.disabled").removeClass("disabled");
	$("#slider").slider('enable').removeAttr("style");
}
function ajaxError(title, text, resetCategory) {
	$("#error").dialog('destroy');
	$("#error").dialog({
	    bgiframe: true,
	    close: function() {
	        if (resetCategory) {
	            window.location = $("#controls a.clear-all").attr("href");
	            return false;
	        } else {
	            noResultsMoveBack();
	        }
	    },
	    height: 90,
	    modal: true,
	    open: function() {
	        $("#error").show();
	        $(".ui-resizable-handle").css("display", "none");
	    },
	    overlay: {
	        opacity: 0.7,
	        background: "#000000"
	    },
	    width: 600
	});
	$("#error .error-title").html(title);
	$("#error .error-text").html(text);
	//top.location="errorpage.html";
}
function renderClearLinks(stateClean, arrRefineState) {
	if (stateClean == null || stateClean == "") {
		$("#controls a.clear-all").addClass("hide");
	} else {
		$("#controls a.clear-all").removeClass("hide");
	}
	$("#controls a.clear").addClass("hide");
	if (arrRefineState != null && arrRefineState.length > 0) {
		$.each(arrRefineState, function() {
			if (this.search("=") > 0) {
				var thisElemArr = this.split("=");
				var thisKey = thisElemArr[0];
				$("#"+thisKey).siblings("div.refine-control-header").children("a.clear").removeClass("hide");
			} else {
				ajaxError('URL Badly formed', 'The page you are trying to view has a badly formed URL. It is possible that you mistyped it, or you were sent an incorrect link.',false);
				return false;
			}
		});
	}
}
function noResultsMoveBack() {
	var lastState = $("#hdnLastState").val(); //.replace('#', '&');
	if (lastState == "") {
		lastState = document.location.search;
		createHistoryPoint(lastState, -1);
	}
	else {
		history.back();
	}
}
function getServiceAddress() {
	return $("#hdnWebServiceAddress").val();
}
function initialOverlay() {
	bgxPos = $(".overlay").width()/2 + $(".overlay").parent().offset().left - 24;
	height = $(".overlay").parent().parent().height();
	$(".overlay").show();
	if($(".overlay").css("background-attachment")=="fixed") { //for browsers that don't support fixed background attachements (IE6)
		$(".overlay").css("background-position", bgxPos+"px 50%");
	}
	$(".overlay").css({
		"height": height+"px",
		"opacity": "1"
	}).animate({ opacity: 0.7 }, 500);
}
function showOverlayAndCreateHistoryPoint(obj) {
    if ($(".overlay").css("display") != "block") {
        if ($(".overlay").parent().offset() != null) {
			bgxPos = $(".overlay").width()/2 + $(".overlay").parent().offset().left - 24;
		}else {
		    bgxPos = $(".overlay").width() / 2 - 24;
		}

		
		height = $(".overlay").parent().parent().height();
		$(".overlay").show();
		if($(".overlay").css("background-attachment")=="fixed") { //for browsers that don't support fixed background attachements (IE6)
			$(".overlay").css("background-position", bgxPos+"px 50%");
		}
	}
	$(".overlay").css({
		"height": height+"px",
		"opacity": "0"
	}).animate(
		{ opacity: 0.7 },
		500,
		function() {
			Sys.Application.addHistoryPoint(obj, null)
		}
	);
}	
function hideOverlay() {
	if( $("#hdnLastState").val().length > 0 ) {
		hideOverlayAnimate();
	} else {
		setTimeout("hideOverlayAnimate()", 500);
	}
}
function hideOverlayAnimate() {
	$(".overlay").animate({ opacity: 0 }, 500, function() {
		$(this).hide()
	});
}
function getRefineStateAsHistoryObject(href, parentID) {
	var qString = href.split("?");
	var arrQString;
	var strState = '';
	var currentPageNumber = getParam(href, "pge");
	var currentPageSize = getParam(href, "pgeSize");
	var currentSort = getParam(href, "sort");
	if (currentPageNumber == undefined) {
		currentPageNumber = currentPage;	// the global variable
	}
	if (currentPageSize == undefined) {
		currentPageSize = pageSize;
	}
	if (currentSort == undefined) {
		currentSort = pageSort;
	}
	if (qString[1].length > 0) {
		arrQString = qString[1].replace('@','&').split("&");

		$.each(arrQString, function() {
			var thisElemArr = this.split("=");
			var thisKey = thisElemArr[0];
			if (thisKey.substring(0, 2).toLowerCase() == 'rf') {
				strState += this + '@';
			}
		});
		
		if(strState.substring(strState.length - 1, strState.length) == '@') {
			strState = strState.substring(0, strState.length - 1);
		}
		
		var objOut = new Object;
		if (strState.length > 0) {
			strJSONObj = getJSONStateString(strState, parentID, currentPageNumber, currentPageSize, currentSort);
			objOut = JSON.parse(strJSONObj);
		} else {
			strJSONObj = getJSONStateString(null, parentID, currentPageNumber, currentPageSize, currentSort);
			objOut = JSON.parse(strJSONObj);
		}

	} else {
		strJSONObj = getJSONStateString(null, parentID, currentPageNumber, currentPageSize, currentSort);
		objOut = JSON.parse(strJSONObj);
	}
	return objOut;
}
function getJSONStateString(state, parentID, currentPage, currentPageSize, currentSort) {
	var output;
	if(parentID == null) {
		if(state == null){
			output = '{"state":' + state + ', "pge":"' + currentPage + '", "pgeSize":"' + currentPageSize + '", "sort":"' + currentSort + '"}';
		} else {
			output = '{"state":"' + state + '", "pge":"' + currentPage + '", "pgeSize":"' + currentPageSize + '", "sort":"' + currentSort + '"}';
		}
	} else {
		if(state == null){
			output = '{"state":' + state + ', "parentID":"' + parentID + '", "pge":"' + currentPage + '", "pgeSize":"' + currentPageSize + '", "sort":"' + currentSort + '"}';
		} else {
			output = '{"state":"' + state + '", "parentID":"' + parentID + '", "pge":"' + currentPage + '", "pgeSize":"' + currentPageSize + '", "sort":"' + currentSort + '"}';
		}
	}
	return output;
}

function initializeSlider() {
	var sliderValues = new Array();
	sliderValues[0] = $("#userMin").html();
	sliderValues[1] = $("#userMax").html();
	sliderMinMax(sliderValues);
	$("#userMin").html(sliderValues[0]);
	$("#userMax").html(sliderValues[1]);
	createSlider("#slider",sliderValues);
	//moveUserSliderPriceSelections();
	//create initial state for slider
	$("#stateHref").val("?cid=" + queryString('cid'));
}

function createSlider(sliderID, sliderValues) {
	var sliderStepSize = $("span#slider-step-size > input").val();
	if(sliderStepSize > 0) {
		var min = $("#productMin").text();
		var max = $("#productMax").text();
		if( min == max ) {
			sliderValues[0] = sliderValues[0]-1;
			sliderValues[1] = sliderValues[1]+1;
		}
		$(sliderID).slider({
			handles: [
				{ start: sliderValues[0] },
				{ start: sliderValues[1] }
			],
			min: min,
			max: max,
			range: true,
			slide: function(event, ui) {
				$("#userMin").text($(this).slider("value", 0));
				$("#userMax").text($(this).slider("value", 1));
			},
			stop: function(event, ui) {
				$("#userMin").text($(this).slider("value", 0));
				$("#userMax").text($(this).slider("value", 1));
				disableControls();
				var parentID = $(this).parent().attr("id");
				var href = $("#stateHref").val() + "&";
				var exchangeRate = parseFloat($("#exchangeRate").val());
				if ($("#sliderState").val() != "") {
					href = href + $("#sliderState").val() + "&";
				}
				var selectedMin = $("#userMin").text();
				if (selectedMin == $("#productMin").text()) {
					selectedMin = -1;
				} else {
					selectedMin = (parseFloat(selectedMin) / exchangeRate).toFixed(3);
				}
				var selectedMax = $("#userMax").text();
				if (selectedMax == $("#productMax").text()) {
					selectedMax = -1;
				} else {
					selectedMax = (parseFloat(selectedMax) / exchangeRate).toFixed(3);
				}
				if(selectedMin == -1 && selectedMax == -1 ) {
					//nothing
				} else {
					href = href + parentID + "=" + selectedMin + "," + selectedMax + "&pge=0";
				}
				$("div.ui-slider-handle").removeClass("ui-slider-handle-active");
				createHistoryPoint(href, parentID);
			},
			steps: (($("#productMax").html()-$("#productMin").html())/sliderStepSize)
		});
		$(sliderID).parent().css("visibility","visible");
	}
}
function updateSlider(sliderID, sliderValue) {
	var sliderStepSize = $("span#slider-step-size > input").val();
	sliderMinMax(sliderValue);
	var exchangeRate = parseFloat($("#exchangeRate").val());
	if(sliderValue[0] != $("#productMin").html()) {
		sliderValue[0] = (Math.round((sliderValue[0] * exchangeRate)/sliderStepSize))*sliderStepSize; //round to nearest sliderStepSize
	}
	if(sliderValue[1] != $("#productMax").html()) {
		sliderValue[1] = (Math.round((sliderValue[1] * exchangeRate)/sliderStepSize))*sliderStepSize; //round to nearest sliderStepSize
	}

	if($("#userMin").html() == sliderValue[0] && $("#userMax").html() == sliderValue[1] ) {
		//no need to change the slider
	} else {
		$("#userMin").html(sliderValue[0]);
		$("#userMax").html(sliderValue[1]);
		$(sliderID).slider("destroy").empty();
		createSlider(sliderID, sliderValue);
	}
}
function sliderMinMax(sliderValue) {
	if(sliderValue[0] == -1 || sliderValue[0] == null) {
		sliderValue[0] = $("#productMin").html();
	}
	if(sliderValue[1] == -1 || sliderValue[1] == null) {
		sliderValue[1] = $("#productMax").html();
	}
	return sliderValue;
}
function moveUserSliderPriceSelections() {
	var leftHandle = ( parseFloat($(".ui-slider-handle:first").css("left")) - (parseFloat($("#userMin").width() )/2) ) + 2 + "px";
	var rightHandle = ( parseFloat($(".ui-slider-handle:last").css("left")) - (parseFloat($("#userMax").width() )/2) ) + 2 + "px";
	$(".slider-price-user-min").css({
		"left": leftHandle
	});
	$(".slider-price-user-max").css({
		"left": rightHandle
	});
}
function selectLinks(arrRefineState) {
	var sliderValue = new Array();
	$("#controls > .control > ul > li > a.selected").removeClass("selected");
	if (arrRefineState != null && arrRefineState.length > 0) {
		$.each(arrRefineState, function() {
			if (this.search("=") > 0) {
				var thisElemArr = this.split("=");
				var thisKey = thisElemArr[0];
				var thisValue = thisElemArr[1].split(",");
				$.each(thisValue, function() {
					$("ul#" + thisKey + " > li > a[name=" + this.replace("%26", "*") + "]").addClass("selected");
				});
				//set slider variables
				if (thisKey == "Rf-800") {
					sliderValue = thisValue;
				}
			} else {
				ajaxError('URL Badly formed', 'The page you are trying to view has a badly formed URL. It is possible that you mistyped it, or you were sent an incorrect link.', false);
			}
		});
	}
	updateSlider("#slider", sliderValue);
}
function showSizeIfProductTypeSelected(arrRefineState) {
	var showSize = false;
	if( $("ul#Rf-100").length > 0 ) {
		if (arrRefineState != null && arrRefineState.length > 0) {
			$.each(arrRefineState, function() {
				if (this.search("=") > 0) {
					var thisElemArr = this.split("=");
					var thisKey = thisElemArr[0];
					var thisValue = thisElemArr[1].split(",");
					if(thisKey == "Rf-100" || thisKey == "Rf-300" ) {
						showSize = true;
					}
				} else {
					ajaxError('URL Badly formed', 'The page you are trying to view has a badly formed URL. It is possible that you mistyped it, or you were sent an incorrect link.',false);
				}
			});
		}
		if($("#showSizeAttribute").val()== "True") {
			showSize = true;
		}
	} else {
		showSize = true;
	}
	if(showSize) {
							
		$("ul#Rf-300").parent().removeClass("hide");
	} else {
		$("ul#Rf-300").parent().addClass("hide");
	}
}
function buildHrefs(stateClean, arrRefineState, cid, searchQuery) {
	var href = "";
	var thisHref = "";
	var isSearchPage = false;
	
	var stateClean = stateClean + '&';
	/*var stateClean = "";

	if (state != null && state != "") {
		//stateClean = state.replace(/@/g, "&") + '&';
		stateClean = cleanState(state) + '&';
	}*/
	
	if (searchQuery != null && searchQuery != "") {
		isSearchPage = true;
		href = "?q=" + searchQuery;
	} else {
		href = "?cid=" + cid;
	}
	
	// deal with refine links
	$.each($("#controls > .control > ul"), function() {
		var parentID = $(this).attr("id");  	        

		//"?cid=" + queryString('cid');
		$.each($("#" + parentID).children("li").children("a"), function() {
			var linkName = this["name"].replace("*","%26");
			var hrefState = attributeHref(stateClean, arrRefineState, parentID, linkName);
			hrefState =  stripHangingCharacters(hrefState, "&");
			if (hrefState.length > 0) {
				var hrefState = "&" + hrefState;
			}
			thisHref = href + hrefState;
			thisHref =  stripHangingCharacters(thisHref, "&");
			$(this).attr("href", thisHref);
		});
		//For the slider
		var sliderState = "";
		if (arrRefineState != null) {
			$.each(arrRefineState, function() {
				var thisElemArr = this.split("=");
				var thisKey = thisElemArr[0];
				if (thisKey != "Rf-800") {
					sliderState = sliderState + "&" + this;
				}
			});
		}
		sliderState = stripHangingCharacters(sliderState, "&");
		$("#sliderState").val(sliderState);
	});
}
function buildPagingHrefs(state, arrRefineState, cid, searchQuery) {
	var href = "";
	var thisHref = "";
	var newHref = "";
	var isSearchPage = false;
	
	if (state != null && state != "") {
		//stateClean = state.replace("@", "&") + '&';
		stateClean = cleanState(state) + '&';
	} else {
		stateClean = "";
	}
	if (searchQuery != null && searchQuery != "") {
		isSearchPage = true;
		href = "?q=" + searchQuery;
	} else {
		href = "?cid=" + cid;
	}
	//deal with paging controls
	$.each($("ol.page-nos > li > a"), function() {
		thisHref = this["href"];
		thisHref = thisHref.substring(thisHref.indexOf('?') + 1, thisHref.length);
		var thisPgeElem = '';
		var i = 0;
		var thisHrefArr = thisHref.split('&');
		if (thisHref.length > 0) {
			for (i = 0; i < thisHrefArr.length - 1; i++) {
				var thisElem = thisHrefArr[i];
				if (thisElem.toLowerCase().indexOf('pge=') == 0) {
					thisPgeElem = thisElem.toLowerCase();
					break;
				}
				newHref = href + '&' + stateClean + thisPgeElem + '&pgesize' + pageSize + '&sort' + pageSort;                                         
			}
			newHref = href + '&' + stateClean +  thisPgeElem + '&pgesize=' + pageSize + '&sort=' + pageSort;                                         
		}
		$(this).attr("href", newHref);
	});
	// the paged view and view all links
	var defaultPageSize = $("#hdnDefaultPgeSize").val();
	var maxPageSize = $("#hdnMaxPgeSize").val();
	var viewAllPageSize = $("#hdnViewAllPgeSize").val();
	newHref = href + '&' + stateClean + 'pge=' + 0 + '&pgesize=' + defaultPageSize + '&sort=' + pageSort;
	$("a.view-paged").attr("href", newHref);
	newHref = href + '&' + stateClean + 'pge=' + 0 + '&pgesize=' + maxPageSize + '&sort=' + pageSort;
	$("a.view-max-paged").attr("href", newHref);
	newHref = href + '&' + stateClean + '&pge=' + 0 + '&pgesize=' + viewAllPageSize + '&sort=' + pageSort;
	$("a.view-all").attr("href", newHref);
	// the sort options
	$("select.filterSort > option").each(function() {
		//var currentSortHref = $(this).val();
		//var currentSortNumber = getParam(currentSortHref, "sort");
		newHref = href + '&' + stateClean + 'pge=0&pgesize=' + pageSize;
		//$(this).val(newHref);
		setSortLinks(newHref, $(this))
	});
}
function buildClearHrefs(arrRefineState, cid, searchQuery) {
	var href = "";
	var thisHref = "";
	var isSearchPage = false;
	
	if (searchQuery != null && searchQuery != "") {
		isSearchPage = true;
		href = "?q=" + searchQuery;
	} else {
		href = "?cid=" + cid;
	}

	$.each($("#controls .control a.clear"), function() {
		var parentID = $(this).parent().siblings().attr("id");         
		var hrefState = "";
		if (arrRefineState != null && arrRefineState.length > 0) {
			$.each(arrRefineState, function() {
				if (this.search("=") > 0) {
					var thisElemArr = this.split("=");
					var thisKey = thisElemArr[0];
					var thisValue = thisElemArr[1].split(",");
					if (thisKey == parentID) {
						//hrefState = state.replace(thisKey + "=" + thisValue, "");
					} else {
						hrefState = hrefState + "&" + thisKey + "=" + thisValue;
					}
				} else {
					ajaxError('URL Badly formed', 'The page you are trying to view has a badly formed URL. It is possible that you mistyped it, or you were sent an incorrect link.',false);
					return false;
				}
			});
			
		}
		
		hrefState = cleanState(hrefState) + '&';
		//hrefState = hrefState.replace("@", "&") + '&';
		hrefState =  stripHangingCharacters(hrefState, "&");
		if (hrefState.length > 0) {
			var hrefState = "&" + hrefState;
		}
		thisHref = href + hrefState;
		$(this).attr("href", thisHref);

	});
}
function setSortLinks(hrefWithoutSort, currentSortOption){
	var currentSortHref = currentSortOption.val();
	var currentSortNumber = getParam(currentSortHref, "sort");
	var newHref = hrefWithoutSort + '&sort=' + currentSortNumber;
	currentSortOption.val(newHref);
}

function attributeHref(stateClean, arrRefineState, parentID, linkName) {
	var href = "";
	if (arrRefineState != null && arrRefineState.length > 0) {
		$.each(arrRefineState, function() {
		
			if (this.search("=") > 0) {
				var thisElemArr = this.split("=");
				var thisKey = thisElemArr[0];
				if (thisKey == parentID) {
					var thisValue = thisElemArr[1].split(",");
					$.each(thisValue, function() {
						if (this.toLowerCase() == linkName.toLowerCase()) {
							//This is for attributes which have been selected						
                            if (thisValue.length > 1) {
							    var newValue = thisElemArr[1].replace(this, "");
							    newValue = stripHangingCharacters(newValue, ",");
							    href = stateClean.replace(thisKey + "=" + thisValue, thisKey + "=" + newValue);
							}
							else {
								    href = stateClean.replace(thisKey + "=" + thisValue, "");
								    if (href == "") {
									    href = "&" + href;
									
									//search exception for floors
					                if( thisKey == "Rf-700" ){
                                       href = "Rf-700=" + linkName; 
					                }	
								}
							}
						}
					});

					//This is for attributes in a refined control which have not been selected
					if (href == "") {
						href = stateClean.replace(thisKey + "=" + thisValue, thisKey + "=" + thisValue + "," + linkName);
						
						//search exception for floors
		                if( thisKey == "Rf-700" ){
                           href = stateClean.replace(thisKey + "=" + thisValue, thisKey + "=" + linkName);
		                }	
					}
				}
			} else {
				ajaxError('URL Badly formed', 'The page you are trying to view has a badly formed URL. It is possible that you mistyped it, or you were sent an incorrect link.',false);
				return false;
			}
		});
	}
	if (href == "") {
		//This is the default case
		if (arrRefineState != null && arrRefineState.length > 0) {
			href = stateClean + "&" + parentID + "=" + linkName;
		} else {
			href = parentID + "=" + linkName;
		}
	}
	return href;
}
function stripHangingCharacters(string, character) {
	if (string.charAt(0) == character) {
		string = string.substring(1, string.length);
	}
	if (string.charAt(string.length - 1) == character) {
		string = string.substring(0, string.length - 1);
	}
	string = string.replace(character + character, character);
	return string;
}

function queryString(ji) {
	hu = window.location.search.substring(1).toLowerCase();
	gy = hu.split("&");
	for (i = 0; i < gy.length; i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji.toLowerCase()) {
			return ft[1];
		}
	}
}

function getParam(queryString, paramName) {
	paramArray = queryString.toLowerCase().split("&");
	for (i = 0; i < paramArray.length; i++) {
		nameValuePair = paramArray[i].split("=");
		if (nameValuePair[0] == paramName.toLowerCase()) {
			return nameValuePair[1];
		}
	}
}
function getDefaultValue(variableName) {
	var output = "";
	var variableNameToLower = variableName.toLowerCase()
	output = $("input.default_" + variableNameToLower).val();
	if(output == ""){
		var s = variableName;	// debugging
	}
	return output;
}
function showNoItemsLightBox(parentID){
	var refinementName = $("#"+parentID).parent().find("div.refine-control-header h3").text();
	errorMsg = "Your <span class='error-details'>" + refinementName + "</span> selection caused no results to be returned - please widen your search criteria.";
	ajaxError("No Results Found", errorMsg,false);
}
function clearCheckBoxes() {
	$("#controls > .control > ul > li > a.selected").removeClass("selected");
}
function renderPaging(cid, totalItems, currentPage, pageSize, pageSort, strQuery) {
	$('ol.page-nos').removeClass("hide").empty();
	var pageLinksString = "";
	var pageTypeQuery = '';
	var liTemplate = '';
	var aTemplate = '';

	if (pageSize != -1) {
		aTemplate = $("input.aTemplate").val();

		if (strQuery != '' && strQuery != null) {
			// get Search template
			//aTemplate = $("input.aTemplateSearch").val();
			//aTemplate = jQuery.trim(aTemplate.replace('#QUERY#', strQuery));
			pageTypeQuery = "q=" + strQuery;
		} else {
			// get category template
			//aTemplate = $("input.aTemplateCategory").val();
			//aTemplate = jQuery.trim(aTemplate.replace('#CID#', cid));
			pageTypeQuery = "cid=" + cid;
		}
		aTemplate = jQuery.trim(aTemplate.replace('#PAGETYPEQUERY#', pageTypeQuery))
		liTemplate = jQuery.trim($(".liTemplate").val());
		aTemplate = aTemplate.replace("#PGESIZE#", pageSize).replace("#SORT#", pageSort);

		//Refining added to URL here - blank for now
		aTemplate = aTemplate.replace("#REFINING#", "");

		// create Next and Previous links
		var previous = parseInt(currentPage) - 1;
		var previousLink = liTemplate.replace("#LIBODY#", aTemplate.replace("#PGE#", previous).replace("#ABODY#", "&laquo;&nbsp;Previous")).replace('#LIVALUES#', ' class="page-skip" ');
		var next = parseInt(currentPage) + 1;
		var nextLink = liTemplate.replace("#LIBODY#", aTemplate.replace("#PGE#", next).replace("#ABODY#", "Next&nbsp;&raquo;")).replace('#LIVALUES#', ' class="page-skip" ');
		liTemplate = liTemplate.replace("#LIVALUES#", "");


		var spacer = liTemplate.replace("#LIBODY#", "...");

		var totalPages = Math.round(totalItems / pageSize);
		if (totalPages < (totalItems / pageSize)) {
			// rounded down... so increment by one
			totalPages++;
		}
		if (currentPage > 0) {
			pageLinksString += previousLink;
		}
		if (currentPage < 5) {
			var stop = 5;
			if (totalPages < stop || totalPages == 6) {
				stop = totalPages;
			}
			for (i = 0; i < stop; i++) {
				if (i == currentPage) {
					pageLinksString += liTemplate.replace("#LIBODY#", "<span class='selected'>" + (i + 1) + "</span>");
				}
				else {
					pageLinksString += liTemplate.replace("#LIBODY#", aTemplate.replace("#PGE#", i).replace("#ABODY#", (i + 1)));
				}
			}
			if (totalPages > 5 && totalPages != 6) {
				pageLinksString += spacer;
				pageLinksString += liTemplate.replace("#LIBODY#", aTemplate.replace("#PGE#", (totalPages - 1)).replace("#ABODY#", totalPages));
			}
		}
		else {
			if (totalPages != 6) {
				pageLinksString += liTemplate.replace("#LIBODY#", aTemplate.replace("#PGE#", 0).replace("#ABODY#", 1));
				pageLinksString += spacer;
			}
			if (currentPage >= (totalPages - 5)) {
				var start = totalPages - 5;
				if (totalPages == 6) {
					start = 0; // include the first link, as we have ignored the 1... above...
				}
				// render the tail.
				for (i = start; i < totalPages; i++) {
					if (i == currentPage) {
						pageLinksString += liTemplate.replace("#LIBODY#", "<span class='selected'>" + (i + 1) + "</span>");
					}
					else {
						pageLinksString += liTemplate.replace("#LIBODY#", aTemplate.replace("#PGE#", i).replace("#ABODY#", (i + 1)));
					}
				}
			}
			else {
				// render the middle.
				var startIndex = parseInt(currentPage) - 2;
				var stopIndex = parseInt(currentPage) + 2;
				for (i = startIndex; i < (stopIndex + 1); i++) {
					var displayIndex = i + 1;
					if (i == currentPage) {
						pageLinksString += liTemplate.replace("#LIBODY#", "<span class='selected'>" + (i + 1) + "</span>");
					}
					else {
						pageLinksString += liTemplate.replace("#LIBODY#", aTemplate.replace("#PGE#", i).replace("#ABODY#", (i + 1)));
					}
				}
				pageLinksString += spacer;
				pageLinksString += liTemplate.replace("#LIBODY#", aTemplate.replace("#PGE#", (totalPages - 1)).replace("#ABODY#", totalPages));
			}
		}
		if (currentPage < totalPages - 1) {
			pageLinksString += nextLink;
		}
	
		//use ol class here to ensure top and bottom paging is updated
		$('ol.page-nos').append(pageLinksString);
	}
	/*if (parseInt(totalItems) <= parseInt(pageSize)) {
		$('ol.page-nos').empty();
		$("a.view-all").addClass("hide");
		$("a.view-paged").addClass("hide");
		if (!$("a.back-to-top").hasClass("hide")) {
			$("a.back-to-top").addClass("hide");
		}
	}*/
	
	
	// Deal with View link visibility
	$("a.view-paged").removeClass("hide");
	$("a.view-all").removeClass("hide");
	$("a.view-max-paged").removeClass("hide");
	$("span.styles-found").removeClass("hide");	    
	$("span.veiwing-all-notification").removeClass("hide");
	var defaultPageSize = parseFloat($("#hdnDefaultPgeSize").val());
	var maxPageSize = parseFloat($("#hdnMaxPgeSize").val());
	var viewAllPageSize = parseFloat($("#hdnViewAllPgeSize").val());
	if (pageSize == viewAllPageSize ) {
		// for view all/view 200 per page - show view-paged, hide viewall, show back-to-top
		$("a.view-all").addClass("hide");
		$("a.view-max-paged").addClass("hide");
		if(totalItems <= maxPageSize) {
			$('ol.page-nos').empty();
		}
		if(totalItems > defaultPageSize) {
			$("a.view-paged").removeClass("hide");
			$("a.back-to-top").removeClass("hide");
		} else {
			$("a.view-paged").addClass("hide");
		}
		if (pageSize == maxPageSize ) {
			$("span.veiwing-all-notification").addClass("hide");
		}
	} else if (pageSize == defaultPageSize) {
		// for when there are 20 on a page - show view-max-paged, hide view-paged, hide view-all, hide back-to-top, hide veiwing-all-notification
		$("a.view-paged").addClass("hide");
		//$("a.view-all").addClass("hide");
		if (!$("a.back-to-top").hasClass("hide")) {
			$("a.back-to-top").addClass("hide");
		}
		if(totalItems > defaultPageSize) {
			$("span.veiwing-all-notification").addClass("hide");
		} else {
			$('ol.page-nos').empty();
			$("a.view-all").addClass("hide");
		}
		if(totalItems > maxPageSize) {
			$("a.view-all").addClass("hide");
		} else {
			$("a.view-max-paged").addClass("hide");
			$("span.styles-found").addClass("hide");
		}
	} else {
		// hide view-paged and viewall
		$("a.view-paged").addClass("hide");
		$("a.view-all").addClass("hide");
		if (!$("a.back-to-top").hasClass("hide")) {
			$("a.back-to-top").addClass("hide");
		}			
	}
	$("ol.page-nos a").click(function() {
		pageNumbers(this)
        return false;
    });
}
function filterPath(string) {
	return string
	.replace(/^\//,'')
	.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
	.replace(/\/$/,'');
}
function cleanState(state) {
	stateClean = state.replace(/@/g, "&");
	return stateClean;
}

function addProductTypeAnalytics(arrRefineState) {
    var productType = '';
	if (arrRefineState != null && arrRefineState.length > 0) {
		$.each(arrRefineState, function() {
		    if (this.search("=") > 0) {
		        var thisElemArr = this.split("=");
			    var thisKey = thisElemArr[0];
				var thisValue = thisElemArr[1].split(",");
				if (thisKey == "Rf-100") {
				    $.each(thisValue, function() {
					    if(productType.length == 0){
					        productType += this;
					    }else{
					        productType += ';' + this;
					    }  
				    });
				}
		    } else {
				ajaxError('URL Badly formed', 'The page you are trying to view has a badly formed URL. It is possible that you mistyped it, or you were sent an incorrect link.', false);
			}
		});
    }
    productType = productType.replace(/\+/g, ' ');
    dcsMultiTrack('DCS.dcsuri','/producttype_event.htm','WT.ti', 'Product Type event', 'DCSext.productType', productType);
}
function renderItems(itemContainer, itemTemplate, itemData, renderType, speed) {
	if(renderType!="progressive") {
		$("#items").setTemplateElement("template");
		$("#items").processTemplate(itemData);
	} else {
		$(itemContainer).empty();
		var template = $(itemTemplate).text();
		stopCurrentRefinementLoading = false;
		$(itemData.items).slowEach(speed, function() {
			if(!stopCurrentRefinementLoading){
				var item = template;
				if(this.videoPath=="") {
					item = item.replace(/videosrc="#videoPath#"/, "");
				}
				if(this.mixMatch == "SUBGROUP") {
					item = item.replace(/#price#/, "FROM #price#");
				}
				if(this.showNowPrefixString == false) {
					if(this.minPrice != '') {
						item = item.replace(/#price#/, "FROM #minprice#");
					}
				} else {
					item = item.replace(/#price#/, "#prevprice#");
				}
				if(this.showNowPrefixString == true) {
					if(this.mixMatch != "SUBGROUP") {
						if(this.minPrice != '') {
							item = item.replace(/#prevpricespan#/, "<br/>NOW FROM #minprice#");
						} else {
							item = item.replace(/#prevpricespan#/, "<br/>NOW #price#");
						}
					} else {
						item = item.replace(/#prevpricespan#/, "<br/>NOW FROM #price#");
					}
				} else {
					item = item.replace(/#prevpricespan#/, "");
				}
				if(this.showOutletString==true) {
					item = item.replace(/#origprice#/, "SAVE #origprice#");
					if(this.minPrice != '') {
						item = item.replace(/#origprice#/, "UPTO #origprice#");
					}
					item = item.replace(/#origprice#/, "#pricereducedby# (#savingspercent#%)");
				} else {
					item = item.replace(/#origprice#/, "");
				}
				if(this.showOutletString==true) {
					item = item.replace(/#recrp#/, "RRP #recrp#");
				} else {
					item = item.replace(/#recrp#/, "");
				}
				if(this.mixMatch!="") {
					item = item.replace(/<a href='#NavigateURL#' class='more-colours'><\/a>/, "<a href='#NavigateURL#' class='more-colours'>Mix &amp; Match</a>");
				}
				else if(this.moreColors==true) {
					item = item.replace(/<a href='#NavigateURL#' class='more-colours'><\/a>/, "<a href='#NavigateURL#' class='more-colours'>More Colours</a>");
				} else {
					item = item.replace(/<a href='#NavigateURL#' class='more-colours'><\/a>/, "");
				}
				item = item
						.replace(/#desc#/g, this.desc)
						.replace(/#NavigateURL#/g, this.NavigateURL)
						.replace(/#image#/g, this.image)
						.replace(/#videoPath#/g, this.videoPath)
						.replace(/#price#/g, this.price)
						.replace(/#minprice#/g, this.minPrice)
						.replace(/#prevprice#/g, this.prevPrice)
						.replace(/#pricereducedby#/g, this.priceReducedBy)
						.replace(/#savingspercent#/g, this.savingsPercent)
						.replace(/#recrp#/g, this.recRP);
				$(itemContainer).append(item);
			} else {
				return false;
			}
		});
	}

}
function pageNumbers(clickedElement) {
	currentPage = getParam(clickedElement.search, "pge");
	prepareForHistoryPoint($(clickedElement), -1);
	if ($(clickedElement).parent().parent().parent().hasClass("bottom")) {
		btmPagingClicked = true;
	}
	return false;
}