﻿//
// product listing pages specific functions
//
$(document).ready(function () {

    // ie dropdown fix
    //if ($.browser.msie) {
    //    if ($.ieSelectStyle != null) {
    //        $('.refinement-option').ieSelectStyle();
    //    }
    //}

    // add a click event to every element to hide the add to basket overlay on any click
    $(this).each(
        function (intIndex) {
            $(this).bind("click", function () {
                $(".list-tool-tip-wrap").fadeOut();
                $("[id$='appendedOverlay']").remove();
            });
        }
    );

    $('.tool-tip-close').click(function () {
        $('.list-tool-tip-wrap').hide();
        $("[id$='appendedOverlay']").remove();
        return false;
    });


    if (typeof commerce.ui != 'undefined') {
        if (typeof commerce.ui.swatchifyref != 'undefined') {
            commerce.ui.swatchifyref($(".refine-selection #Colour"));
        }
    }

    ApplyProductListMethods();
    ApplyDropDownListMethods();

    // Hide the items exceeding the set amount.
    $('li.more').hide();
    // Show the more link button.
    $('.refinement-group .more-submit').show();
    // Define the click event for the more link button.
    $('a.more-submit').click(function () {
        if ($(this).attr('action') != 'hide') {
            $('li.more[refinement=' + $(this).attr('refinement') + ']').show();
            $(this).attr('action', 'hide')
            $(this).text('Hide');
        }
        else {
            $('li.more[refinement=' + $(this).attr('refinement') + ']').hide();
            $(this).attr('action', 'show')
            $(this).text('More...');
        }
        return false;
    });

    // Numeric refinements can be displayed as a range slider if JavaScript is enabled.
    // For those refinements using a range slider, show the slider, hiding the standard (checkbox) refinement controls.
    $('.slider-range-wrap').show();
    $('.slider-range-wrap').each(function () {
        var sliderSection = $(this);
        var refinementName = sliderSection.attr("refinementName");
        $('.refinement-group[refinementname="' + refinementName + '"]').hide();
    });

    // Remove the href attribute to not navigate to a page when Javascript is enabled
    $('#refinement-standard a.refinement-option').removeAttr('href');

    // Remove the href attribute for the clear refinements link
    $('refinements-clear').removeAttr('href');

    // Enable/Disable the clear refinements link
    if ($('a.refinements-clear').length == 1) {
        if ($('#refinement-standard span.refinement-option input[checked]').length == 0) {
            // Disable
            SetupClearRefinements(false);
        }
        else {
            // Enable            
            SetupClearRefinements(true);
        }
    }

    // Handle the clear refinements click event
    $('a.refinements-clear').click(function () {
        ResetPageNumber();
        $('.configRefinementsSelected')[0].value = "";
        $('#refinement-standard span.refinement-option input').removeAttr('checked');
        $(".slider-range-wrap").each(function () {
            var sliderHolder = $(this).find('#slider-range');
            var minValue = sliderHolder.slider('option', 'min');
            var maxValue = sliderHolder.slider('option', 'max');
            $(this).find('input.slider-range-amount').val(minValue + '~' + maxValue);
            sliderHolder.slider('values', 0, minValue);
            sliderHolder.slider('values', 1, maxValue);
        });
        SetPagingPoint();
        SetupClearRefinements(false);
        return false;
    });

    // Handle the refinement click event
    $('#refinement-standard span.refinement-option input').click(function (event) {
        $('.refinements-container').block({ fadeIn: 0, timeout: 0, message: '<h5>Please wait...</h5>' });
        SetRefreshRefinements(true);
        setTimeout("RefinementCheckBoxSelect('" + $(this)[0].id + "'); ", 1);
        $('.refinements-container').unblock();
        event.stopPropagation();
    });

    // Populate the properties of any range sliders.
    $(".slider-range-wrap").each(function () {
        var range = $(this).find('input.slider-range-amount');
        if (range !== null && range.size() !== 0) {
            var valuesRange = range.val().split('~');
            var sliderWrapper = $(this);
            var sliderHolder = $(this).find('#slider-range');
            sliderHolder.slider({
                range: true,
                values: valuesRange,
                min: valuesRange[0],
                max: valuesRange[1],
                slide: function (event, ui) {
                    range.val(ui.values[0] + '~' + ui.values[1]);
                },
                stop: function (event, ui) {
                    $(".refinements-container").block({ fadeIn: 0, timeout: 0, message: '<h5>Please wait...</h5>' });
                    SetRefreshRefinements(true);
                    var refinementName = sliderWrapper.attr('refinementname');
                    var refinementRange = ui.values[0] + '~' + ui.values[1];
                    setTimeout("RefinementSliderSelect('" + refinementName + "', '" + refinementRange + "'); ", 1);
                    $(".refinements-container").unblock();
                    SetupClearRefinements(true);
                    event.stopPropagation();
                }
            });
        }
    });

    // Handle any change in the list of selected refinements. 
    if ($.address != undefined) {
        $.address.change(function (event) {
            if (event.value != '/') {
                var params = event.value.substring(1).split('&');

                // Clear the selected refinements
                $('.configRefinementsSelected')[0].value = "";

                for (counter = 0; counter < params.length; counter++) {
                    var queryStringItems = params[counter].split('=');
                    if (queryStringItems.length == 2) {
                        switch (queryStringItems[0]) {
                            case "page":
                                $('.configPageNumber')[0].value = queryStringItems[1];
                                break;
                            case "ippage":
                                $('.configItemsPerPage')[0].value = queryStringItems[1];
                                break;
                            case "sortp":
                                $('.configSortExpression')[0].value = queryStringItems[1];
                                break;
                            case "term":
                                $('.configSearchTerm')[0].value = queryStringItems[1];
                                break;
                            case "refine":
                                $('.configRefinementsSelected')[0].value = queryStringItems[1];
                                break;
                        }
                    }
                }

                if (RefreshRefinements()) {
                    // Ensure existing refinements are cleared
                    $('#refinement-standard span.refinement-option input').removeAttr('checked');

                    // Select the active refinements
                    var selected = $('.configRefinementsSelected')[0].value.split('!');
                    for (counter = 0; counter < selected.length; counter++) {
                        // Check the relevant checkboxes.
                        $('#refinement-standard span.refinement-option[refinement="' + selected[counter] + '"]').find('input').attr('checked', true);
                    }
                    RefreshProductsAndRefinements();
                }
                else {
                    RefreshProducts();
                }
            }
            else if (typeof $('.configPageNumber')[0] != 'undefined') {
                if ($('.configPageNumber')[0].value != "1") {
                    ResetPageNumber();
                    RefreshProducts();
                }
            }
        });
    }
});

function ClearStandardRefinementDiv() {
    $('#refinement-standard').html('');
}

// The function called when a refinement drop-down value is selected.
function RefinementDropDownSelect(dropDownId) {
    // Identify the refinement selected.
    var dropDown = document.getElementById(dropDownId);
    var refinement = $(dropDown).val();
    // Add the selected refinement.
    var current = $('.configRefinementsSelected')[0].value;
    if (current.length > 1) current = current.concat("!");
    current = current.concat(refinement);
    $('.configRefinementsSelected')[0].value = current;
    ResetPageNumber();
    SetPagingPoint();
}

function RefinementSliderSelect(refinementName, refinementRange) {
    // When using the slider only one range can be selected for that refinement.
    // So remove any current refinements that match the refinement name.
    RemoveRefinement(refinementName)
    // Add the new refinement.
    var refinement = refinementName + "|" + refinementRange
    var current = $('.configRefinementsSelected')[0].value;
    if (current.length > 1) current = current.concat("!");
    current = current.concat(refinement);
    $('.configRefinementsSelected')[0].value = current;
    ResetPageNumber();
    SetPagingPoint();
}

function RefinementCheckBoxSelect(chkId) {
    var chk = document.getElementById(chkId);
    var chkSelected = $(chk).is(':checked');
    var chkOrderValue = parseInt($(chk).closest('li').attr('orderValue'));
    var current = $('.configRefinementsSelected')[0].value;
    var refinement = $(chk).parent().attr('refinement');
    var refinementName = $(chk).closest('div').attr('refinementname');
    if (chkSelected) {
        // Add the refinement
        if (current.length > 1) current = current.concat("!");
        current = current.concat(refinement);
    }
    else {
        // Remove the refinement optoin
        current = current.replace(refinement + "!", "");
        current = current.replace("!" + refinement, "");
        current = current.replace(refinement, "");
    }
    $('.configRefinementsSelected')[0].value = current;
    ResetPageNumber();
    SetPagingPoint();

    // Handle And refinements
    // 1. Select refinement group div
    // 2. if div has refinement type of "AND"
    // 3.       Get list of refinement items
    // 4.       Clear current list in UL control
    // 5.       Select 'selected' items and insert
    // 6.       Insert  'And Also...'
    // 7.       Select 'unselected' items and insert
    // 8.       Apply hooks for the click events
    // 9. END if

    var group = $(chk).closest('div.refinement-group');
    if (group.attr('refinementType') == "AND") {

        if (chkSelected) {
            // Set the parent to showtop
            $(chk).closest('li').attr("showTop", true);
        }
        else {
            // remove the option to showtop
            $(chk).closest('li').removeAttr("showTop");
        }

        var newItems = "";
        var counter = 0;

        var ul = $(group).find('ul.option');
        // Get the ul items
        var ulItems = $(ul).find('li').not('li[litype="alsoFlag"]');

        var selectedItems = false;
        var inserted = false;
        var moreClass = "";

        // insert the selected
        $(ul).find('li[showTop="true"]').not('li[orderValue="' + chkOrderValue + '"]').each(function(i, item) {
            // Set the selected items flag to true - this is checked later to insert
            // the 'and also' flag
            selectedItems = true;
            if (chkSelected && !inserted && chkOrderValue < parseInt($(item).attr('orderValue'))) {
                inserted = true;
                counter++;
                if (counter >= 5) moreClass = ' class="more" ';
                newItems = newItems.concat('<li orderValue="' + chkOrderValue + '" showTop="true" refinement="' + refinementName + '" ' + moreClass + ' >' + $(chk).closest('li').html() + '</li>');
            }
            counter++;
            if (counter >= 5) moreClass = ' class="more" ';
            newItems = newItems.concat('<li orderValue="' + $(item).attr('orderValue') + '" showTop="true" refinement="' + refinementName + '" ' + moreClass + ' >' + $(item).html() + '</li>');
        });

        // Add in the selected item if it appears at the bottom of the list
        if (chkSelected && !inserted) {
            selectedItems = true;
            inserted = true;
            counter++;
            if (counter >= 5) moreClass = ' class="more" ';
            newItems = newItems.concat('<li orderValue="' + chkOrderValue + '" showTop="true" refinement="' + refinementName + '" ' + moreClass + ' >' + $(chk).closest('li').html() + '</li>');
        }

        // If selected items inserted then add the 'and also item'
        if (selectedItems && ($(ulItems).length > $(newItems).length)) {
            newItems = newItems.concat('<li litype="alsoFlag">And also</li>');
        }

        // insert the selected
        $(ul).find('li').not('li[showTop="true"]').not('li[litype="alsoFlag"]').not('li[orderValue="' + chkOrderValue + '"]').each(function(i, item) {

            if (!chkSelected && !inserted && chkOrderValue < parseInt($(item).attr('orderValue'))) {
                inserted = true;
                counter++;
                if (counter >= 5) moreClass = ' class="more" ';
                newItems = newItems.concat('<li orderValue="' + chkOrderValue + '" refinement="' + refinementName + '" ' + moreClass + ' >' + $(chk).closest('li').html() + '</li>');
            }
            if ($(item).attr('orderValue') != undefined) {
                counter++;
                if (counter >= 5) moreClass = ' class="more" ';
                newItems = newItems.concat('<li orderValue="' + $(item).attr('orderValue') + '" refinement="' + refinementName + '" ' + moreClass + ' >' + $(item).html() + '</li>');
            }
        });

        if (!chkSelected && !inserted) {
            inserted = true;
            counter++;
            if (counter >= 5) moreClass = ' class="more" ';
            newItems = newItems.concat('<li orderValue="' + chkOrderValue + '" refinement="' + refinementName + '" ' + moreClass + ' >' + $(chk).closest('li').html() + '</li>');
        }

        ul.html($(newItems));

        // Hook in the click event for the new items
        $(ul).find('span.refinement-option input').click(function(event) {
            RefinementCheckBoxSelect($(this)[0].id);
        });

        $(ul).find('li.more').hide();

        // Select the new item if selected
        $(ul).find('li[showTop="true"] input').attr('checked', true);
        $(ul).find('li[orderValue="' + chkOrderValue + '"] input').attr('checked', chkSelected);
    }

    // Set the clear refinements link property
    if (chkSelected | $('#refinement-standard span.refinement-option input[checked]').length > 0) {
        SetupClearRefinements(true);
    }
    else {
        SetupClearRefinements(false);
    }
}

function SetPageNumber(newValue) {
    $('.configPageNumber')[0].value = newValue;
}

function ResetPageNumber() {
    SetPageNumber(1);
}

function SetPagingPoint() {
    // Method to set a paging point in the browser so that the user can navigate back using the 
    // back button.
    var pagingPoint = "";

    pagingPoint = pagingPoint.concat("page=", $('.configPageNumber')[0].value);
    pagingPoint = pagingPoint.concat("&ippage=", $('.configItemsPerPage')[0].value);
    pagingPoint = pagingPoint.concat("&term=", $('.configSearchTerm')[0].value);
    pagingPoint = pagingPoint.concat("&sortp=", $('.configSortExpression')[0].value);
    if ($('.configRefinementsSelected')[0].value.length > 0) {
        pagingPoint = pagingPoint.concat("&refine=", encodeURIComponent($('.configRefinementsSelected')[0].value));
    }
    $.address.value(pagingPoint);
}

function RefreshProducts() {
    document.body.style.cursor = 'wait';
    var configurationXml = GeneratePageListingXml();
    $.ajax({
        type: "POST",
        url: "/SiteWebServices/Products.asmx/GetProductList",
        data: "configurationXml=" + configurationXml,
        cache: false,
        async: false,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "xml",
        success: function(msg) {
            var mytext;
            if (msg.text !== undefined)
                mytext = msg.text;  //for IE
            else
                mytext = $(msg).text();

            mytext = unescape(mytext);
            $('#product-list').html(mytext);
            ApplyProductListMethods();
            document.body.style.cursor = 'default';
            SetRefreshRefinements(true);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            document.body.style.cursor = 'default';
            SetRefreshRefinements(true);
            //AjaxError(xhr, ajaxOptions);
        }
    });
}

function RefreshProductsAndRefinements() {
    document.body.style.cursor = 'wait';
    var configurationXml = GeneratePageListingXml();
    $.ajax({
        type: "POST",
        url: "/SiteWebServices/Products.asmx/GetProductListAndRefinements",
        data: "configurationXml=" + configurationXml,
        cache: false,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "xml",
        async: false,
        success: function (msg) {

            var xmlText;
            var refinement;

            if (msg.text !== undefined)
                xmlText = msg.text;  //for IE
            else
                xmlText = $(msg).text();

            var productCount, refinementCount;
            var start, end;

            // Get the product count
            start = xmlText.indexOf("<productCount>") + 14;
            end = xmlText.indexOf("</productCount>");
            var productCount = xmlText.substring(start, end);

            // Get the product count
            start = xmlText.indexOf("<totalItems>") + 12;
            end = xmlText.indexOf("</totalItems>");
            var totalItems = xmlText.substring(start, end);

            var ippage = $('.configItemsPerPage')[0].value;

            //Update the paging controls
            // (get the page number from the config incase the user
            // is refreshing the page but might already be on a page > 1...)
            var config = $('.configPageNumber')[0];
            if (config != null && config != 'undefined' && config != '') {
                var pageno = $('.configPageNumber')[0].value;
                if (pageno != null && pageno != 'undefined' && pageno != '') {
                    RefreshingPagingControl(totalItems, ippage, pageno);
                }
                else {
                    RefreshingPagingControl(totalItems, ippage, 1);
                }
            }

            // Get the refinement count
            start = xmlText.indexOf("<refinementCount>") + 17;
            end = xmlText.indexOf("</refinementCount>");
            var refinementCount = xmlText.substring(start, end);

            // Get the product list
            start = xmlText.indexOf("<productList>") + 13;
            end = xmlText.indexOf("</productList>");
            $('#product-list').html(xmlText.substring(start, end));

            // Get the category refinements
            start = xmlText.indexOf("<refinementCategory>") + 20;
            end = xmlText.indexOf("</refinementCategory>");
            $('#refinement-category').html(xmlText.substring(start, end));

            // Get the best sellers and the recommended products.
            if ($('.configPageNumber')[0].value == "1") {
                start = xmlText.indexOf("<bestSellers>") + 13;
                end = xmlText.indexOf("</bestSellers>");
                $('div.most-wanted').html(xmlText.substring(start, end));
                start = xmlText.indexOf("<recommendedProducts>") + 21;
                end = xmlText.indexOf("</recommendedProducts>");
                $('div#hero-product').html(xmlText.substring(start, end));
                ApplyMerchandisingZoneMethods();
            }

            // Deselect the previously common refinements
            $('#refinement-standard span.refinement-option input[common]').removeAttr('checked');
            // Remove the disabled option for common refinements
            $('#refinement-standard span.refinement-option input[common]').removeAttr('disabled');
            // Remove the common property - this will be reapplied if stil valid
            $('#refinement-standard span.refinement-option input[common]').removeAttr('common');

            $('#refinement-standard .refinement-group').each(function (i) {
                if ($(this).find('span.refinement-option input[checked]').length == 0) {
                    $(this).find('span.refinement-option input').attr('disabled', true);
                }
                else {
                    $(this).find('span.refinement-option input').removeAttr('disabled');
                }
            });

            // Get the available refinements
            start = xmlText.indexOf("<refinementAvailable>") + 21;
            end = xmlText.indexOf("</refinementAvailable>");
            var refinementAttr;

            if (xmlText.substring(start, end).length > 0) {
                var refinementAvailable = xmlText.substring(start, end).split("!");
                for (counter = 0; counter < refinementAvailable.length; counter++) {
                    DisplayRefinementCheckBox(refinementAvailable[counter]);
                }
            }

            // Refresh the html for the refinement drop downs
            start = xmlText.indexOf("<dropDownOptions>") + 17;
            end = xmlText.indexOf("</dropDownOptions>");
            var dropDownOptionsHtml = xmlText.substring(start, end);
            if (dropDownOptionsHtml.length > 0) {
                $('#refinement-dropdown').html(dropDownOptionsHtml);
            }
            ApplyDropDownListMethods();

            // Get the common refinements - these will not be enabled but will be ticked
            start = xmlText.indexOf("<refinementCommon>") + 18;
            end = xmlText.indexOf("</refinementCommon>");

            if (xmlText.substring(start, end).length > 0) {
                var refinementCommon = xmlText.substring(start, end).split("!");
                for (counter = 0; counter < refinementCommon.length; counter++) {
                    refinementAttr = refinementCommon[counter].split("|");

                    if (refinementAttr[0] != 'Price') {
                        var refinementIdent = refinementAttr[0] + '|' + refinementAttr[1];
                        EnsureRefinementExists(refinementAttr[0], refinementAttr[1], refinementAttr[2], refinementAttr[3]);

                        if (refinementAttr[0] != 'Price') {
                            $('#refinement-standard span[refinement="' + refinementIdent + '"] input').attr('checked', true);
                            $('#refinement-standard span[refinement="' + refinementIdent + '"] input').attr('disabled', true);
                            $('#refinement-standard span[refinement="' + refinementIdent + '"] input').attr('common', true);
                        }
                    }
                    else {
                        // Price range refinement
                        var priceValues = refinementAttr[1].split('~');
                        if (priceValues.length == 2) {

                            $('div.refinement-group[refinementname="Price"] li').each(function (index, item) {
                                if (!$(item).find('input').is(':checked')) {
                                    if (parseInt(priceValues[0]) >= parseInt($(item).attr('valuelower'))
                                        &&
                                        parseInt(priceValues[1]) <= parseInt($(item).attr('valuehigher'))) {
                                        $(item).find('input').attr('checked', true);
                                        $(item).find('input').attr('disabled', true);
                                        $(item).find('input').attr('common', true);
                                    }
                                }
                            });
                        }
                    }
                }
            }

            // Set the visibility of the results containers if present
            if ($('.resultsContainer').length == 1 && $('.resultsBlankContainer').length == 1) {
                if (productCount != "0") {
                    $('.resultsContainer').show();
                    $('.resultsBlankContainer').hide();
                }
                else {
                    $('.resultsBlankContainer').show();
                    $('.resultsContainer').hide();
                }
            }

            // Set the visibility of the refinements container if present
            if ($('.refinements-container').length == 1) {
                if (refinementCount != "0") {
                    $('.refinements-container').show();
                }
                else {
                    $('.refinements-container').hide();
                }
            }

            ApplyProductListMethods();
            document.body.style.cursor = 'default';

        },
        error: function (xhr, ajaxOptions, thrownError) {
            document.body.style.cursor = 'default';
            AjaxError(xhr, ajaxOptions);
        }
    });
}

function EnsureRefinementExists(groupName, refinementValue, groupOrder, refinementOrder) {

    if (groupName == "" || refinementValue == "") return;

    var inserted = false;

    // Check if the refinement is present
    if ($('#refinement-standard span[refinement="' + groupName + '|' + refinementValue + '"] input').length == 1) {
        // Refinement group and value present
        return;
    }
    else {
        // Construct the refinement link
        var displayValue = "";
        var values = refinementValue.split('~');

        if (values.length == 1) {
            // Single valued attribute - just use the value
            displayValue = refinementValue;
        }
        else {
            // Multi valued attribute - treat as price
            displayValue = "£" + values[0] + " to £" + values[1];
        }

        var toInsert = '<li orderValue="' + refinementOrder + '">' +
                            '<a class="refinement-option" title="' + displayValue.toString() + '" >' +
                                '<span class="refinement-option" refinement="' + groupName + '|' + refinementValue + '" >' +
                                    '<input type="checkbox" >' +
                                    '<label>' + displayValue.toString() + '</label>' +
                                '</span>' +
                            '</a>' +
                       '</li>';

        if ($('div.refinement-group[refinementName="' + groupName + '"]').length == 1) {

            // Refinement group present, but refinement value missing            
            $('div.refinement-group[refinementName="' + groupName + '"] ul.option').find('li').not('li[showTop="true"]').each(function(i, item) {

                if (!inserted && refinementOrder < parseInt($(item).attr('orderValue'))) {
                    inserted = true;
                    // New item to appear before the current item
                    $(item).before(toInsert);
                }
            });

            if (!inserted) {
                // New item to appear after the last item
                $('div.refinement-group[refinementName="' + groupName + '"] ul.option li:last').after(toInsert);
            }

        }
        else {

            toInsert = '<div class="refinement-group" refinementName="' + groupName + '" >' +
                            '<h4>' + groupName + '</h4>' +
                            '<ul class="option">' +
                                toInsert +
                            '</ul>' +
                       '</div>';

            // Refinement group and value missing
            $('#refinement-standard div.refinement-group').each(function(i, item) {
                if (!inserted && groupOrder < parseInt($(item).attr('orderValue'))) {
                    inserted = true;
                    // New item to appear before the current item
                    $(item).before(toInsert);
                }
            });

            if (!inserted) {
                if ($('#refinement-standard div.refinement-group').length == 0) {
                    // New item to appear as first item
                    $('#refinement-standard').html(toInsert);
                }
                else {
                    // New item to appear after the last item
                    $('#refinement-standard div.refinement-group:last').after(toInsert);
                }
            }
        }

        // Apply the click event to the input item
        $('#refinement-standard span.refinement-option[refinement="' + groupName + '|' + refinementValue + '"] input').click(function(event) {
            $('#refinements-container').block({ fadeIn: 0, timeout: 0, message: '<h5>Please wait...</h5>' });
            SetRefreshRefinements(true);
            setTimeout("RefinementCheckBoxSelect('" + $(this)[0].id + "'); ", 1);
            $('#refinements-container').unblock();
            event.stopPropagation();
        });
    }

    return;
}

function SetupClearRefinements(enabled) {
    // Enable/Disable the clear refinements link
    if ($('div.refinements-clear').length == 1) {
        if (!enabled) {
            // Disable
            $('div.refinements-clear').hide();
        }
        else {
            // Enable
            $('div.refinements-clear').show();
        }
    }
}

function AjaxError(xhr, info) {
    alert("There was a problem processing this request.");
}

function EncodeConfigValue(input) {
    return input.replace(/</g, '&lt;'
            ).replace(/>/g, '&gt;'
            ).replace(/£/g, '&#163;'
            ).replace(/&/g, '%26'
            ).replace(/&nbsp;/g, '&#160;'
            ).replace(/'/g, '&apos;');
}

function GeneratePageListingXml() {
    var xml = "<config>";

    // Page Options
    xml = xml.concat("<pageOptions>");
    xml = xml.concat("<pageNumber>" + $('.configPageNumber')[0].value + "</pageNumber>");
    xml = xml.concat("<itemsPerPage>" + $('.configItemsPerPage')[0].value + "</itemsPerPage>");
    var searchTerm = $('.configSearchTerm')[0].value;
    searchTerm = searchTerm.replace('"', ' ');
    searchTerm = searchTerm.replace("'", " ");
    xml = xml.concat("<searchTerm>" + EncodeConfigValue(searchTerm) + "</searchTerm>");
    xml = xml.concat("<baseUrl>" + EncodeConfigValue($('.configBaseUrl')[0].value.replace('?', '%3F')) + "</baseUrl>");
    xml = xml.concat("<sortExpression>" + EncodeConfigValue($('.configSortExpression')[0].value) + "</sortExpression>");
    xml = xml.concat("<categoryId>" + $('.configCategoryId')[0].value + "</categoryId>");
    xml = xml.concat("<sourceType>" + $('.configSourceType')[0].value + "</sourceType>");
    xml = xml.concat("<highLevelCategoryPage>" + $('.configHighLevelCategoryPage')[0].value + "</highLevelCategoryPage>");
    xml = xml.concat("<maxItems>" + $('.configMaxItems')[0].value + "</maxItems>");
    xml = xml.concat("<HideDesignerRefinement>" + $('.configHideDesignerRefinement')[0].value + "</HideDesignerRefinement>");
    xml = xml.concat("</pageOptions>");

    // String Formats
    xml = xml.concat("<stringFormats>");
    xml = xml.concat("<vatPriceCaption>" + $('.configVatPriceCaption')[0].value + "</vatPriceCaption>");
    xml = xml.concat("<sortByListSource>" + EncodeConfigValue($('.configSortByListSource')[0].value) + "</sortByListSource>");
    xml = xml.concat("</stringFormats>");

    // Refinement AND/OR Options
    xml = xml.concat("<refinements>");

    if ($('.configSourceType')[0].value == "") {
        xml = xml.concat("<option type='and' value='" + EncodeConfigValue($('.configRefimementsAnd')[0].value) + "' />");
        xml = xml.concat("<option type='selected' value='" + encodeURIComponent(EncodeConfigValue($('.configRefinementsSelected')[0].value)) + "' />");
        xml = xml.concat("<option type='ignore' value='" + EncodeConfigValue($('.configRefinementsIgnore')[0].value) + "' />");
    }
    xml = xml.concat("</refinements>");

    xml = xml.concat("</config>");

    return xml;
}

function SetRefreshRefinements(refreshRefinements) {
    if (refreshRefinements) {
        $('.configRefreshRefinements')[0].value = "1";
    }
    else {
        $('.configRefreshRefinements')[0].value = "0";
    }
}

function RefreshRefinements() {
    return $('.configRefreshRefinements')[0].value == "1";
}

function BlockResultsContainer($element, block, ensureVisible) {

    var problemBrowser = $.browser.msie && $.browser.version <= 6;

    if (ensureVisible && $(window).scrollTop() > 300) {
        $('html, body').animate({ scrollTop: 300 }, 0);
    }

    if (!problemBrowser) {
        if (block) {
            var options = {
                centerY: 0,
                fadeIn: 0,
                timeout: 0,
                message: '<h5 class="loading-original"></h5>',
                css: { top: '125px', width: '60px', height: '33px' }
            };
            $element.block(options);
        }
        else {
            $element.unblock();
        }
    }
    
    
    /*
    if (block) {
        var options = {
            centerY: 0,
            fadeIn: 0,
            timeout: 0,
            message: '<h5 class="loading-original"></h5>',
            css: { top: '0px', left:'0px', width: '725px', height: '1200px' }
        };
        $element.block(options);
    }
    else {
        $element.unblock();
    }
    */
}

function HtmlEncode(text) {
    return $('<div/>').text(text).html(); 
};

function HtmlDecode(text) {
    return $('<div/>').html(text).text();
};

function ApplyProductListMethods() {

    

    //TEMP FIX: IE7 button position thrown out from blocking (TFS 5223)
    var problemBrowser = $.browser.msie && $.browser.version <= 7;
    var $resultsContainer = $('#product-list-wrapper');

    $('.listing-page-no').click(function () {
        //Proceed only if the button is enabled or a URL exist
        if ($(this)[0].href != '') {
            if (!problemBrowser) BlockResultsContainer($resultsContainer, true, true);
            SetRefreshRefinements(false);
            SetPageNumber($(this).attr('pageno'));
            RefreshingPagingControl($(this).attr('totalitems'), $('.configItemsPerPage')[0].value, $(this).attr('pageno'));
            setTimeout("SetPagingPoint();", 1);
            if (!problemBrowser) BlockResultsContainer($resultsContainer, false);
        }

        return false;
    });

    $('select.page-listing-ippage').change(function() {
        if (!problemBrowser) BlockResultsContainer($resultsContainer, true, true);
        SetRefreshRefinements(false);
        ResetPageNumber();
        $('.configItemsPerPage')[0].value = $(this).val();
        setTimeout("SetPagingPoint();", 1);
        if (!problemBrowser) BlockResultsContainer($resultsContainer, false);

        return false;
    });

    $('select.page-listing-sorting').change(function() {
        if (!problemBrowser) BlockResultsContainer($resultsContainer, true, true);
        SetRefreshRefinements(false);
        ResetPageNumber();
        $('.configSortExpression')[0].value = $(this).val();
        setTimeout("SetPagingPoint();", 1);
        if (!problemBrowser) BlockResultsContainer($resultsContainer, false);

        return false;
    });

    // display the JS enabled addtobasket button
    $('.JavaEnabledButton').attr('style', 'display:block');

    // handle addtogiftlist click
    $("[id$='AddToGiftListLink']").click(function () {        
        // hide any open addtobasket overlays
        $(".list-tool-tip-wrap").hide();
        $("[id$='appendedOverlay']").remove();

        var category_id = '';
        if ($('#product-cat') != null && $('#product-cat') != 'undefined') {
            category_id = $('#product-cat').val();
        }
        var q = "1";
        var self = $(this);
        var prodid = $(this).attr('productid');
        var variant_id = $(this).attr('variantid');
        if (variant_id == null || variant_id == 'undefined') {
            variant_id = '';
        }

        // handle the return from web service call for add to giftlist in handler
        var fn = function (data, status) {

            // get the button parent container for positioning of info overlays
            var sectionPos = self.parent();
            var additionalLeft = 130;
            var additionalTop = 60;
            if (sectionPos.attr('class') != "btns-wish-buy") {
                sectionPos = sectionPos.parent();
                additionalTop = 0;
            }

            if (status === 'success') {
                var j = eval('(' + data + ')');

                // not found - redirect to product detail page...
                if (j.UrlRedirect != null && j.UrlRedirect != 'undefined' && j.UrlRedirect != '') {
                    window.location = j.UrlRedirect;
                }

                if (typeof j.products != 'undefined' && j.products.length != 0) {
                    // added ok - show the overlay
                    var popup = $("[id='addtogiftlistOverlay']");
                    self.closest('ul').after('<div id="appendedOverlay" class="list-tool-tip-wrap giftlist-info">' + popup.html() + '</div>');
                    $("[id$='appendedOverlay']").fadeIn();
                }
                return false;  // ensure postback not done
            }

            // not added - postback instead
            return true;
        };


        if (prodid != null && prodid != 'undefined' && prodid != '') {
            // web service call to add to wishlist
            var o = $.extend({ command: 'AddToGiftList', ajax: true, pid: prodid, vid: variant_id, cid: category_id }, { qty: q });
            var h = $.ajax({ url: '/handler.aspx', data: o, success: fn, error: fn, dataType: 'text', cache: false });
            return false;
        }
        else {
            // cannot add - postback instead
            return true;
        }
        return false;

    });

    // handle addtowishlist click
    $("[id$='AddToWishListLink']").click(function () {

        // hide any open addtobasket overlays
        $(".list-tool-tip-wrap").hide();
        $("[id$='appendedOverlay']").remove();

        var category_id = '';
        if ($('#product-cat') != null && $('#product-cat') != 'undefined') {
            category_id = $('#product-cat').val();
        }
        var q = "1";
        var self = $(this);
        var prodid = $(this).attr('productid');
        var variant_id = $(this).attr('variantid');
        if (variant_id == null || variant_id == 'undefined') {
            variant_id = '';
        }

        // handle the return from web service call for add to wishlist in handler
        var fn = function (data, status) {

            // get the button parent container for positioning of info overlays
            var sectionPos = self.parent();
            var additionalLeft = 130;
            var additionalTop = 60;
            if (sectionPos.attr('class') != "btns-wish-buy") {
                sectionPos = sectionPos.parent();
                additionalTop = 0;
            }

            if (status === 'success') {
                var j = eval('(' + data + ')');

                if (typeof j.products != 'undefined' && j.products.length != 0) {
                    // added ok - show the overlay
                    var popup = $("[id='addtowishlistOverlay']");
                    self.closest('ul').after('<div id="appendedOverlay" class="list-tool-tip-wrap wishlist-info">' + popup.html() + '</div>');
                    $("[id$='appendedOverlay']").fadeIn();
                }
                return false;  // ensure postback not done
            }

            // not added - postback instead
            return true;
        };


        if (prodid != null && prodid != 'undefined' && prodid != '') {
            // web service call to add to wishlist
            var o = $.extend({ command: 'AddToWishList', ajax: true, pid: prodid, vid: variant_id, cid: category_id }, { qty: q });
            var h = $.ajax({ url: '/handler.aspx', data: o, success: fn, error: fn, dataType: 'text', cache: false });
            return false;
        }
        else {
            // cannot add - postback instead
            return true;
        }
        return false;

    });

    // handle addtobasket button click
    $('.addtobasket').click(function () {

        // hide any open addtobasket overlays
        $(".list-tool-tip-wrap").hide();
        $("[id$='appendedOverlay']").remove();

        var category_id = '';
        if ($('#product-cat') != null && $('#product-cat') != 'undefined') {
            category_id = $('#product-cat').val();
        }
        var q = "1";

        var self = $(this);

        // giftlist page checks on qty to add...
        var isgiftlist = false;
        var purchased = self.parent().parent().find("[id$='purchasedTotal']");
        var remaining = self.parent().parent().find("[id$='hdnRemaining']");
        if (remaining != null && remaining != 'undefined' && remaining != '' && remaining.val() == '0') {
            return false;
        }
        // for giftlist page - check qty already purchased before continuing...
        var Tick = self.parent().parent().find("[id$='Tick']");
        if (Tick != null && Tick != 'undefined' && Tick != '' && Tick.html() != null && Tick.html() != 'undefined' && Tick.html() != '') {
            return false;
        }
        var qtyBox = null;
        var qtyPurchased = "0";
        if (purchased != null && purchased != 'undefined' && purchased != '' && purchased.text() != null && purchased.text() != 'undefined' && purchased.text() != '' && $.trim(purchased.text()) != '') {
            // giftlist edit page check...
            isgiftlist = true;
            qtyPurchased = $.trim(purchased.text());
            var qty1 = parseInt(qtyPurchased);
            var qty2 = parseInt(remaining.val());
            if (qty1 > qty2) {
                return false;
            }
        }
        else {  // public giftlist page qty check...
            qtyBox = self.parent().parent().find("[id$='InputQty']");
            if (qtyBox != null && qtyBox != 'undefined' && qtyBox != '' && qtyBox.val() != null && qtyBox.val() != 'undefined' && qtyBox.val() != '') {
                q = parseInt(qtyBox.val());
            }
        }

        var wishlistid = $("[id$='hdnWishlistId']");

        var prodid = $(this).attr('productid');
        var variant_id = $(this).attr('variantid');
        if (variant_id == null || variant_id == 'undefined') {
            variant_id = '';
        }

        // handle the return from web service call for add to basket in handler
        var fn = function (data, status) {

            // overlay positioning for giftlist pages - nned to inject the html
            var additionalLeft = 0;
            var additionalTop = 60;
            var giftPage = $("#giftlist-page");
            var sectionPos = null;
            if (giftPage != null && giftPage != 'undefined' && giftPage != '' && giftPage.attr('id') == 'giftlist-page') {
                sectionPos = self;
                additionalLeft = 100;
                additionalTop = 60;
            }
            var giftPage = $("#giftlist-user-page");
            if (giftPage != null && giftPage != 'undefined' && giftPage != '' && giftPage.attr('id') == 'giftlist-user-page') {
                sectionPos = self;
                additionalLeft = 100;
                additionalTop = 60;
            }

            if (status === 'success') {
                var j = eval('(' + data + ')');

                // see if a product was found to add
                if (j.ProductNotFound != null && j.ProductNotFound != 'undefined' && j.ProductNotFound == "true") {
                    // not found - redirect to product detail page...
                    if (j.UrlRedirect != null && j.UrlRedirect != 'undefined' && j.UrlRedirect != '') {
                        window.location = j.UrlRedirect;
                    }
                    return;
                }

                // get the cid and vid passed back
                if (typeof j.products != 'undefined' && j.products.length != 0) {
                    if (category_id == null || category_id == 'undefined' || category_id == '') {
                        category_id = j.products[0].cid;
                    }
                    variant_id = j.products[0].vid;
                }

                if (typeof j.products != 'undefined' && j.products.length != 0) {
                    msg = (j.products[0].addToBasket ? 'Added' : (j.products[0].reason || 'unknown error'));

                    // added to basket ok - rebuild minibasket and update omniture
                    if (j.products[0].addToBasket == true) {

                        // show added to basket overlay
                        var popup = $("[id='addtobasketOverlay']");
                        if (sectionPos != null) {
                            popup.fadeIn();
                            // correctly position the overlay
                            popup.css('top', sectionPos.offset().top - popup.height() + 20 - additionalTop);
                            popup.css('left', sectionPos.offset().left - popup.width() - additionalLeft);
                        }
                        else {
                            self.closest('ul').after('<div id="appendedOverlay" class="list-tool-tip-wrap basket-info">' + popup.html() + '</div>');
                            $("[id$='appendedOverlay']").fadeIn();
                        }

                        if (j.products[0].minibaskethtml != null && j.products[0].minibaskethtml != 'undefined' && j.products[0].minibaskethtml != '') {
                            $("#mini-basket-main").html(HtmlDecode(j.products[0].minibaskethtml));
                        }
                        var arrow = $('a.basket-nav-summary-link');
                        arrow.attr('title', arrow.attr('tooltipExpand'));

                        if (typeof Omniture != 'undefined') {
                            if (variant_id != null && variant_id != '') {
                                Omniture.SubmitAddToBasketSingle(prodid, variant_id, category_id, q, bcnt);
                            }
                            else {
                                Omniture.SubmitAddToBasketSingle(prodid, prodid, category_id, q, bcnt);
                            }
                        }

                        // show the checkout link in the summary header
                        $('#basket-nav-checkout-li').html($('#hidden-basket-nav-checkout-li').html());
                        $('#basket-nav-basket-li').attr('class', '');
                        //update the basket summary in header
                        var basketTitle = $('.hdnBasketTitleCaption').val();
                        // strip out items and total
                        var itemsText = "";
                        var totalText = "";
                        if (j !== null && j.message != null && j.message != '' && j.message != 'undefined') {
                            var splitIndex = j.message.indexOf(",");
                            if (splitIndex > 0) {
                                itemsText = j.message.substring(0, splitIndex);
                            }
                            else {
                                itemsText = j.message;
                            }
                            totalText = HtmlDecode(j.total);
                        }
                        $('a#basket-nav-summary').html('<span>' + basketTitle + '</span> ' + itemsText);
                        var totalSection = $('[id$="basket-nav-summary2"]');
                        if (totalSection != null && totalSection != 'undefined' && totalSection != '' && totalSection.html() != null && totalSection.html() != 'undefined' && totalSection.html() != '') {
                            $('[id$="basket-nav-summary2"]').html(totalText);
                        }
                        else {
                            $('[id$="basket-nav-summary2"]').html(totalText);
                        }


                        rebindBasketNavClicks();

                        // on giftlist page - update remaining amount
                        if (qtyBox != null) {
                            if (remaining != null && remaining != 'undefined' && remaining != '') {
                                remaining.val(parseInt(remaining.val()) - q);
                                if (remaining.val() == 0) {
                                    // all bought - disable add
                                    self.attr('style', 'display:none;');
                                    // hide qty up/down
                                    var qtyUp = self.parent().parent().find("[id$='qtyUp']");
                                    var qtyDown = self.parent().parent().find("[id$='qtyDown']");
                                    if (qtyUp != null && qtyUp != 'undefined' && qtyUp != '') {
                                        qtyUp.attr('style', 'display:none;');
                                    }
                                    if (qtyDown != null && qtyDown != 'undefined' && qtyDown != '') {
                                        qtyDown.attr('style', 'display:none;');
                                    }
                                    // hide qty
                                    if (qtyBox != null && qtyBox != 'undefined' && qtyBox != '') {
                                        qtyBox.attr('style', 'display:none;');
                                    }
                                    // show tick image
                                    var tick = self.parent().parent().find("[id$='Tick']");
                                    if (tick != null && tick != 'undefined' && tick != '') {
                                        tick.attr('style', 'display:block;');
                                    }

                                }
                                else if (remaining.val() == 1) {
                                    // hide qty up/down
                                    var qtyUp = self.parent().parent().find("[id$='qtyUp']");
                                    var qtyDown = self.parent().parent().find("[id$='qtyDown']");
                                    if (qtyUp != null && qtyUp != 'undefined' && qtyUp != '') {
                                        qtyUp.attr('style', 'display:none;');
                                    }
                                    if (qtyDown != null && qtyDown != 'undefined' && qtyDown != '') {
                                        qtyDown.attr('style', 'display:none;');
                                    }
                                    // format qty box to be label
                                    if (qtyBox != null && qtyBox != 'undefined' && qtyBox != '') {
                                        var textboxbackcol = $("[id$='hdnTextBoxBackColor']");
                                        qtyBox.attr('style', 'border:0px;background-color:' + textboxbackcol.val());
                                        qtyBox.attr('disabled', 'disabled');
                                        qtyBox.val('1');
                                    }
                                }
                            }
                        }

                    }
                    else {
                        // display out of stock overlay
                        if (msg == "out of stock") {
                            var popup = $("[id='outofstockOverlay']");
                            if (sectionPos != null) {
                                popup.fadeIn();
                                // correctly position the overlay
                                popup.css('top', sectionPos.offset().top - popup.height() + 20 - additionalTop);
                                popup.css('left', sectionPos.offset().left - popup.width() - additionalLeft);
                            }
                            else {
                                self.closest('ul').after('<div id="appendedOverlay" class="list-tool-tip-wrap outof-stock-info">' + popup.html() + '</div>');
                                $("[id$='appendedOverlay']").fadeIn();
                            }
                        }
                        else if (msg == "insufficient stock") {
                            var popup = $("[id='insufficientstockOverlay']");
                            if (sectionPos != null) {
                                popup.fadeIn();
                                // correctly position the overlay
                                popup.css('top', sectionPos.offset().top - popup.height() - 15 - additionalTop);
                                popup.css('left', sectionPos.offset().left - popup.width() - additionalLeft);
                            }
                            else {
                                self.closest('ul').after('<div id="appendedOverlay" class="list-tool-tip-wrap insufficient-stock-info">' + popup.html() + '</div>');
                                $("[id$='appendedOverlay']").fadeIn();
                            }
                        }
                        else {
                            var popup = $("[id='stockerrorOverlay']");
                            if (sectionPos != null) {
                                popup.fadeIn();
                                // correctly position the overlay
                                popup.css('top', sectionPos.offset().top - popup.height() - 15 - additionalTop);
                                popup.css('left', sectionPos.offset().left - popup.width() - additionalLeft);
                            }
                            else {
                                self.closest('ul').after('<div id="appendedOverlay" class="list-tool-tip-wrap error-stock-info">' + popup.html() + '</div>');
                                $("[id$='appendedOverlay']").fadeIn();
                            }
                        }
                    }
                } else { // error
                    var popup = $("[id='stockerrorOverlay']");
                    if (sectionPos != null) {
                        popup.fadeIn();
                        // correctly position the overlay
                        popup.css('top', sectionPos.offset().top - popup.height() - 15 - additionalTop);
                        popup.css('left', sectionPos.offset().left - popup.width() - additionalLeft);
                    }
                    else {
                        self.closest('ul').after('<div id="appendedOverlay" class="list-tool-tip-wrap error-stock-info">' + popup.html() + '</div>');
                        $("[id$='appendedOverlay']").fadeIn();
                    }
                }
            }
            return false;  // ensure postback not done
        };

        var bcnt = $('#basket-count').val();
        if (bcnt == "True")
        { $('#basket-count').val('False'); }

        if (prodid != null && prodid != 'undefined' && prodid != '') {
            // web service call to add to basket
            var wishlist = '';
            if (wishlistid != null && wishlistid != 'undefined' && wishlistid != '' && wishlistid.val() != null && wishlistid.val() != 'undefined') {
                wishlist = wishlistid.val();
            }
            var o = $.extend({ command: 'AddToBasket', ajax: true, pid: prodid, vid: variant_id }, { qty: q }, { wishid: wishlist }, { giftlist: isgiftlist });
            var h = $.ajax({ url: '/handler.aspx', data: o, success: fn, error: fn, dataType: 'text', cache: false });
        }
        else {
            return false;
        }
        return false;
    });

    $(function() {
        //$.ui.dialog.defaults.frame = true;
        //$('#product-comparison').dialog({ modal: true, autoOpen: false, width: 540 });
        $('button.add-to-comparison').click(function() {
            var fn = function(results, status) {
                commerce.ui.new_comparison_list(results, status);
                $('#product-comparison').dialog('open');
            };
            // HACK: Workaround for IE6/7 non-standards compliance whereby
            //       the 'value' for the button is not honoured, but in fact
            //       returns the inner html instead.
            var t = null;
            if (typeof ActiveXObject !== 'undefined' && $(this).val() === $(this).html()) {
                //this.outerHTML = this.outerHTML;
                var n = this.getAttributeNode('value');
                if (!n) return true;
                t = n.value;
            }
            commerce.product.consider(t || $(this).val(), { success: fn, error: fn });
            return false;
        });
        $('#product-comparison .remove-all.button').click(function() {
            commerce.product.disregard(null, { success: commerce.ui.new_comparison_list });
            return false;
        });
    });
}

// Applies the relevant functions to the refinement drop-dwon lists.
function ApplyDropDownListMethods() {

    var problemBrowser = $.browser.msie && $.browser.version <= 7;
    var $resultsContainer = $('#product-list-wrapper');
    
    // Handle the refinement drop down select event
    $('#refinement-dropdown select.refinement-option').change(function(event) {
        if (!problemBrowser) BlockResultsContainer($resultsContainer, true, true);
        SetRefreshRefinements(true);
        setTimeout("RefinementDropDownSelect('" + $(this)[0].id + "'); ", 1);
        if (!problemBrowser) BlockResultsContainer($resultsContainer, false);
        event.stopPropagation();
    });

    // Remove the href attribute for the drop-down clear refinement links
    $('a.dropdown-refinements-clear').removeAttr('href');

    // Hide the buttons associated with the drop-down lists
    $('button.refinement-option-button').hide();

    // Handle the clearance of an individual drop-down refinement.
    $('a.dropdown-refinements-clear').click(function() {
        if (!problemBrowser) BlockResultsContainer($resultsContainer, true, true);
        ResetPageNumber();
        // Detect which refinement clear link has been selected.
        var refinementName = $(this).attr('refinementname');
        // Remove the relevant refinement.
        RemoveRefinement(refinementName);
        // Reset the paging.
        SetPagingPoint();
        if (!problemBrowser) BlockResultsContainer($resultsContainer, false);
        return false;
    });

    // Handle the dropdown style if in IE
    if ($.browser.msie) {
        if ($.ieSelectStyle != null) {
            $('.refinement-option').ieSelectStyle();
        }
    }
}

function ApplyMerchandisingZoneMethods() {
}

// Removes the proivded refinment from the list of selected refinements.
function RemoveRefinement(refinementName) {
    var current = $('.configRefinementsSelected')[0].value;
    var refinementStartPosition = current.indexOf(refinementName);
    if (refinementStartPosition > -1) {
        var existingRefinement = current.substring(refinementStartPosition);
        var refinementEndPosition = existingRefinement.indexOf("!");
        if (refinementEndPosition > -1) {
            existingRefinement = existingRefinement.substring(0, refinementEndPosition);
        }
        current = current.replace(existingRefinement + "!", "");
        current = current.replace("!" + existingRefinement, "");
        current = current.replace(existingRefinement, "");
        $('.configRefinementsSelected')[0].value = current;
    }
}

function DisplayRefinementCheckBox(refinement) {
    refinementAttr = refinement.split("|");
    if (refinementAttr[0] == 'Price') {
        // Price range refinement
        var priceValues = refinementAttr[1].split('~');
        if (priceValues.length == 2) {
            $('div.refinement-group[refinementname="Price"] li').each(function(index, item) {

                if ((
                        parseInt(priceValues[0]) >= parseInt($(item).attr('valuelower'))
                        &&
                        parseInt(priceValues[0]) <= parseInt($(item).attr('valuehigher'))
                    )
                    |
                    (
                        parseInt(priceValues[1]) >= parseInt($(item).attr('valuelower'))
                        &&
                        parseInt(priceValues[1]) <= parseInt($(item).attr('valuehigher'))
                    )) {
                    $(item).find('input').removeAttr('disabled');
                }
            });
        }
    }
    else {
        // Non-price refinement
        EnsureRefinementExists(refinementAttr[0], refinementAttr[1], refinementAttr[2], refinementAttr[3]);
        // Allow it to be selected
        $('#refinement-standard span[refinement="' + refinementAttr[0] + '|' + refinementAttr[1] + '"] input').removeAttr('disabled');
    }
}

function RefreshingPagingControl(totalItems, itemsPerPage, pageNo) {
    var data = "totalItemsCount=" + totalItems + "&itemsPerPage=" + itemsPerPage + "&pageNo=" + pageNo + "&term=" + $('.configSearchTerm')[0].value + "&baseurl=" + EncodeConfigValue($('.configBaseUrl')[0].value.replace('?', '%3F'));
    document.body.style.cursor = 'wait';
    $.ajax({
        type: "POST",
        url: "/SiteWebServices/Products.asmx/GetPagingControl",
        data: data,
        cache: false,
        async: false,
        success: function (msg) {

            // Replace the paging control contens

            if ($(msg)[0].text != undefined) {
                $('div.browse-controls').html($(msg)[0].text);
            }
            else {
                $('div.browse-controls').html($(msg).text());
            }            
        },
        error: function (xhr, ajaxOptions, thrownError) {
            document.body.style.cursor = 'default';
            AjaxError(xhr, ajaxOptions);
        }
    });    
    return false;
}

