/* Minification failed. Returning unminified contents.
(1021,22-23): run-time warning JS1004: Expected ';': o
(1021,25-26): run-time warning JS1004: Expected ';': O
 */

// ------------------------------------------------------------------------------------------------------------------------------
// Array
// ------------------------------------------------------------------------------------------------------------------------------

// redefining indexOf ? 
//Array.prototype.indexOf = function (value) {
//    debugger;
//    for (var i = 0; i < this.length; i++) {
//        if (this[i] == value) {
//            return i;
//        }
//    }
//    return null;
//};


Array.prototype.contains = function (value) {
    debugger;
    return this.indexOf(value) != null;
};


Array.prototype.remove = function (value) {
    debugger;
    var index = this.indexOf(value);
    if (index != null) {
        this.splice(index, 1);
        return value;
    }
    return null;
};



// filters an array using provided selectorFunction(arrayobject)
// eg myarray.select(function(arrayobject){ return arrayobject.id = 1; });
Array.prototype.select = function (selectorFunction) {
    debugger;
    var _returnArray = new Array();
    for (var i = 0; i < this.length; i++) {
        if (selectorFunction(this[i])) {
            _returnArray.push(this[i]);
        }
    }
    return _returnArray;
};


Array.prototype.get = function (query) {
    debugger;

    // Supplied an index; return it. 
    if (typeof query == 'number' && query > 0 && query < this.length) {
        return this[query];
    }

    // supplied a comparison function
    if (typeof query == 'function') {
        for (var i = 0; i < this.length; i++) {
            if (query(this[i])) {
                return this[i];
            }
        }
    }

    return null;
};


// Shorthand method for looping through an array
Array.prototype.each = function (function_to_run) {
    debugger;
    var args = new Array();
    args[1] = this;
    for (var i = 0; i < this.length; i++) {
        // use the call function to force 'this' within function_to_run to be the array element i 
        args[0] = i;
        args[2] = this[i];
        function_to_run.apply(this[i], args);
    }
};

// ------------------------------------------------------------------------------------------------------------------------------
// Date
// ------------------------------------------------------------------------------------------------------------------------------


Date.prototype.fromJson = function(value) {
    // remove anything except numbers and + sign (so we can use /Date(123456780000)/ and /Date(12345678+010)/
    var ticks = parseFloat(value.replace(/[^0-9+]/gi, ''));
    this.setTime(ticks);
    return this;
};

Date.prototype.fromJsonWithTimezone = function(value, timezoneOffsetInMinutes) {
    // remove anything except numbers and + sign (so we can use /Date(123456780000)/ and /Date(12345678+010)/
    var ticks = parseFloat(value.replace(/[^0-9+]/gi, ''));
    this.timeZoneCorrection = timezoneOffsetInMinutes;
    var timezoneCorrection = (timezoneOffsetInMinutes || 0) * 60 * 1000;
    this.setTime(ticks + timezoneCorrection);
    return this;
};


// ------------------------------------------------------------------------------------------------------------------------------
// Number
// ------------------------------------------------------------------------------------------------------------------------------


Number.prototype.ordinalSuffix = function() {
    if (this > 3) {
        return 'th';
    } else if (this == 3) {
        return 'rd';
    } else if (this == 2) {
        return 'nd';
    } else if (this == 1) {
        return 'st';
    }
};


Number.prototype.padWithZeros = function(digits) {
    ///<summary>Pads a number with the specified number of zeros</summary>
    var text = '' + this;
    for (var i = text.length; i < digits; i++) {
        text = '0' + text;
    }
    return text;
};


// ------------------------------------------------------------------------------------------------------------------------------
// String
// ------------------------------------------------------------------------------------------------------------------------------

// truncate string to nearest word
String.prototype.truncate = function (limit, useWordBoundary) {
    var tooLong = this.length > limit;
    var shortened = tooLong ? this.substr(0, limit - 1) : this;
    shortened = useWordBoundary && tooLong ? shortened.substr(0, shortened.lastIndexOf(' ')) : shortened;
    return tooLong ? shortened + '...' : shortened;
};


// strip html
String.prototype.stripHtml = function () {
    return this.replace(/(<([^>]+)>)/ig, "");
};


String.prototype.contains = function(value) {
    return this.indexOf(value) > -1;
};

// safely add a querystring term to a url
String.prototype.addQueryStringTermToUrl = function(value) {
    if (this.contains('?')) {
        return this + '&' + value;
    } else {
        return this + '?' + value;
    }
};


String.prototype.isNullOrEmpty = function() {
    return this == null || this == '';
};



// Replaces all instances of the given substring.
String.prototype.replaceAll = function(
    strTarget, // The substring you want to replace
    strSubString // The string you want to replace in.
) {
    var strText = this;
    var intIndexOfMatch = strText.indexOf(strTarget);

    // Keep looping while an instance of the target string
    // still exists in the string.
    while (intIndexOfMatch != -1) {
        // Relace out the current instance.
        strText = strText.replace(strTarget, strSubString);

        // Get the index of any next matching substring.
        intIndexOfMatch = strText.indexOf(strTarget);
    }

    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return (strText);
};
;/// <reference path="/scripts/jquery-1.7.1.min.js" />


(function () {

    window.Gap = window.Gap || {};
    Gap.Common = Gap.Common || {};
    Gap.Common.Ajax = Gap.Common.Ajax || {};
    Gap.Common.Serialise = Gap.Common.Serialise || {};
    Gap.Common.UI = Gap.Common.UI || {};

    // Definition for the options for AjaxWithDefaults
    Gap.Common.Ajax.Options = function() {
        this.type = 'POST';
        this.timeout = 100000;
        this.success = null; // custom handler for success
        this.error = null; // custom handler for error
        this.contentType = 'application/json'; // a content type default to application/json for ajax calls, or application/x-www-form-urlencoded
        this.dataType = 'json'; // returns a javascript object in data, use html or xml for other content. null is automaic. 
        this.autoSerialise = true;
        this.complete = null; // custom handler for complete
    };


    // Definition for the AjaxResponseObject returned by ajax calls
    Gap.Common.Ajax.Response = function () {
        this.Success = true; // indicates a successful server operation
        this.preventDefault = false; // prevents the default action from occurring when set in a custom handler
        this.Message = null;
        this.Redirect = false; // causes a browser redirect
        this.ReloadPage = false; // causes current page to reload
        this.Data = null;
        this.Complete = true;
    };


    Gap.Common.Ajax.Post = function (url, data, options) {
        ///<summary>Wrapper for an ajax call, passes user's callbacks to DefaultAjaxSuccess and DefaultAjaxError callbacks </summary>
        options = $.extend(new Gap.Common.Ajax.Options(), options);

        if (options.autoSerialise && options.contentType == 'application/json') {
            // serialise
            data = Gap.Common.Serialise.toJson(data);
        }

        $.ajax({
            url: url,
            type: options.type,
            data: data,
            headers: Gap.Common.Ajax.GetAntiForgeryTokenHeader(),
            dataType: options.dataType || 'json',
            contentType: options.contentType || 'application/json',
            timeout: options.timeout,
            success: function (response) { Gap.Common.Ajax.Success(response, options.success, options.error); },
            error: function (response) { Gap.Common.Ajax.Error(response, options.error); },
            complete: function (response) { Gap.Common.Ajax.Complete(response, options.complete); }
        });
    };

    Gap.Common.Ajax.GetAntiForgeryTokenHeader = function getAntiForgeryTokenHeader(selector) {
        if (!selector) {
            selector = "input[name='__RequestVerificationToken']";
        }

        if ($(selector).length <= 0) {
            return null;
        }
        var headers = {};
        headers["__RequestVerificationToken"] = $(selector).val();
        return headers;
    };


    Gap.Common.Ajax.Success = function (ajaxResponse, SuccessFunction, FailFunction) {
        ajaxResponse = $.extend(new Gap.Common.Ajax.Response(), ajaxResponse);
        ///<summary>Default sucess handler for an ajax call. Accepts user defined success and error callbacks.Callbacks should set ajaxResponse.prevent Default to prevent the default callback behaviour</summary>

        if (ajaxResponse.Success) {

            // Run user defined callback first
            if (SuccessFunction) {
                // set ajaxResponse.preventDefault in this method to prevent the default handling. 
                SuccessFunction(ajaxResponse);
            }

            // if preventDefault is set in the user defined callback, stop here
            if (ajaxResponse.preventDefault) {
                return;
            }

            // show lightbox notification
            if (ajaxResponse.Message) {
                // Show a user message
                Gap.Common.ShowNotification('good', '', ajaxResponse.Message);
            }

            // redirect
            if (ajaxResponse.Redirect) {
                // Transfer to the returned location
                window.location.href = ajaxResponse.Redirect;
            }

            // reload the current page
            if (ajaxResponse.ReloadPage) {
                window.location.reload(true);
                document.location.reload(true);
            }
        } else {
            // Communication succeeded, but server operation failed
            Gap.Common.Ajax.Error(ajaxResponse, FailFunction);
        }
    };


    Gap.Common.Ajax.Error = function (response, FailFunction) {
        ///<summary>Default error handler for an ajax call. Accepts a user defined callback </summary>

        // This could be the jquery response object if an exception was thrown, or our AjaxResponseObject if validation failed.
        var ajaxResponse = response.responseText ? jQuery.parseJSON(response.responseText) : response;

        // run user-defined callback
        if (FailFunction) {
            FailFunction(ajaxResponse);

            // if preventDefault is set in the user defined callback, stop here
            if (ajaxResponse.preventDefault) {
                return;
            }
        }

        // Show a notification indicating the response failed. 
        Gap.Common.ShowNotification('error', '', ajaxResponse.Message || response.responseText || 'An Error occurred');
    };

    Gap.Common.Ajax.Complete = function(response, CompleteFunction) {
        if (CompleteFunction) {
            CompleteFunction(response);
        }
    };


    Gap.Common.ShowNotification = function (type, title, message) {
        alert(message);
    };

    Gap.Common.ReplaceLanguage = function(currentLang, newLang) {
        var url = window.location.href;
        var regEx = new RegExp('/' + currentLang, "i");
        window.location.href = url.replace(regEx, '/' + newLang);
    }

    Gap.Common.Serialise.fromJson = $.parseJSON;

    Gap.Common.Serialise.formToObject = function (form) {
        var o = {};
        var a = form.serializeArray();
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    // gets the querystring as an object
    Gap.Common.Serialise.querystringToObject = function () {
        var querystring = window.location.search.substring(1); // get querystring and remove the ?
        var querystringParts = querystring.split("&");
        var querystringObject = {};
        for (var i = 0; i < querystringParts.length; i++) {
            var entryParts = querystringParts[i].split('=');
            querystringObject[entryParts[0]] = (entryParts.length > 1 ? decodeURIComponent(entryParts[1]) : null);
        }
        return querystringObject;
    };


    Gap.Common.UI.OpenWindowOptions = function () {
        // null values are ommitted, false's are included
        this.url = null;
        this.name = null;
        this.status = false;
        this.toolbar = false;
        this.menubar = false;
        this.location = false;
        this.resizable = false;
        this.copyhistory = false;
        this.directories = false;
        this.scrollbars = false;
        this.height = 480;
        this.width = 640;
        this.top = null;
        this.left = null;
    };

    Gap.Common.UI.OpenWindow = function (options) {

        // null values are ommitted from options, false's are included
        options = $.extend(new Gap.Common.UI.OpenWindowOptions(), options);


        // default the window position to the centre of the screen
        options.top = options.top || ((window.screen.height / 2) - (options.height / 2));
        options.left = options.left || ((window.screen.width / 2) - (options.width / 2));

        // Extract these values from options - we dont want them serialised. 
        var url = options.url;
        var name = options.name.replace(' ', ''); // IE doesnt accept spaces in the window title
        options.url = null;
        options.name = null;

        // serialise the user options
        var serialisedOptions = serialise(options).replace(/true/g, 'yes').replace(/false/g, 'no');

        window.open(url, name, serialisedOptions);

        // serialise an object to property=value,

        function serialise(object) {
            var serialisedObject = "";
            var counter = 0;
            for (var property in object) {
                // specific test for missing values here as we want to include false's
                if (typeof (object[property]) != 'undefined' && object[property] != null) {
                    serialisedObject += (counter++ > 0 ? "," : "") + property + "=" + object[property];
                }
            }
            return serialisedObject;
        }
    };


    Gap.Common.UI.showNotification = function (message, title, status) {
        // TODO: use lightbox
        alert(message);
    };


    Gap.Common.UI.escapeHtml = function (string) {
        var entityMap = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;',
            '/': '&#x2F;',
            '`': '&#x60;',
            '=': '&#x3D;'
        };

        return String(string).replace(/[&<>"'`=\/]/g, function (s) {
            return entityMap[s];
        });
    }

    // use the json formatter in json.js
    Gap.Common.Serialise.toJson = (typeof (JSON) != 'undefined' && JSON) ? JSON.stringify : {};

    Gap.Common.UI.renderTemplate = function (templateSelector, targetSelector, data) {
        return new Promise(function (resolve) {
            setTimeout(function () {
                var template = $(templateSelector).html();
                
                for (var key in data) {
                    if (data.hasOwnProperty(key)) {
                        template = template.replace(new RegExp('{{' + key + '}}', 'ig'), data[key]);
                    }
                }

                $(targetSelector).append(template);
                resolve();
            }, 0);
        });
    }

    Gap.Common.UI.isNewUiSkin = function () {
        return $('body').hasClass('new-ui-skin');
    }

    Gap.Common.UI.getParamFromQueryString = function (paramName)
    {
        var results = new RegExp('[\?&]' + paramName + '=([^&#]*)', 'i').exec(window.location.href);
        if (results == null) {
            return null;
        }
        return decodeURI(results[1]) || null;
    }
})();;/// <reference path="/scripts/jquery-1.7.1.min.js" />
/// <reference path="/scripts/prototypes.js" />

$(function () {
    //On Page Load
    //The following event handlers are loaded
    AddSearchParametersToQuerystring();
    printPageButton();
    navigationEventHandlers();
    siteWideMessage();
    cookieMessage();
});

// Sitewide Message
function siteWideMessage() {
    var cookie = GetCookie('closeSiteMessage');
    if (cookie != 'hideMe2' && cookie != 'hideMePermanently') {
        $("#siteWideMessage").hide().delay(3000).slideDown('slow').removeClass('hide');
    }
    $('#closeSiteMessage').click(closeSiteMessge);
}

function closeSiteMessge() {
    $("#siteWideMessage").slideUp();
    if (!window.showReminderAfterRefresh) {
        SetCookie('closeSiteMessage', 'hideMe2', 1);
    }
}

function hideForeverSiteWideMessage() {
    var cookie = GetCookie('closeSiteMessage');
    if (cookie != null && cookie != 'hideMePermanently') {
        SetCookie('closeSiteMessage', 'hideMePermanently', 100);
    }
}


// launch live bidding page in a new window
function launchLiveBidding(url, platformCode, lang) {

    var bidderAppSupportedLanguages = ['de-de', 'en-gb'];

    if (lang !== null && lang !== undefined) {
        lang = lang.toLowerCase().trim();
        if (bidderAppSupportedLanguages.includes(lang)) {
            url += '&lang=' + lang;
        }
    }

    if (platformCode === "BSC") {
        window.open(url, '_blank', 'scrollbars=yes,width=1366,height=768,resizable=yes');
    } else {
        window.open(url, '_blank', 'scrollbars=yes,width=1225,height=775,resizable=yes');
    }
}

// load printing dialog box
function printPageButton() {
    $('.printPageLink').click(function () {
        window.print();
        return false;
    });
}

//Navigation
function navigationEventHandlers() {
    //Reads URL and splits to an array at every forward slash
    var domainName = location.host;
    var splitUrl = location.pathname.split("/");
    var culture = splitUrl[1];
    var levelOne = splitUrl[2];
    //Main Nav
    if (location.pathname != "/" + culture && location.pathname != "/" + culture + "/") {
        $('ul#mainNav li a[href^="http://' + domainName + "/" + culture + '/' + levelOne + '"]').parent().addClass('active');
    }
    else {
        $('ul#mainNav li a:eq(0)').parent().addClass('active');
    }
}

//My Bidder Side Navigation
function myBidderSideNavigation() {
    //Reads URL and splits to an array at every forward slash
    var domainName = location.host;
    var splitUrl = location.pathname.split("/");
    var culture = splitUrl[1];
    var myBidder = splitUrl[2] + '/' + splitUrl[3];
    if (location.pathname != "/" + culture) {
        var nav = $('div#myBidderSideNav ul li a[href^="http://' + domainName + "/" + culture + '/' + myBidder + '"]');

        // If multiple nav elements
        if (nav.length > 1) {
            nav.filter(function() {
                var hrefAttrLowerCase = $(this).attr('href').toLowerCase();
                return location.href.toLowerCase().lastIndexOf(hrefAttrLowerCase, 0) === 0;
            }).parent().addClass('active');
        }
        else {
            nav.parent().addClass('active');
        }
    }
}

// Serialise the form and add to the querystring - so that the search is recoverable if we use the back button. 
function AddSearchParametersToQuerystring(searchForm) {
    if (searchForm) {
        var url = searchForm.action;
        url += '?searchTerm=' + $('#searchTerm').val();
        searchForm.action = url;
    }
}

// Escape string to be displayed in an HTML container.
function htmlEscape(str) {
    if (!str) return str;

    return str
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/\//g, '&#x2F;');
}

// Unescape string retrieved from HTML container.
function htmlUnescape(str) {
    if (!str) return str;

    return str
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&')
        .replace(/&#x2F;/g, '\/');
}

function searchStrip(str) {
    if (!str) return str;

    return str
        .replace(/</g, '')
        .replace(/>/g, '');
}

// Creating a cookie
function SetCookie(name, value, daysTillExpiry, path) {

    var cookie = name + '=' + escape(value) + ';';
    if (daysTillExpiry) {
        var date = new Date();
        date.setDate(date.getDate() + daysTillExpiry);
        cookie += ' expires=' + date.toUTCString() + ';';
    }

    // Set path (defaults to '/' ; scope global to the site)
    cookie += ' path=' + (path || '/') + ';';

    document.cookie = cookie;
}

// Reading a cookie
function GetCookie(name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(name + "=");
        if (c_start != -1) {
            c_start = c_start + name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

// Deleting a cookie
function DeleteCookie(name) {
    // Set cookie to expire yesterday - will get 
    SetCookie(name, '', -1);
}

//Wire up tooltips with label's onclick (instant) and onmouseover (delay of a sec)
function wireUpTooltips(labelCSS, tooltipCSS) {
    $('.' + labelCSS).each(function (i) {

        $(this).mouseover(function () {
            $(this).children('.' + tooltipCSS).addClass('activeTooltip');
            setTimeout("$('.activeTooltip').show()", 1500);
        });

        $(this).click(function () {
            $('.activeTooltip').show();
        });

        $(this).mouseout(function () {
            $(this).children('.activeTooltip').removeClass('activeTooltip').hide();
        });
    });
}

//This builds the correct S3 name for image file
function S3ImageName(imagename, size) {
    var s3Size;
    switch (size) {
        case 'Thumbnail': s3Size = '55x55'; break;
        case 'Small': s3Size = '80x80'; break;
        case 'Medium': s3Size = '120x120'; break;
        case 'IBMedium': s3Size = '155x155'; break;
        case 'Large': s3Size = '468x382'; break;
        case 'IBLarge': s3Size = '540x360'; break;
        case 'IBOriginal': s3Size = 'original'; break;
        default: s3Size = '120x120';
    }

    var newName = imagename.substr(0, imagename.length - 4);
    newName += s3Size;
    newName += imagename.substr(imagename.length - 4, 4);

    return newName;
}

//call this method to validate the form on client side
function isFormValid(form) {
    var validator = form.validate();
    return validator.form();
}

function validateEmail(value) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailPattern.test(value);
}

function validateKeyPress(jQueryEventObject, regularExpression) {
    var charCode = jQueryEventObject.charCode || jQueryEventObject.keyCode || jQueryEventObject.which;

    if (charCode == 8 || charCode == 13 || charCode == 27 || charCode == 37 || charCode == 39) {
        // allow backspace, return, escape, left, right
        return true;
    }
    else {
        // Check that the new character would be valid in the field
        var textIncludingNewCharacter = jQueryEventObject.target.value + String.fromCharCode(charCode);
        var pattern = new RegExp(regularExpression, "");
        var valid = pattern.test(textIncludingNewCharacter);
        return valid;
    }
}

function EstimateExists(lowEstimate, highEstimate) {
    return ((lowEstimate || 0) > 0) || ((highEstimate || 0) > 0);
}

// Returns string value for lot estimates    
function DisplayEstimates(lowEstimate, highEstimate, currencySymbol, currencyCode, notApplicable) {

    // must have a low or high estimate greater than 0
    if (EstimateExists(lowEstimate, highEstimate)) {

        var estimates = "";
        estimates += (currencySymbol || '');

        if (lowEstimate) {
            estimates += lowEstimate;
        }

        if (lowEstimate && highEstimate) estimates += " - ";

        if (highEstimate) {
            estimates += (currencySymbol || '');
            estimates += highEstimate;
        }

        if (currencyCode != 'GBP' && currencyCode != 'EUR') {
            estimates += ' ' + (currencyCode || '');
        }

        return estimates;
    }

    return notApplicable;
}

//call this method on image onerror event, to replace the non-existent image to a generic one
function ImageNotFound(imgElement, hrefElement) {
    $("#" + hrefElement).addClass("noImage");
    $("#" + imgElement).addClass("hide");
}

function ImageDeferredLoading(item) {
    if (!item.data('src')) {
        removeDeferredLoad.apply(item);
        return;
    }
    function removeDeferredLoad() {
        $(this)
            .removeClass('deferred-load')
            .removeAttr('loading')
            .parents('a')
            .removeClass('deferred-load');
    };

    item.parents('a').addClass('deferred-load');
    item.on('load', removeDeferredLoad)
        .on('error', removeDeferredLoad)
        .attr('src', item.data('src'))
        .removeAttr('data-src')
        .attr('loading', true);
}

function ApplyDeferredImages() {
    $('img.deferred-load[data-src]:not([loading])').each(function() {
        ImageDeferredLoading($(this));
    });
}

function AjaxWithDefaults(url, data, userOptions) {
    ///<summary>Wrapper for an ajax call, passes user's callbacks to DefaultAjaxSuccess and DefaultAjaxError callbacks </summary>
    var options = {
        type: 'POST',
        timeout: 100000,
        success: null,
        error: null
    };

    $.extend(options, userOptions);

    var SuccessFunction = function(response) { DefaultAjaxSuccess(response, options.success, options.error); };
    var ErrorFunction = function (response) { DefaultAjaxError(response, options.error); };

    $.ajax({
        type: options.type,
        url: url,
        data: data,
        success: SuccessFunction,
        error: ErrorFunction,
        timeout: options.timeout, // 100 second timeout
        headers: Gap.Common.Ajax.GetAntiForgeryTokenHeader()
    });
}

function DefaultAjaxSuccess(response, SuccessFunction, FailFunction) {
    ///<summary>Default sucess handler for an ajax call. Accepts user defined success and error callbacks.Callbacks should set response.prevent Default to prevent the default callback behaviour</summary>
    
    if (response.success) {

        // Run user defined callback first
        if (SuccessFunction) {
            SuccessFunction(response);
        }

        // if preventDefault is set in the user defined callback, stop here
        if (response.preventDefault) {
            return;
        }

        // show lightbox notification
        if (response.notification) {
            // Show a user message
            ShowNotification('good', '', response.notification);
        }

        // redirect
        if (response.redirect) {
            // Transfer to the returned location
            window.location.href = response.redirect;
        }

        // reload the current page
        if (response.reloadPage) {
            window.location.reload(true);
            document.location.reload(true);
        }
    }
    else {
        // Communication succeeded, but server operation failed
        DefaultAjaxError(response, FailFunction);
    }
}

function DefaultAjaxError(response, FailFunction) {
    ///<summary>Default error handler for an ajax call. Accepts a user defined callback </summary>
    
    // run user-defined callback
    if (FailFunction) {
        FailFunction(response);

        // if preventDefault is set in the user defined callback, stop here
        if (response.preventDefault) {
            return;
        }
    }

    // Show a notification indicating the response failed. 
    ShowNotification('error', '', response.notification || response.responseText || portalScriptResources.ErrorGeneric);
}

//function to return whole number with comma seperated thousands
function ToWholeNumber(amount) {
    var delimiter = ","; // replace comma if desired

    if (String(amount).indexOf(".") == -1)
        amount += ".00";

    var a = amount.split('.', 2);

    var i = parseInt(a[0]);
    if (isNaN(i)) { return '0'; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }
    if (n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);

    return minus + n;
}

// Spinner - You can now create a spinner using any of the variants below:
(function ($) {
    $.fn.spin = function (opts, color) {
        var presets = {
            "tiny": { lines: 15, length: 0, width: 3, radius: 3, trail:100, speed:1.2 },
            "small": { lines: 11, length: 0, width: 10, radius: 14, trail:100, speed:1.2 },
            "large": { lines: 17, length: 0, width: 14, radius: 33, trail:100, speed:1.2 }
        };
        if (Spinner) {
            return this.each(function () {
                var $this = $(this),
                    data = $this.data();

                if (data.spinner) {
                    data.spinner.stop();
                    delete data.spinner;
                }
                if (opts !== false) {
                    if (typeof opts === "string") {
                        if (opts in presets) {
                            opts = presets[opts];
                        } else {
                            opts = {};
                        }
                        if (color) {
                            opts.color = color;
                        }
                    }
                    data.spinner = new Spinner($.extend({ color: $this.css('color') }, opts)).spin(this);
                }
            });
        } else {
            throw "Spinner class not available.";
        }
    };

    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match;
        });
    };

    
})(jQuery);


// Cookie Message
function cookieMessage() {
    var cookie = GetCookie('closeCookieMessage');
    if (cookie != 'hideMe') {
        $("#cookie-banner").removeClass('hide');
       
    }
    $('#close-cookie').click(function () {
        $("#cookie-banner").addClass('hide');
        SetCookie('closeCookieMessage', 'hideMe', '100');
    });
}

// Add sort terms to query string
function UpdateQueryStringParameter(uri, key, value, useSearchFilter) {
    var validPages = ["/auction-catalogues", "/auctioneers"]
        var indexForSearch = uri.indexOf("search-results");
        var indexForFilters = uri.indexOf("search-filter");
    
    // replace search-results with search-filter
    if (useSearchFilter !== false && indexForFilters === -1) {
        if (indexForSearch !== -1) {
            uri = uri.replace("search-results", "search-filter");
        }
    }
    // if search-filter is not present on an appropiate page, add it in the correct place 
    if (useSearchFilter !== false && ContainsAny(uri, validPages) && indexForFilters === -1) {
        var indexForReplace = uri.indexOf("?");
        if (indexForReplace === -1) {
                uri = uri.slice(-1) == "/" ? uri + "search-filter" : uri + "/search-filter";
        } else {
                uri = uri.replace("?", "/search-filter?");
        }
    }

    // Add the sort term
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
        return uri + separator + key + "=" + value;
    }

}

function ContainsAny(str, items) {
        for (var i in items) {
            var item = items[i];
            if (str.indexOf(item) > -1) {
                return true;
            }
        }
        return false;
}

function ReplaceUndefinedToNull(obj) {
    if (!obj)
        return obj;

    // ReSharper disable once Es6Feature
    for(var property of Object.keys(obj))
    {
        if (obj[property] === undefined) {
            obj[property] = null;
        }
    }
    return obj;
}

$(function () {
    var cookieName = 'clerk-log-email';
    var selector = '#clerk-log-email';

    if ($(selector).length > 0 && window.Clerk && !GetCookie(cookieName)) {
        Clerk('content', selector);
        SetCookie(cookieName, true);
    }
});;// ----------------------------------------------------
// LoginBox - Start
// ----------------------------------------------------
(function () {
    window.Gap = window.Gap || {};
    Gap.Portal = Gap.Portal || {};
    Gap.Portal.UI = Gap.Portal.UI || {};
    Gap.Portal.UI.SiteLoginProperties = null;
})();

//on document ready
$(document).ready(function () {

    // On load script
    $('#loginDialogBox').dialog({
        autoOpen: false,
        hide: 'fast',
        width: 700,
        draggable: false,
        resizable: false,
        modal: true
    });

    // Dialog Close
    $('#cancelLoginButton, div#loginMessage div a.close').click(function () {
        $('#loginDialogBox').dialog('close');
        return false;
    });


    $('#cancelLoginButton').removeClass('hide');

    $('#loginPopupButton').click(function (e) {
        e.preventDefault();
        $('#loginForm').submit(submitLoginRequest());
    });
    $('#ajaxRequest').val("true");
    // Add a keypress event to form to replace 'enter keypress'
    $('#loginForm').keypress(formOnKeyDown);


    if ($('#verifyEmailDialog')) {
        $('#verifyEmailDialog').dialog({
            autoOpen: false,
            hide: 'fast',
            width: 620,
            draggable: false,
            resizable: false,
            modal: true
        });

        $(".verifyEmail").click(function() {
            $('#verifyEmailDialog').dialog('open');
        });

        $("#verifyEmailCancel").click(function() {
            $('#verifyEmailDialog').dialog('close');
            return false;
        });


        $('#verifyEmailOk').click(function(e) {
            e.preventDefault();
            $('#verifyEmailForm').submit(submitVerifyEmailRequest());
        });
    }
});


var closeLoginFormDialog;
var loginSuccessURL;

function formOnKeyDown(eventObject) {
    var charCode = eventObject.charCode || eventObject.keyCode || eventObject.which;
    if (charCode == 13) {
        // prevent form from submitting
        eventObject.preventDefault();
        $('#loginPopupButton').click();
        return false;
    }
    return true;
}

function resetPopupValidation() {
    //Removes validation from input-fields
    $('#login .input-validation-error').addClass('input-validation-valid').empty();
    $('#login .input-validation-error').removeClass('input-validation-error');

    //Removes validation message after input-fields
    $('#login .field-validation-error').addClass('field-validation-valid').empty();
    $('#login .field-validation-error').removeClass('field-validation-error');

    //Removes validation summary 
    $('#login .validation-summary-errors').addClass('validation-summary-valid').empty();
    $('#login .validation-summary-errors').removeClass('validation-summary-errors');
}

function resetLoginForm() {
    resetPopupValidation();
    $('#login').show();
    $('#loginMessage').addClass('hide');
}

function showLoginBoxWishList(lotId) {
    showLoginBox('', '', lotId);
}

function showLoginBoxAuctionAlerts(alert) {
    showLoginBox('', '', null, alert);
}

// Dialog Link            
function showLoginBox(successURL, registerURL) {
    if (window.ssoRedirect) {
        window.location.href = window.ssoRedirectLoginUrl + "?returnUrl=" + (successURL || window.location.href);
        return false;
    }

    resetLoginForm();
    if (successURL && successURL != '') {
        loginSuccessURL = successURL;
    }
    else {
        loginSuccessURL = Gap.Portal.UI.SiteLoginProperties.returnURL;
    }

    if (registerURL && registerURL != '') {
        $('#newAccountButton').attr('href', registerURL);
    }
    else {
        $('#newAccountButton').attr('href', Gap.Portal.UI.SiteLoginProperties.registerLink);
    }

    // Get email address from cookie set by previous logins. 
    $('#loginEmail').val(GetCookie('EmailAddress'));
    $('#loginPass').val('');
    $('#loginDialogBox').dialog('open');
    $('#loginEmail').focus();
    //Detect the user's browser timezone
    var timezone = jstz.determine();
    $('#TimeZone').val(timezone.name());
    return false;
}

function submitLoginRequest() {
    resetLoginForm();

    var form = $("#loginForm");
    if (!isFormValid(form) || !form.valid()) {
        return false;
    }

    $("#loginGo").addClass("loading");
    var postUrl = form.attr("action");
    var serializedForm = form.serialize();

    // Make an ajax call with the default callbacks - DefaultAjaxSuccess, DefaultAjaxError
    AjaxWithDefaults(postUrl, serializedForm, { success: loginSuccess, error: loginFailed });

    return false;

    // Callbacks
    function loginSuccess(resultObject) {
        window.location.href = loginSuccessURL;

        // Prevent the default behaviour - dont want to see a notification
        resultObject.preventDefault = true;
    }

    function loginFailed(resultObject) {
        // Do not show error message when the request has not been initialised, could happen when user hits enter multiple times, and when login happens the remaining requests are cancelled (readyState: 0)
        if (resultObject.readyState === 0) {
            resultObject.preventDefault = true;
            return;
        }
            
        // Show error message
        $('#loginMessage')
            .html('<ul><li>' + (resultObject.notification || Gap.Portal.UI.SiteLoginProperties.anErrorOccured) + '</li></ul>')
            .removeClass('validation-summary-valid')
            .addClass('validation-summary-errors')
            .removeClass('hide');
        // Prevent the default behaviour - dont want to see a notification
        resultObject.preventDefault = true;

        if (resultObject.data) {
            $('#resendVerificationEmail').live('click', function () {
                // Make an ajax call to resend the verification email
                AjaxWithDefaults(Gap.Portal.UI.SiteLoginProperties.resendVerificationLink, resultObject.data, { success: loginSuccess, error: loginFailed });
                $('#resendVerificationEmail').die('click', null);
            });
        }
    }
}    


// ----------------------------------------------------
// ForgottenPasswordBox - Start
// ----------------------------------------------------
var closeForgottenPasswordDialog;

function forgottenPasswordGo() {
    var form = $("#forgottenPasswordForm");

    if (!isFormValid(form)) {
        return false;
    }

    $("#forgottenPasswordGo").addClass("loading");
    var postUrl = form.attr("action");

    $('#hidReturnURLForgotPassword').val(document.location);
    var postData = $("#forgottenPasswordForm").serialize();

    $.ajax({
        type: 'POST',
        url: postUrl,
        data: postData,
        success: forgottenPasswordSuccess,
        error: AjaxCallFailed,
        timeout: 100000 // 10 second timeout
    });
}

function forgottenPasswordSuccess(resultObject) {
    if (resultObject.Status == 'success') {
        $('#forgottenPassword').hide("fast");
        $('#forgottenPasswordMessage div.error').hide();
        $('#forgottenPasswordMessage div.success').show();
        $('#forgottenPasswordMessage div.verifyEmail').hide();
        $('#forgottenPasswordMessage').show("fast");
        closeforgottenPasswordDialog = window.setTimeout("$('#forgottenPasswordDialogBox').dialog('close')", 5000);
        $("#forgottenPasswordGo").removeClass("loading");
    }
    else {
        forgottenPasswordFailed(resultObject);
    }
}

function AjaxCallFailed(resultObject) {
    forgottenPasswordFailed("");
}

function forgottenPasswordFailed(resultObject) {
    if (resultObject.Message == "") {
        resultObject.Message = Gap.Portal.UI.SiteLoginProperties.anErrorOccured;
    }
    $('#forgottenPassword').hide("fast");
    $('#forgottenPasswordMessage div.success').hide();
    $('#forgottenPasswordMessage div.verifyEmail').hide();
    $('#forgottenPasswordMessage p.errorMsg').html(resultObject.Message);
    $('#forgottenPasswordMessage div.error').show();
    $('#forgottenPasswordMessage').show("fast");
    $("#forgottenPasswordGo").removeClass("loading");
}

$(function () {
    // Dialog			
    $('#forgottenPasswordDialogBox').dialog({
        autoOpen: false,
        hide: 'fast',
        width: 600,
        draggable: false,
        resizable: false,
        modal: true
    });

    // Dialog Link            
    $('.forgotPass').click(function () {
        resetForgottenPasswordForm();
        if ($('#loginDialogBox')) {
            $('#loginDialogBox').dialog('close');
        }
        $('#forgottenPasswordDialogBox').dialog('open');
        return false;
    });

    // Send Again           
    $('a#forgottenPasswordTryAgain').click(function () {
        resetForgottenPasswordForm();
        window.clearTimeout(closeForgottenPasswordDialog);
        $('#forgottenPasswordMessage').hide();
        $('#forgottenPassword').show();
        return false;
    });

    // Dialog Close
    $('#cancelForgottenPasswordButton, div#forgottenPasswordMessage div a.close').click(function () {
        $('#forgottenPasswordDialogBox').dialog('close');
        return false;
    });
});

function resetForgottenPasswordForm() {
    $('#forgottenPassword').show();
    $('#forgottenPasswordMessage').hide();
}


function submitVerifyEmailRequest() {
    
    var verifyForm = $("#verifyEmailForm");

    if (!isFormValid(verifyForm) || !verifyForm.valid()) {
        return false;
    }
    
    var postUrl = verifyForm.attr("action");
    var data = {
        RegisteredEmail: $('#customerEmailAddress').val()
    };

    AjaxWithDefaults(postUrl, data, { success: verifyEmailSuccess, error: verifyEmailFailed });

    return false;

    // Callbacks
    function verifyEmailSuccess(resultObject) {
        $('#verifyEmailDialog').dialog('close');
        resultObject.preventDefault = true;
    }

    function verifyEmailFailed(resultObject) {
        // Do not show error message when the request has not been initialised, could happen when user hits enter multiple times, and when login happens the remaining requests are cancelled (readyState: 0)
        if (resultObject.readyState === 0) {
            resultObject.preventDefault = true;
            return;
        }
        // Show error message
        $('#verifyEmailMessage')
            .html('<ul><li>' + (resultObject.notification || Gap.Portal.UI.SiteLoginProperties.anErrorOccured) + '</li></ul>')
            .removeClass('validation-summary-valid')
            .addClass('validation-summary-errors')
            .removeClass('hide');
        // Prevent the default behaviour - dont want to see a notification
        resultObject.preventDefault = true;
    }
};(function () {
    window.Gap = window.Gap || {};
    Gap.Portal = Gap.Portal || {};
    Gap.Portal.UI = Gap.Portal.UI || {};
    Gap.Portal.UI.SiteMessageProperties =
    {
        CloseClicked: null,
        MessageLoaded: null,
        AutoOpen: false
    };
})();

$(document).ready(function () {
    // Dialog Close
    $('#messageOkButton, #messageCancelButton').click(function () {
        $('#messageDialogBox').dialog('close');
        if (Gap.Portal.UI.SiteMessageProperties && Gap.Portal.UI.SiteMessageProperties.CloseClicked) {
            Gap.Portal.UI.SiteMessageProperties.CloseClicked();
        }
        return false;
    });

    if (Gap.Portal.UI.SiteMessageProperties && Gap.Portal.UI.SiteMessageProperties.MessageLoaded) {
        Gap.Portal.UI.SiteMessageProperties.MessageLoaded();
    }

    if (Gap.Portal.UI.SiteMessageProperties && Gap.Portal.UI.SiteMessageProperties.AutoOpen) {
        // Open automatically if a notification has been provided in the ViewModel
        $('div#messageDialogBox').dialog('open');
    }
});

function ShowNotification(messageType, dialogTitle, message, toastrOptions) {
    // Check for toastr, and use that if available
    if (window['toastr']) {
        //legacy message CSS class has 'good' for 'success'
        if (messageType === 'good') {
            messageType = 'success'
        }            
        toastr.options = {
            "positionClass": "toast-top-center",
            "preventDuplicates": true
        }
        if (toastrOptions) {
            toastr.options = toastrOptions;
        }
        toastr[messageType](message, dialogTitle);
    } else {
        var container = $('div#messageDialogBox');
        $('span#notificationMessage,div#notificationMessage', container).html(message);
        container.dialog({ dialogClass: messageType, title: dialogTitle, autoOpen: true, minHeight: 130, width: 350, modal: true });
        container.dialog('open');
    }
};(function () {
    $(document).ready(function () {
        var retval = {};

        var body = $('body').eq(0);

        body.on('click touchstart', function (e) {

            if (!$(e.target).parents('.sidebarContainer').length) {
                retval.closeSidebar();
                Gap.Layout.returnUrl = null;
            }
        });

        var classes = {
            Sidebar: 'sidebar-open',
            Searchbox: 'searchbox-open',
            Filters: 'filters-open',
            Menu: 'menu-open',
            Catalogue: 'catalogue-page',
            BetaOverlay: 'beta-overlay-visible',
            Lot: 'lot-details-page'
        };

        var actions = {
            toggle: 'toggleClass',
            open: 'addClass',
            close: 'removeClass'
        };

        function buildAction(action, klass) {
            return function () {
                body[actions[action]](classes[klass]);
            }
        }


        for (var action in actions) {
            for (var klass in classes) {
                retval[action + klass] = buildAction(action, klass);
            }
        }

        Gap.Layout = retval;

        Gap.Layout.openSidebarWithRedirect = function (url, event) {
            Gap.Layout.returnUrl = url;
            Gap.Layout.openSidebar();
            event.stopPropagation();
            return false;
        };

        // hack for fixing chrome bug
        // on browser back button, chrome do not display selected dropdown value properly
        // we ned to re-set dropdown values
        $(window).on('pageshow', function () {

            $(document).ready(function () {
                $('select#cultureList').each(function () {
                    $(this).val($(this).find('option[selected]').val());
                });
            });
        });

    });
})();

;(function(){
    Gap.Headerbar = {
        sideBarToggle: function(event){
            event.stopPropagation();
            Gap.Layout.toggleSidebar();
        },
        searchBarToggle: function() {
            $('body').toggleClass('searchbox-open');
        }
    };
})();;$(function () {
	//On Page Load
	primaryNav();
});

function primaryNav() {
	$(".primary-navigation .top-menu").click(function () {

        $(".primary-navigation .top-menu").parent().removeClass('active');
        $(".primary-navigation").removeClass('active');

		$(this).parent().addClass('active');
    });

	$(document).bind('click', function (e) {

        var $clicked = $(e.target);

        if (!$clicked.hasClass("top-menu") && !$clicked.parents().hasClass("sub-menu")) {
            $(".primary-navigation .top-menu").parent().removeClass('active');
            $(".primary-navigation").addClass('active');
		}
	});
};$(function () {
    //On Page Load
    navigationToggle();
    searchBoxToggle();
    navigationBack();
});

function navigationToggle() {
    $(".menu-toggle").click(function () {
        $('body').toggleClass('menu-open');
        $('body').removeClass('searchbox-open');
    });
}

function searchBoxToggle() {
    $(".search-box-toggle").click(function () {
        $('body').toggleClass('searchbox-open');
        $('body').removeClass('menu-open');
    });
}

function navigationBack() {
    $(".menu-back").click(function () {
        $(".primary-navigation .top-menu").parent().removeClass('active');
        $(".primary-navigation").addClass('active');

        $(".primary-nav .top-menu").parent().removeClass('active');
        $(".primary-nav").addClass('active');
    });
};function GapRecentlyViewedEntry(key, item) {
    this.key = key;
    this.item = item;
}

function GapSortOrder() {
    this.asc = false;
    this.desc = true;
}

function GapRecentlyViewedStorage(name, maxItems) {
    if (typeof maxItems === "undefined") maxItems = 30;
    this.maxItems = maxItems;
    this.storage = $.initNamespaceStorage("gap-lot").localStorage;
}

GapRecentlyViewedStorage.prototype.removeAll = function () {
    this.storage.removeAll();
}

GapRecentlyViewedStorage.prototype.add = function (id, item) {

    // push this to the end and don't repeat viewings
    if (this.storage.isSet(id)) {
        this.storage.remove(id);
    }

    while (this.storage.keys().length >= this.maxItems) {
        this.remove(this.storage.keys()[0]);
    }

    this.storage.set(id, item);
}

GapRecentlyViewedStorage.prototype.remove = function (id) {
    this.storage.remove(id);
}

GapRecentlyViewedStorage.prototype.getItems = function (descending) {
    if (typeof descending === "undefined") descending = false;

    var keys = this.storage.keys();
    var items = new Array();
    var current = descending === true ? keys.length - 1 : 0;
    var increment = descending === true ? -1 : 1;

    for (var i = 0; i < keys.length; i++) {
        items[i] = new GapRecentlyViewedEntry(keys[current], this.storage.get(keys[current]));
        current += increment;
    }

    return items;
}

// specific javascript object being stored for lots
function GapRecentlyViewedLot(id, title, url, thumbnailUrl, timeStamp, defaultLanguage, translations) {
    this.id = id;
    this.title = title;
    this.url = url;
    this.thumbnailUrl = thumbnailUrl;
    this.timeStamp = timeStamp;
    this.defaultLanguage = defaultLanguage;
    this.translations = translations;
}



var rv;
var currentLanguage;

var recentlyViewedLotsCurrentLanguage = recentlyViewedLotsCurrentLanguage || "en";

$(function (recentlyViewedLotsCurrentLanguage) {
    rv = new GapRecentlyViewedStorage();
    currentLanguage = recentlyViewedLotsCurrentLanguage;

    loadSlick($("#recentLotCarousel"), rv);
}(recentlyViewedLotsCurrentLanguage));

function removeAndRefresh(id) {
    rv.remove(id);
    var mcs = $("#recentLotCarousel");
    mcs.slick("unslick");
    mcs.empty();
    loadSlick(mcs, rv);
}

function recentlyViewedRemoveAll() {
    rv.removeAll();

    $(".recently-viewed h1, .recently-viewed .clear, #recentLotCarousel").fadeOut('slow');

    var rvHeight = $(".recently-viewed").height();
    
    $(".recently-viewed").css({ "height": rvHeight});

    $(".recently-viewed").delay(1000).animate({
        height: '0'
    }, 1000, function () {
        $(".recently-viewed").slideUp("slow", function () {
            $(".recently-viewed").addClass('hide').removeAttr("style");
        });
    });

}

function loadSlick(carousel, storage) {
    var items = storage.getItems(true);

    if (items.length === 0) {
        recentlyViewedRemoveAll();
    }
    else {
        $(".recently-viewed").removeClass('hide');

        $.each(items, function (i, item) {

            var lotImageClass = "", lotImage;
            var itemTitle;

            var translations = item.item.translations;
            var defaultLanguage = item.item.defaultLanguage;

            if (translations && translations[currentLanguage] && translations[currentLanguage].Title && translations[currentLanguage].Title.length > 0) {
                itemTitle = translations[currentLanguage].Title;
            } else if (translations && translations[defaultLanguage] && translations[defaultLanguage].Title && translations[defaultLanguage].Title.length > 0) {
                itemTitle = translations[defaultLanguage].Title;
            } else {
                itemTitle = item.item.title;
            }

            if (!item.item.thumbnailUrl) {
                lotImageClass = "no-lot-image";
                lotImage = [
                    '<span class="no-image">',
                    '<span>', portalScriptResources.No_Image, '</span>',
                    '<img src="/content/sr/images/blank-image-120x120.png" alt="',  portalScriptResources.No_Image, '" />',
                    '</span>'
                ].join('');
            } else {
                lotImage = '<img src="' + item.item.thumbnailUrl + '" alt="' + Gap.Common.UI.escapeHtml(itemTitle) + '" />';
            };

            carousel.append(
                '<div class="lot-container ' + lotImageClass + '">' +
                    '<div class="lot-info">' +
                        '<a href=\"' + item.item.url + '\" rel=\"follow\">' +
                            lotImage +
                        '</a>' +
                '<p>' + Gap.Common.UI.escapeHtml(itemTitle) + '</p>' +
                        '<button class="button cross" onclick=\"javascript:removeAndRefresh(\'' + item.key + '\')\">Remove</button>' +
                    '</div>' +
                '</div>');
            });

        carousel.slick({
            dots: true,
            arrows: true,
            infinite: false,
            slidesToShow: 12,
            slidesToScroll: 12,
            respondTo: 'min',
            responsive: [
                {
                    breakpoint: 1920,
                    settings: {
                        slidesToShow: 9,
                        slidesToScroll: 9,
                        infinite: true,
                        dots: true
                    }
                },
                {
                    breakpoint: 1400,
                    settings: {
                        slidesToShow: 7,
                        slidesToScroll: 7,
                        infinite: true,
                        dots: true
                    }
                },
                {
                    breakpoint: 1050,
                    settings: {
                        slidesToShow: 5,
                        slidesToScroll: 5,
                        infinite: true,
                        dots: true
                    }
                },
                {
                    breakpoint: 800,
                    settings: {
                        slidesToShow: 3,
                        slidesToScroll: 3,
                        infinite: true,
                        dots: true
                    }
                },
                {
                    breakpoint: 600,
                    settings: {
                        slidesToShow: 2,
                        slidesToScroll: 2
                    }
                },
                {
                    breakpoint: 440,
                    settings: {
                        slidesToShow: 1,
                        slidesToScroll: 1
                    }
                }]
        });
    }
};/*
$(function() {
    'use strict';

    / *
        Override mystery toggleSideBar for SR to show semantic modal
    * /
    Gap.Layout = Gap.Layout || {};
    Gap.Layout.toggleSidebar = function() {
        $('#login-modal .tabular.menu .item').tab();
        $('#login-modal').modal('show');
    };
});
*/

function showLoginBoxWishList(lotId) {
    showLoginBox('', '', lotId);
}

function showLoginBoxAuctionAlerts(alert) {
    showLoginBox(window.location.href, '', null, alert);
}

function showLoginBoxAuctioneerId(auctioneerId) {
    showLoginBox('', '', null, null, auctioneerId);
}

// Override default showLoginBox           
function showLoginBox(successURL, registerURL, lotId, alert, auctioneerId) {
    resetLoginForm();

    var queryParam = "";

    if (lotId != undefined) {
        queryParam = "wishListLotId=" + lotId;
        $('#wishListLotId').val(lotId);
    }

	if (successURL && successURL != '') {
		loginSuccessURL = successURL;
	}
	else {
	    loginSuccessURL = Gap.Portal.UI.SiteLoginProperties.returnURL;
	}

	if (alert != undefined) {
	    queryParam += "&auctionAlert=" + alert;
	    $('#auctionAlert').val(alert);
	    loginSuccessURL += '&auctionAlertCreated=true';
	}

	if (auctioneerId) {
	    queryParam += "&auctioneerId=" + auctioneerId;
	    $('#auctioneerId').val(auctioneerId);
	}

	if (registerURL && registerURL != '') {
	    $('#newAccountButton').attr('href', registerURL);

 	    Gap.Portal.UI.SiteLoginProperties.RegistrationUrl = registerURL;
	}
	else {
	    $('#newAccountButton').attr('href', Gap.Portal.UI.SiteLoginProperties.registerLink);

	    Gap.Portal.UI.SiteLoginProperties.RegistrationUrl = Gap.Portal.UI.SiteLoginProperties.registerLink + (queryParam.length ? "?" + queryParam.substring(1) : "");
    }

    if (window.ssoRedirect) {
        window.location.href = window.ssoRedirectLoginUrl + "?returnUrl=" + encodeURIComponent(loginSuccessURL.trim());
        return false;
    }

	// Get email address from cookie set by previous logins. 
	$('#loginEmail').val(GetCookie('EmailAddress'));
	$('#loginPass').val('');
	//$('#loginDialogBox').dialog('open');
	//$('#loginEmail').focus();
	//Detect the user's browser timezone
	var timezone = jstz.determine();
	$('#TimeZone').val(timezone.name());

	setTimeout(function () { Gap.Layout.toggleSidebar(); }, 1);
	return false;
}

// Dialog Link    
$(function () {
    $('.forgotPass').off('click');
    $('.forgotPass').click(function () {
        Gap.Layout.toggleSidebar();
        Gap.Portal.UI.SiteLoginProperties.setActiveTab('forgotpassword');
        return false;
    });
});
;/*
    Lot details page
*/
$(function () {
    'use strict';

    // Lot tabular & accordion details
    $('.ui.menu .item').tab();

    $('.accordion').accordion({
        onOpening: function () {
            var $this = $(this.context);

            $('.angle', $this)
                .removeClass('down')
                .addClass('up');
        },
        onChange: function () {
            var $this = $(this),
                $parent = $this.parent('.accordion');

            $('.title:not(.active) .angle', $parent)
                .addClass('down')
                .removeClass('up');
        }
    });

    //Shipping options
    $('.shipping-options').on('click', function (e) {
        e.preventDefault();

        var $tabWrapper = $('.tabs-wrapper'),
            $accordionWrapper = $('.accordion-wrapper'),
            $body = $('html, body');

        $('.ui.menu .item', $tabWrapper).tab('change tab', 'shipping');
        $('.ui.accordion', $accordionWrapper).accordion('open', 2);

        if ($tabWrapper.is(':visible')) {
            $body.animate({
                scrollTop: $tabWrapper.offset().top
            }, 500);
        }
        else if ($accordionWrapper.is(':visible')) {
            $body.animate({
                scrollTop: $accordionWrapper.offset().top
            }, 500);
        }
    });

    // Lot image / video carousel (synchronised with below)
    $('.lot-details-image').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        infinite: true,
        fade: true,
        asNavFor: '.lot-details-image-nav',
        lazyLoad: 'ondemand',
        respondTo: 'slider'
    });

    // Lot image / video bar carousel (synchronised with above)
    $('.lot-details-image-nav').slick({
        mobileFirst: true,
        infinite: false,
        slidesToShow: 3,
        slidesToScroll: 1,
        centerMode: true,
        focusOnSelect: true,
        centerPadding: '0px',
        variableWidth: true,
        asNavFor: '.lot-details-image',
        lazyLoad: 'progressive',
        respondTo: 'slider'
    });

    // Sticky bid panel
    //$('.ui.sticky').sticky({
    //    context: '#bidpanel'
    //});

    // Wishlist / Watchlist ...apparently the same thing!
    $('.watchlist').on('click', function (e) {
        e.preventDefault();

        var $this = $(this),
            $count = $('.watchlist-count'),
            data = {
                auctionId: $this.data('auctionId'),
                lotId: $this.data('lotId'),
                action: $this.hasClass('watchlist-add') ? 'add' : 'remove'
            };

        if (Gap.Portal.UI.IsAuthenticated) {
            $this.addClass('loading');

            $.ajax({
                url: Gap.Portal.UI.WatchlistUrl,
                type: "POST",
                headers: Gap.Common.Ajax.GetAntiForgeryTokenHeader(),
                data: data,
                success: function (response) {

                    var count = Number($count.text());

                    if (data.action === 'add') {

                        var queryId = Gap.Common.UI.getParamFromQueryString('queryId');
                        if (typeof aa !== 'undefined' && queryId) {
                            aa(CONVERSION_EVENT_TYPE,
                                {
                                    userToken: dataLayer[0].globalId || UNKNOWN_USER_TOKEN,
                                    index: saytVM.config.indexName,
                                    eventName: CONVERSION_WATCHLISTED_AFTER_SEARCH_ON_LOT_PAGE,
                                    queryID: queryId,
                                    objectIDs: [$this.data('lotId')]
                                });
                        }

                        $this.removeClass('watchlist-add').addClass('watchlist-remove');
                        $count.text(count += 1);

                        pushWatchedUnwatchedEvent($this, 'WatchedItem')

                    } else if (data.action === 'remove') {
                        $this.removeClass('watchlist-remove').addClass('watchlist-add');
                        $count.text(count -= 1);

                        pushWatchedUnwatchedEvent($this, 'UnwatchedItem')
                    }
                },
                error: function () {
                    console.log('Watchlist error', arguments);
                }
            }).always(function () {
                $this.removeClass('loading');
            });
        }
        else { // Legacy login
            window.showLoginBoxWishList(data.lotId);
        }
    });


    // Popup
    $('.bid-panel .popup-wrapper').popup({
        on: 'click',
        closable: true
        //inline: true
    });

    // Bid history
    $('.bid-panel .bidHistoryContainer .popup-wrapper').popup({
        position: 'bottom right',
        on: 'click'
    });

    $('#bidHistoryForm').removeClass('hide').addClass('ui unstackable basic table bidHistoryForm');

    // Your max bid
    $('.bid-panel .your-max-bid-standard .popup-wrapper').popup({
        lastResort: 'bottom right',
        html: $('#max-bid-popup').html(),
        on: 'click',
        exclusive: true,
        boundary: $('.bid-panel')
    });

    // Buyer's premium
    $('.bid-panel .buyer-premium .popup-wrapper').popup({
        position: 'top right',
        html: $('#buyers-premium-popup').html(),
        on: 'click'
    });

    // Commissions & fees
    $('.bid-panel .commissions .popup-wrapper').popup({
        lastResort: 'bottom right',
        html: $('#commissions-popup').html(),
        on: 'click',
        inline: false,
        exclusive: true,
        boundary: $('.bid-panel')
    });

    $('.bid-panel .pending-approval-popup .popup-wrapper').popup({
        position: 'top right',
        html: $('#bidding-popup').html(),
        on: 'click'
    });

    $('.bid-panel .tender-popup').popup({
        position: 'top right',
        html: $('#tender-popup').html(),
        on: 'click'
    });

    $('.catalogue-popup').popup({
        position: 'top right',
        html: $('#catalogue-popup').html(),
        on: 'click'
    });


    $(".touch-swipe-gallery .sliderHolder .closeIcon").on('mousedown touchstart', function (e) {

        // On close set the main image to be the same image as the one the user was last viewing within the gallery zoom
        var getGallery = TouchNSwipe.getSlider("zoomSlider");
        var getGalleryIndex = getGallery.index();
        var getVideoCount = $('.lot-image').attr('data-video-count');
        var getTotalMediaCount = (parseInt(getGalleryIndex) + parseInt(getVideoCount));

        $('.lot-details-image').slick("slickGoTo", getTotalMediaCount);

        return false;

    });

    // Video
    $('.lot-details-image .slick-slide.video').click(mainImageAction);

    $('.lot-details-image-nav').on('beforeChange', function (event, slick, currentSlide, nextSlide) {
        stopYouTubeVideo();
    });

    $('.lot-details-image').on('beforeChange', function (event, slick, currentSlide, nextSlide) {
        $('.lot-details-image-nav .slick-slide').removeClass('slick-active');
        $('.lot-details-image-nav .slick-slide').removeClass('slick-current');
        $('.lot-details-image-nav .slick-slide[data-slick-index="' + nextSlide + '"]').addClass('slick-current');
        $('.currentImage').text(nextSlide + 1);
        stopYouTubeVideo();
    });

    function mainImageAction() {
        if ($(this).hasClass('video')) {

            $('.lot-image').addClass('display-video');

            var videoID = $(this).attr('data-id');
            if (portalYouTubePlayer) {
                portalYouTubePlayer.loadVideoById(videoID, 0, 'medium');
            }
        }
    }

    function stopYouTubeVideo() {
        if ($('.lot-image').hasClass('display-video')) {
            if (portalYouTubePlayer) {
                portalYouTubePlayer.stopVideo();
            }

            $('.lot-image').removeClass('display-video');
        }
    }

    function pushWatchedUnwatchedEvent($this, eventName) {
        if (window.dataLayer) {
            window.dataLayer.push(ReplaceUndefinedToNull({
                event: eventName,
                catalogueId: $this.data('auctionId'),
                auctioneerId: $this.data('clientId'),
                lotId: $this.data('lotId'),
                lotName: $this.data('lotName'),
                categoryCode: window.dataLayer[0].categoryCode,
                lotCategory: window.dataLayer[0].lotCategory,
                catalogueName: $this.data('auctionName'),
                auctioneerName: $this.data('clientName'),
                lotPrimaryCategory: window.dataLayer[0].lotPrimaryCategory,
                lotItemType: window.dataLayer[0].lotItemType,
                lotBrand: window.dataLayer[0].lotBrand,
                auctionType: $this.data('auctionType'),
                userId: $this.data('userId'),
                globalId: window.dataLayer[0].globalId
            }));
        }
    }

    // Checkbox
    $('.ui.checkbox').checkbox();
});
;
var OPTOUTTOGGLEID = 'instantSearchOptOutBtn';
var OPTOUTTOGGLECOOKIE = 'esOptOut';
var OPTOUTBTNID = 'toggleBtn';
var OPTOUTTOOLTIPID = 'optOutToolTip';
var ACTIVECLASS = 'active';

$(document).ready(function () {
    var lsVal = false;

    if (typeof instantSearchSwitch !== 'undefined') { // If a customer has already opted out in a previous visit
        lsVal = instantSearchSwitch.toLowerCase() == 'true' ? true : false;
    }

    SetCookie(OPTOUTTOGGLECOOKIE, lsVal);

    var optOutToggle = $('#instantSearchOptOutBtn > form');

    if (optOutToggle) {

        var btn = optOutToggle.find('#' + OPTOUTBTNID).first();
        var tip = optOutToggle.find('#' + OPTOUTTOOLTIPID).first();

        btn.hover(// show/hide tool tip
            function () {
                $(tip).delay('500').fadeIn('fast');
            },
            function () {
                $(tip).delay('100').fadeOut('fast');
            });

        btn.click(function (event) {
            lsVal = !lsVal;
            // set visual state of toggle
            var holder = btn.parent();
            if (lsVal) {
                holder.removeClass(ACTIVECLASS);
            }
            else {
                holder.addClass(ACTIVECLASS);
            }
            // update cooke
            SetCookie(OPTOUTTOGGLECOOKIE, lsVal);
            // reload page to switch search engine
            location.reload();
        });
    }
});;"use strict";

$(document).ready(function () {
    var toggle = $('#instantSearchOptOutBtn');
    var searchBox = $('.instant-search-on .main-search .lot-search');
    var cutoff = 425;

    $('#main-search-term').focus(function () {
        if ($(window).width() <= cutoff) {
            $(toggle).addClass('hide');
            $(searchBox).addClass('full-width');
        }
    });

    $('#main-search-term').blur(function () {
        if ($(window).width() <= cutoff) {
            $(toggle).removeClass('hide');
            $(searchBox).removeClass('full-width');
        }
    });
});;