﻿//
// product listing pages specific functions
//
$(document).ready(function () {

    // ie dropdown fix
    //if ($.browser.msie) {
    //    if ($.ieSelectStyle != null) {
    //        $('.refinement-option').ieSelectStyle();
    //    }
    //}

    var problemBrowser = $.browser.msie && $.browser.version <= 7;
    if (problemBrowser) {
        $('#header').css('z-index', '200');
    }

    // overlay close clicks
    $('.close-btn').click(function () {
        var popup = $("[id='addOverlay']");

        if (popup.attr('postback') == '1') {
            window.location = window.location;
            popup.attr('postback', '0')
            return;
        }

        popup.attr('style', 'display:none');
        var transBox = $('.transbox');
        transBox.attr('style', 'display:none');

        var problemBrowser = $.browser.msie && $.browser.version <= 7;
        if (problemBrowser) {
            $('#header').css('z-index', '200');
        }
        return false;
    });
    $('#btnContinue').click(function () {
        var popup = $("[id='addOverlay']");

        if (popup.attr('postback') == '1') {
            window.location = window.location;
            popup.attr('postback','0')
            return;
        }

        popup.attr('style', 'display:none');
        var transBox = $('.transbox');
        transBox.attr('style', 'display:none');

        var problemBrowser = $.browser.msie && $.browser.version <= 7;
        if (problemBrowser) {
            $('#header').css('z-index', '200');
        }
        return false;
    });


    $('.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("&iipage=", $('.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 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, '&amp;'
            ).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>");
    xml = xml.concat("<searchTerm>" + EncodeConfigValue($('.configSearchTerm')[0].value) + "</searchTerm>");
    xml = xml.concat("<sortExpression>" + EncodeConfigValue($('.configSortExpression')[0].value) + "</sortExpression>");
    xml = xml.concat("<baseUrl>" + EncodeConfigValue($('.configBaseUrl')[0].value) + "</baseUrl>");
    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) {
    if (ensureVisible && $(window).scrollTop() > 300) {
        $('html, body').animate({ scrollTop: 300 }, 0);
    }

    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() {
    // reset the mouse cursor from progress/waiting
    function resetMouse() {
        $("*").css("cursor", "auto");
        $('a').css('cursor', 'pointer');
        $('button').css('cursor', 'pointer');
        $('img').css('cursor', 'pointer');
    };


    //TEMP FIX: IE7 button position thrown out from blocking (TFS 5223)
    var problemBrowser = $.browser.msie && $.browser.version <= 7;
    var $resultsContainer = $('#product-list');

    $('#prod-list a.listing-page-no').click(function () {
        //Proceed only if the button is enabled or a URL exist
        if ($(this)[0].href != '') {
            $('html, body').animate({ scrollTop: 300 }, 0);
            if (!problemBrowser) BlockResultsContainer($resultsContainer, true, true);
            SetRefreshRefinements(false);
            SetPageNumber($(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 addtowishlist click
    $("[id$='AddToWishListLink']").click(function () {

        // hide any open addtobasket overlays
        $(".list-tool-tip-wrap").hide();
        $("[id$='appendedOverlay']").remove();

        var problemBrowser = $.browser.msie && $.browser.version <= 7;
        if (problemBrowser) {
            $('#header').css('z-index', '200');
        }

        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');
       // var hdnMsg = $(this).val();
        
        if (variant_id == null || variant_id == 'undefined') {
            variant_id = '';
        }
        var mode = $(this).attr('mode');  // add or remove

        var AddToWishlistCaption = $('.hdnAddToWishlistCaption').val();
        var RemoveFromWishlistCaption = $('.hdnRemoveFromWishlistCaption').val();
        var ListingWishListOverlayContent = $('.hdnListingWishListOverlayContent').val();
        var ListingWishListRemovedOverlayContent = $('.hdnListingWishListRemovedOverlayContent').val();

        // handle the return from web service call for add to wishlist in handler
        var fn = function (data, status) {
            resetMouse();

            // get the button parent container for positioning of info overlays
            var sectionPos = self.parent();
            var additionalLeft = 0;
            var additionalTop = 200;
            //var scaleHeight = 10;
            var popup = $("[id='addOverlay']");
            var transBox = $('.transbox');

            if (status === 'success') {
                var j = eval('(' + data + ')');

                if (typeof j.products != 'undefined' && j.products.length != 0) {
                    var producttext = j.products[0].productdetailtext;
                    if (mode == 'add') {
                        // added ok - show the overlay
                        popup.attr('style', 'display:block');
                        transBox.attr('style', 'display:block');
                        popup.css('top', sectionPos.offset().top - popup.height() + additionalTop);

                        //scroll into view 
                        var target = $("addOverlay");
                        //var top = target.offset().top + 300;                        
                        var top = popup.css('top');
                        //console.log("top: " + top);
                        $('html,body').animate({ scrollTop: top }, 1000);

                        // update the link text and mode to 'remove'
                        popup.find("[id='overlayHeader']").html(ListingWishListOverlayContent);
                        self.attr('mode', 'remove');
                        self.html(RemoveFromWishlistCaption);
                    }
                    if (mode == 'remove') {
                        // removed ok - show the overlay
                        popup.attr('postback', '1');
                        popup.attr('style', 'display:block');
                        transBox.attr('style', 'display:block');
                        popup.css('top', sectionPos.offset().top - popup.height() + additionalTop);

                        //scroll into view 
                        var target = $("addOverlay");
                        //var top = target.offset().top + 300;                        
                        var top = popup.css('top');
                        //console.log("top: " + top);
                        $('html,body').animate({ scrollTop: top }, 1000);

                        // update the link text and mode to 'add'
                        popup.find("[id='overlayHeader']").html(ListingWishListRemovedOverlayContent);
                        self.attr('mode', 'add');
                        self.html(AddToWishlistCaption);
                    }
                    // hide checkout button
                    popup.find("[id$='overlayCheckout']").attr('style', 'display:none');
                    popup.find("[id$='overlayError']").attr('style', 'display:none');
                    popup.find("[id$='overlayMessage']").attr('style', 'display:block');
                    popup.find("[id$='overlayHeader']").attr('style', 'display:block');
                    //  popup.find("[id$='overlayMessage']").html(producttext);
                    $('overlayMessage').hide();
                }
                return false;  // ensure postback not done
            }

            // not added - postback instead
            return true;
        };


        if (prodid != null && prodid != 'undefined' && prodid != '') {
            $("*").css("cursor", "progress");
            // web service call to add to wishlist
            if (mode == 'add') {
                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 });
            }
            // web service call to remove from wishlist
            if (mode == 'remove') {
                var o = $.extend({ command: 'RemoveFromWishList', 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 () {

        if (problemBrowser) {
            // If ie 6 then handle as javascript disabled and perform a postback
            return true;
        }

        // hide any open addtobasket overlays
        $(".list-tool-tip-wrap").hide();
        $("[id$='appendedOverlay']").remove();

        //hide mini-basket
        basketnavhide();

        var UpdateBasketCaption = $('.hdnUpdateBasketCaption').val();
        var ListingUpdatedBasketOverlayText = $('.hdnListingUpdatedBasketOverlayText').val();
        var ListingAddToBasketOverlayText = $('.hdnListingAddToBasketOverlayText').val();
        var ListingInsufficientStockOverlayText = $('.hdnListingInsufficientStockOverlayText').val();
        var ListingAddToBasketErrorOverlayText = $('.hdnListingAddToBasketErrorOverlayText').val();
        var ListingOutOfStockOverlayText = $('.hdnListingOutOfStockOverlayText').val();
        var ListingEnterQuantityOverlayText = $('.hdnListingEnterQuantityOverlayText').val();
        var ListingNothingToAddOverlayText = $('.hdnListingNothingToAddOverlayText').val();
        // quotas - TODO
        var ListingQuotaWarningOverlayText = $('.hdnListingQuotaWarningOverlayText').val();
        var ListingQuotaLimitOverlayText = $('.hdnListingQuotaLimitOverlayText').val();


        var variant_id = $(this).attr('variantid');


        var category_id = '';
        if ($('#product-cat') != null && $('#product-cat') != 'undefined') {
            category_id = $('#product-cat').val();
        }
        var q = "1";

        var self = $(this);

        qtyBox = self.parent().parent().find("[id$='addamount']");
        if (qtyBox != null && qtyBox != 'undefined' && qtyBox != '' && qtyBox.val() != null && qtyBox.val() != 'undefined' && qtyBox.val() != '') {
            q = parseInt(qtyBox.val());
        }
        else {
            return false;  // cannot add null qty
        }
        if ((q + '' == "NaN")) {
            return false;  // invalid number
        }

        var wishlistid = $("[id$='hdnWishlistId']");


        var prodid = $(this).attr('productid');
        var variant_id = $(this).attr('variantid');
        var hdnMsgForOverLay = $(this).attr('hdnMsg');

        if (variant_id == null || variant_id == 'undefined') {
            variant_id = '';
        }

        var existing = $(this).attr('existing');

        // handle the return from web service call for add to basket in handler
        var fn = function (data, status) {
            resetMouse();

            // overlay positioning for giftlist pages - need to inject the html
            var additionalLeft = 0;
            var additionalTop = 100;
            var sectionPos = self.parent();
            var popup = $("[id='addOverlay']");
            var transBox = $('.transbox');

            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'));
                    var producttext = j.products[0].productdetailtext;

                    // added to basket ok - rebuild minibasket
                    if (j.products[0].addToBasket == true) {

                        // show updated basket overlay
                        popup.attr('style', 'display:block');
                        transBox.attr('style', 'display:block');
                        popup.css('top', sectionPos.offset().top - popup.height() + additionalTop);
                        if (existing != null && existing != '' && existing != 'undefined' && existing == 'true') {
                            popup.find("[id='overlayHeader']").html(ListingUpdatedBasketOverlayText);
                        }
                        else {
                            // format added to basket overlay
                            popup.find("[id='overlayHeader']").html(ListingAddToBasketOverlayText);
                        }
                        // show checkout button
                        popup.find("[id$='overlayCheckout']").attr('style', 'display:block');
                        popup.find("[id$='overlayHeader']").attr('style', 'display:block');
                        popup.find("[id$='overlayMessage']").attr('style', 'display:block');
                        popup.find("[id$='overlayError']").attr('style', 'display:none');



                        popup.find("[id$='overlayHeader']").html(producttext);
                        popup.find("[id$='overlayMessage']").html(hdnMsgForOverLay);


                        if (j.products[0].quotaLimitExceeded == true) {
                            // show quota limit warning message
                            popup.find("[id$='overlayError']").html(ListingQuotaWarningOverlayText.replace('{0}', j.products[0].qty));
                            popup.find("[id$='overlayError']").attr('style', 'display:block');
                            qtyBox.val(j.products[0].newQty);
                        }


                        if (j.products[0].minibaskethtml != null && j.products[0].minibaskethtml != 'undefined' && j.products[0].minibaskethtml != '') {
                            $("#mini-basket-main").html(HtmlDecode(j.products[0].minibaskethtml));
                        }

                        //update the basket summary in header
                        var basketTitle = $('.hdnBasketTitleCaption').val();
                        // strip out items and total
                        var itemsText = "";
                        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;
                            }
                        }
                        $("[id$='divEmptyBasket']").attr('style', 'display:none;');
                        $("[id$='divBasketPopulated']").attr('style', 'display:block;');
                        if (j !== null && j.total != null) {
                            $('.basket-nav-summary-link').html(HtmlDecode(itemsText) + " " + HtmlDecode(j.total));
                        }
                        else {
                            $('.basket-nav-summary-link').html(HtmlDecode(itemsText) + " ");
                        }

                        // update the add to basket button image to 'update'
                        if (j.products[0].qty > 0) {
                            self.attr('existing', 'true');
                            self.attr('class', 'update-basket addtobasket');
                        }
                        else {
                            self.attr('existing', '');
                            self.attr('class', 'add-basket addtobasket');
                        }


                        rebindBasketNavClicks();

                    }
                    else {
                        popup.attr('style', 'display:block');
                        transBox.attr('style', 'display:block');
                        popup.css('top', sectionPos.offset().top - popup.height() + additionalTop);

                        //scroll into view 
                        var target = $("addOverlay");
                        //var top = target.offset().top + 300;                        
                        var top = popup.css('top');
                        //console.log("top: " + top);
                        $('html,body').animate({ scrollTop: top }, 1000);

                        if (msg == "nothing to update") {
                            $('#overlayMessage').html('');
                            popup.find("[id$='overlayMessage']").css('display', 'none');
                            popup.find("[id='overlayError']").html(ListingNothingToAddOverlayText);
                            self.attr('existing', '');
                        }
                        else if (j.products[0].qty == "0") {
                            popup.find("[id='overlayError']").html(ListingEnterQuantityOverlayText);
                            self.attr('existing', '');
                        }
                        else if (msg == "out of stock") {
                            popup.find("[id='overlayError']").html(ListingOutOfStockOverlayText);
                        }
                        else if (msg == "insufficient stock") {
                            popup.find("[id='overlayError']").html(ListingInsufficientStockOverlayText);
                        }
                        else {
                            popup.find("[id='overlayError']").html(ListingAddToBasketErrorOverlayText);
                        }
                        if (j.products[0].quotaLimitExceeded == true) {
                            // show quota limit warning message
                            popup.find("[id$='overlayError']").html(ListingQuotaWarningOverlayText.replace('{0}', j.products[0].qty));
                            qtyBox.val(j.products[0].newQty);
                        }
                        if (j.products[0].cannotAddDueToQuota == true) {
                            // show quota warning message

                            $('overlayMessage').hide();
                            popup.find("[id$='overlayError']").html(ListingQuotaLimitOverlayText);

                            qtyBox.val(j.products[0].newQty);
                        }
                        popup.find("[id$='overlayCheckout']").attr('style', 'display:block');
                        popup.find("[id$='overlayHeader']").attr('style', 'display:none');
                        popup.find("[id$='overlayMessage']").attr('style', 'display:block');

                        popup.find("[id$='overlayError']").attr('style', 'display:block');
                        $('overlayMessage').hide();
                        //popup.find("[id$='overlayMessage']").html(producttext);
                        // alert(hdnMsg);
                        //popup.find("[id$='overlayMessage']").html(hdnMsg);
                    }
                } else { // erroral
                    popup.attr('style', 'display:block');
                    transBox.attr('style', 'display:block');
                    popup.css('top', sectionPos.offset().top - popup.height() + additionalTop);

                    //scroll into view 
                    var target = $("addOverlay");
                    //var top = target.offset().top + 300;                        
                    var top = popup.css('top');
                    //console.log("top: " + top);
                    $('html,body').animate({ scrollTop: top }, 1000);

                    popup.find("[id='overlayError']").html(ListingAddToBasketErrorOverlayText);
                    popup.find("[id$='overlayCheckout']").attr('style', 'display:block');
                    popup.find("[id$='overlayHeader']").attr('style', 'display:none');
                    popup.find("[id$='overlayMessage']").attr('style', 'display:block');
                    popup.find("[id$='overlayError']").attr('style', 'display:block');
                    // popup.find("[id$='overlayMessage']").html(producttext);
                    // popup.find("[id$='overlayMessage']").html(hdnMsg);
                    $('overlayMessage').hide();
                }
            }
            return false;  // ensure postback not done
        };

        var bcnt = $('#basket-count').val();
        if (bcnt == "True")
        { $('#basket-count').val('False'); }

        if (prodid != null && prodid != 'undefined' && prodid != '') {
            $("*").css("cursor", "progress");
            // 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 });
            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');

    // 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');
    }
}

