/* Minification failed. Returning unminified contents.
(1633,9-21): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: scrollTopElm
(1493,13-19): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: newURL
 */
"use strict";
console.log("Infinate Scoller: Enter");

var _slicedToArray = (function () {
    function sliceIterator(arr, i) {
        var _arr = [];
        var _n = true;
        var _d = false;
        var _e = undefined;
        try {
            for (
                var _i = arr[Symbol.iterator](), _s;
                !(_n = (_s = _i.next()).done);
                _n = true
            ) {
                _arr.push(_s.value);
                if (i && _arr.length === i) break;
            }
        } catch (err) {
            _d = true;
            _e = err;
        } finally {
            try {
                if (!_n && _i["return"]) _i["return"]();
            } finally {
                if (_d) throw _e;
            }
        }
        return _arr;
    }
    return function (arr, i) {
        if (Array.isArray(arr)) {
            return arr;
        } else if (Symbol.iterator in Object(arr)) {
            return sliceIterator(arr, i);
        } else {
            throw new TypeError(
                "Invalid attempt to destructure non-iterable instance"
            );
        }
    };
})();

var _createClass = (function () {
    function defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
            var descriptor = props[i];
            descriptor.enumerable = descriptor.enumerable || false;
            descriptor.configurable = true;
            if ("value" in descriptor) descriptor.writable = true;
            Object.defineProperty(target, descriptor.key, descriptor);
        }
    }
    return function (Constructor, protoProps, staticProps) {
        if (protoProps) defineProperties(Constructor.prototype, protoProps);
        if (staticProps) defineProperties(Constructor, staticProps);
        return Constructor;
    };
})();

function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}

var infiniteScroll = (function () {
    function infiniteScroll() {
        var _ref =
            arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
            _ref$element = _ref.element,
            element = _ref$element === undefined ? ".dynamicContent" : _ref$element,
            _ref$endpoint = _ref.endpoint,
            endpoint = _ref$endpoint === undefined ? false : _ref$endpoint,
            _ref$page = _ref.page,
            page = _ref$page === undefined ? 1 : _ref$page,
            _ref$outputClass = _ref.outputClass,
            outputClass = _ref$outputClass === undefined ? false : _ref$outputClass,
            _ref$scrollContainer = _ref.scrollContainer,
            scrollContainer =
                _ref$scrollContainer === undefined ? false : _ref$scrollContainer,
            _ref$productContainer = _ref.productContainer,
            productContainer =
                _ref$productContainer === undefined
                    ? ".associated-product"
                    : _ref$productContainer,
            _ref$initialFetch = _ref.initialFetch,
            initialFetch = _ref$initialFetch === undefined ? true : _ref$initialFetch,
            _ref$dataLayer = _ref.dataLayer,
            dataLayer = _ref$dataLayer === undefined ? false : _ref$dataLayer,
            _ref$totalPages = _ref.totalPages,
            totalPages = _ref$totalPages === undefined ? false : _ref$totalPages,
            _ref$pagination = _ref.pagination,
            pagination = _ref$pagination === undefined ? true : _ref$pagination,
            _ref$scrollOffset = _ref.scrollOffset,
            scrollOffset = _ref$scrollOffset === undefined ? 0 : _ref$scrollOffset;


        _classCallCheck(this, infiniteScroll);

        this.element = element;
        this.element_selector = document.querySelector(element);
        if (!this.element_selector)
            throw new Error("Element " + element + " not found.");
        if (((this.endpoint = endpoint), !this.endpoint))
            throw new Error("Endpoint not set.");
        this.start_page = parseInt(page) ? parseInt(page) : 1;
        this.outputClass = outputClass;
        this.productContainer = productContainer;
        this.scrollContainer = document.querySelectorAll(scrollContainer)[0];
        this.initialFetch = initialFetch;
        this.dataLayer = dataLayer;
        this.totalPages = parseInt(totalPages);
        if (!this.totalPages) throw new Error("TotalPages not set.");
        this.scrollOffset = parseInt(scrollOffset);
        this.start_page =
            this.start_page > this.totalPages ? this.totalPages : this.start_page;
        this.pagination = pagination;
        this.init();
    }

    _createClass(infiniteScroll, [
        {
            key: "dispatchEvent",
            value: function dispatchEvent(eventName) {
                var params =
                    arguments.length > 1 && arguments[1] !== undefined
                        ? arguments[1]
                        : {};

                var event = new CustomEvent("infiniteScroll:" + eventName, {
                    detail: params
                });
                document.dispatchEvent(event);
            }
        },
        {
            key: "getParams",
            value: function getParams(query) {
                if (!query) {
                    return {};
                }
                return (/^[?#]/.test(query) ? query.slice(1) : query)
                    .split("&")
                    .reduce(function (params, param) {
                        var _param$split = param.split("="),
                            _param$split2 = _slicedToArray(_param$split, 2),
                            key = _param$split2[0],
                            value = _param$split2[1];

                        params[key] = value
                            ? decodeURIComponent(value.replace(/\+/g, " "))
                            : "";
                        return params;
                    }, {});
            }
        },
        {
            key: "serialize",
            value: function serialize(obj) {
                return (
                    "?" +
                    Object.entries(obj)
                        .map(function (_ref2) {
                            var _ref3 = _slicedToArray(_ref2, 2),
                                key = _ref3[0],
                                val = _ref3[1];

                            return key + "=" + val;
                        })
                        .join("&")
                );
            }
        },
        {
            key: "findAncestor",
            value: function findAncestor(el, cls) {
                while ((el = el.parentElement) && !el.classList.contains(cls)) { }
                return el;
            }
        },
        {
            key: "getOffset",
            value: function getOffset(el) {
                var _x = 0,
                    _y = 0;
                while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
                    _x += el.offsetLeft - el.scrollLeft;
                    _y += el.offsetTop - el.scrollTop;
                    el = el.offsetParent;
                }
                return { top: _y, left: _x };
            }
        },
        {
            key: "fetchPage",
            value: function fetchPage(pageNumber) {
                var _this = this;

                var pageElement =
                    arguments.length > 1 && arguments[1] !== undefined
                        ? arguments[1]
                        : false;
                var previous =
                    arguments.length > 2 && arguments[2] !== undefined
                        ? arguments[2]
                        : false;

                pageNumber = parseInt(pageNumber);
                if (isNaN(pageNumber)) {
                    return Promise.reject(new Error("Invalid page number"));
                }
                this.dispatchEvent("beforeFetch", { page: pageNumber });
                var params = this.getParams(window.location.search);
                params.page = pageNumber;
                delete params.fetch; 
                params = this.serialize(params);
                return fetch("" + this.endpoint + params)
                    .then(function (response) {
                        return response.ok
                            ? response.text()
                            : Promise.reject(Error(response.message));
                    })
                    .then(function (text) {
                        if (_this.dataLayer) {
                            var newDataLayer = document
                                .createRange()
                                .createContextualFragment(text)
                                .querySelector("script.dataLayer").text;
                            newDataLayer +=
                                "dataLayer[1].listing.items = dataLayer[1].listing.items.concat(data.listing.items);";
                            new Function(newDataLayer)();
                        }
                        if (_this.outputClass) {
                            text = document
                                .createRange()
                                .createContextualFragment(text)
                                .querySelector(_this.outputClass).outerHTML;
                        }
                        _this
                            .outputPage(pageElement, pageNumber, text, previous)
                            .then(function (pageElement) {
                                _this.dispatchEvent("afterFetch", {
                                    page: pageNumber,
                                    element: pageElement
                                });

                                document.querySelector('.paging-module__loading').classList.remove('active');
                                _this.productTotals();

                                return Promise.resolve();
                            });
                    })
                    .catch(function (error) {
                        return Promise.reject(new Error("Unable to load page", error));
                    });
            }
        },
        {
            key: "outputPage",
            value: function outputPage(pageElement, pageNumber, text, previous) {
                var self = this;

                return new Promise(function (resolve) {
                    var newElement = !pageElement;
                    pageElement || (pageElement = document.createElement("div"));
                    pageElement.innerHTML = text;
                    pageElement.className = "js-infinite-scroll-page";
                    pageElement.style.height = "";
                    if (newElement) {
                        pageElement.setAttribute("data-page", pageNumber);
                        if (previous) {
                            self.element_selector.insertBefore(
                                pageElement,
                                self.element_selector.childNodes[0]
                            );
                            self.addPreviousButton(pageNumber - 1);
                            self.scrollContainer
                                ? self.scrollContainer.scrollTo(0, pageElement.scrollHeight)
                                : window.scrollTo(0, pageElement.scrollHeight);
                        } else {
                            self.element_selector.appendChild(pageElement);
                            self.addNextButton(pageNumber + 1);
                        }
                    }


                    resolve(pageElement);

                    // Track the ajax page view
                    var pageTitle = document.querySelector('input[name="ajaxTitle"]').value;

                    $(document).trigger("rc-pageview", {
                        url: location.pathname + location.search,
                        title: pageTitle
                    });


                    if (checkDYO()) {

                        DY.API('spa', {
                            context: {
                                type: 'CATEGORY',
                                data: fetchBreadCrumb()
                            },
                            url: location.href,
                            countAsPageview: true
                        });
                    }

                });
            }
        }, {
            key: "productTotals",
            value: function calculateTotals() {

                var elm = document.querySelector('.js-infinite-scroll');
                var isLoadMore = document.querySelector('.infinite-scroll__load-more');
                var pagingShowing = document.querySelector('.paging-module__showing');
                var pagingTotal = document.querySelector('.paging-module__total');

                var currentPage = 1;
                var query = this.getParams(window.location.search);
                    
                if (query.page) {
                    currentPage = query.page;
                }

                var adverts = document.querySelectorAll('.listing-items');
                var totalAdverts = 0;

                for (var i = 0; i < adverts.length; i++) {
                    totalAdverts = totalAdverts + parseInt(adverts[i].dataset.advert);
                }

                var productCount = (currentPage * elm.dataset.page) - totalAdverts;
                var totalProducts = elm.dataset.total;


                if (productCount > totalProducts) {
                    productCount = totalProducts;
                }

                if (query.viewall === "true") {
                    productCount = totalProducts;
                }

                if (isLoadMore !== null) {
                    
                    var child = document.querySelector(".infinite-scroll__load-more-info");

                    if (child !== null) {
                        isLoadMore.removeChild(child);
                    }

                    var element = document.createElement("div");
                    element.className = "infinite-scroll__load-more-info";
                    element.innerHTML = "1 to " + productCount + " (of " + totalProducts + " found)";

                    isLoadMore.appendChild(element);  
                } 

                pagingShowing.innerHTML = productCount;
                pagingTotal.innerHTML = totalProducts;

            }
        },
        {
            key: "addNextButton",
            value: function addNextButton(pageNumber) {

                var _this2 = this;
                var url = window.location.href;
                var currentPage = pageNumber - 1;
                var newUrl;

                if (pageNumber === 2) {

                    if (url.indexOf('?') !== -1) {
                        newUrl = url + '&page=2'
                    } else {
                        newUrl = url + '?page=2'
                    }
                } else {
                    newUrl = url.replace('page=' + currentPage, 'page=' + pageNumber);
                }

                if (pageNumber <= this.totalPages && this.pagination) {
                    var element = document.createElement("div");
                    element.className =
                        "infinite-scroll__load-more js-infinite-scroll-loadmore";
                    element.innerHTML = "<a href='" + newUrl + "' class='infinite-scroll__btn'>Load more</div>";
                    element.setAttribute("data-page", pageNumber);
                    element.onclick = function () {
                        var params = _this2.getParams(window.location.search);
                        params.page = pageNumber;
                        params.fetch = 1;

                        window.history.pushState("", "", _this2.serialize(params));
                        _this2.fetchPage(element.getAttribute("data-page"));
                        _this2.element_selector.removeChild(
                            document.querySelectorAll(".js-infinite-scroll-loadmore")[0]
                        );

                        document.querySelector('.paging-module__loading').classList.add('active');

                      

                    };
                    this.element_selector.appendChild(element);

                    var loadBtn = document.querySelector('.infinite-scroll__btn');
                    loadBtn.addEventListener("click", function (e) {
                        e.preventDefault();
                    });
                }
            }
        },
        {
            key: "addPreviousButton",
            value: function addPreviousButton(pageNumber) {
                var _this3 = this;

                if (pageNumber > 0 && this.pagination) {
                    var element = document.createElement("div");
                    element.className =
                        "infinite-scroll__load-prev js-infinite-scroll-loadprev";
                    element.innerHTML = "<div class='infinite-scroll__btn'>Load Previous</div>";
                    element.setAttribute("data-page", pageNumber);
                    element.onclick = function () {
                        var params = _this3.getParams(window.location.search);
                        params.page = pageNumber;
                        window.history.pushState("", "", _this3.serialize(params));
                        _this3.fetchPage(element.getAttribute("data-page"), false, true).then(function() {

                                var previousPage = pageNumber + 1;

                                var elm = document.querySelectorAll('.js-infinite-scroll-page[data-page="' + previousPage + '"]')[0];
                                elm.scrollIntoView({ behavior: "instant", block: "center"});
                        });
                        _this3.element_selector.removeChild(
                            document.querySelectorAll(".js-infinite-scroll-loadprev")[0]
                        );
                    };
                    this.element_selector.insertBefore(
                        element,
                        this.element_selector.childNodes[0]
                    );
                }
            }
        },
        {
            key: "setupSaveScroll",
            value: function setupSaveScroll() {
                var self = this;
                this.element_selector.addEventListener("click", function (event) {
                    var className = self.productContainer.replace(".", "");
                    var element = event.target.classList.contains(className)
                        ? event.target
                        : self.findAncestor(event.target, className);
                    if (element) {

                        var product = element.getAttribute("data-id");
                        var page = self
                            .findAncestor(element, "js-infinite-scroll-page")
                            .getAttribute("data-page");

                        var params = self.getParams(window.location.search);
                       // params.page = params.page != null ? params.page: page;
                        params.scrollto = product;
                        window.history.pushState("", "", self.serialize(params));
                    }
                });
            }
        },
        {
            key: "goToProduct",
            value: function goToProduct(final) {
                var params = this.getParams(window.location.search);
                if (params.scrollto) {
                           
                    var elm = document.querySelectorAll(this.productContainer + '[data-id="' + params.scrollto + '"]')[0];
                    elm.scrollIntoView(true);

                    if (final) {
                        delete params.scrollto;
                        window.history.replaceState("", "", this.serialize(params));
                    }
                }
            }
        },
        {
            key: "init",
            value: function init() {
                var _this4 = this;

                if ("scrollRestoration" in history) {
                    history.scrollRestoration = "manual";
                }
                this.setupSaveScroll();
                //this.addPreviousButton(this.start_page - 1);
                if (this.initialFetch) {
                    this.fetchPage(this.start_page).then(function () {
                        _this4.goToProduct(true);
                    });
                } else {
                    var self = this;

                    //this.goToProduct(false);
                    window.onload = function () {
                        self.goToProduct(true);
                    };

                    this.addNextButton(this.start_page + 1);
                    this.productTotals();
                }
            }
        }
    ]);

    return infiniteScroll;
})();

/* USAGE *

import infiniteScroll from '../frontend-modules/infinite-scroll/infinite-scroll';
new infiniteScroll({options});

// options:
//
// Required:
// - endpoint: JSONified resource for page content [string] (required)
// - totalPages: Total number of pages on this listing page [int] (required)
//
// Optional:
// - element: Which element should be the container for the infinite scroll [string] (optional, default '.dynamicContent')
// - outputClass: Which element should be outputted from the returned fetch call [string] (optional, default false)
// - scrollContainer: Class name of a div that acts as a page scroller [string] (optional, default 'body')
// - scrollOffset: Height of any static headers, etc, that may affect auto-scrolling [int] (optional, default 0)
// - page: Start loading content from this page number [int] (optional, default 1)
// - initialFetch: Fetch the first page on init [bool] (optional, default true)
// - dataLayer: Look for and include the datalayer JS tag [bool] (optional, default false)
// - pagination: Include previous/next buttons [bool] (optional, default true)
*/
;
/*!
 * headroom.js v0.9.3 - Give your page some headroom. Hide your header until you need it
 * Copyright (c) 2016 Nick Williams - http://wicky.nillia.ms/headroom.js
 * License: MIT
 */

!function(a,b){"use strict";"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?module.exports=b():a.Headroom=b()}(this,function(){"use strict";function a(a){this.callback=a,this.ticking=!1}function b(a){return a&&"undefined"!=typeof window&&(a===window||a.nodeType)}function c(a){if(arguments.length<=0)throw new Error("Missing arguments in extend function");var d,e,f=a||{};for(e=1;e<arguments.length;e++){var g=arguments[e]||{};for(d in g)"object"!=typeof f[d]||b(f[d])?f[d]=f[d]||g[d]:f[d]=c(f[d],g[d])}return f}function d(a){return a===Object(a)?a:{down:a,up:a}}function e(a,b){b=c(b,e.options),this.lastKnownScrollY=0,this.elem=a,this.tolerance=d(b.tolerance),this.classes=b.classes,this.offset=b.offset,this.scroller=b.scroller,this.initialised=!1,this.onPin=b.onPin,this.onUnpin=b.onUnpin,this.onTop=b.onTop,this.onNotTop=b.onNotTop,this.onBottom=b.onBottom,this.onNotBottom=b.onNotBottom}var f={bind:!!function(){}.bind,classList:"classList"in document.documentElement,rAF:!!(window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame)};return window.requestAnimationFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame,a.prototype={constructor:a,update:function(){this.callback&&this.callback(),this.ticking=!1},requestTick:function(){this.ticking||(requestAnimationFrame(this.rafCallback||(this.rafCallback=this.update.bind(this))),this.ticking=!0)},handleEvent:function(){this.requestTick()}},e.prototype={constructor:e,init:function(){return e.cutsTheMustard?(this.debouncer=new a(this.update.bind(this)),this.elem.classList.add(this.classes.initial),setTimeout(this.attachEvent.bind(this),100),this):void 0},destroy:function(){var a=this.classes;this.initialised=!1,this.elem.classList.remove(a.unpinned,a.pinned,a.top,a.notTop,a.initial),this.scroller.removeEventListener("scroll",this.debouncer,!1)},attachEvent:function(){this.initialised||(this.lastKnownScrollY=this.getScrollY(),this.initialised=!0,this.scroller.addEventListener("scroll",this.debouncer,!1),this.debouncer.handleEvent())},unpin:function(){var a=this.elem.classList,b=this.classes;!a.contains(b.pinned)&&a.contains(b.unpinned)||(a.add(b.unpinned),a.remove(b.pinned),this.onUnpin&&this.onUnpin.call(this))},pin:function(){var a=this.elem.classList,b=this.classes;a.contains(b.unpinned)&&(a.remove(b.unpinned),a.add(b.pinned),this.onPin&&this.onPin.call(this))},top:function(){var a=this.elem.classList,b=this.classes;a.contains(b.top)||(a.add(b.top),a.remove(b.notTop),this.onTop&&this.onTop.call(this))},notTop:function(){var a=this.elem.classList,b=this.classes;a.contains(b.notTop)||(a.add(b.notTop),a.remove(b.top),this.onNotTop&&this.onNotTop.call(this))},bottom:function(){var a=this.elem.classList,b=this.classes;a.contains(b.bottom)||(a.add(b.bottom),a.remove(b.notBottom),this.onBottom&&this.onBottom.call(this))},notBottom:function(){var a=this.elem.classList,b=this.classes;a.contains(b.notBottom)||(a.add(b.notBottom),a.remove(b.bottom),this.onNotBottom&&this.onNotBottom.call(this))},getScrollY:function(){return void 0!==this.scroller.pageYOffset?this.scroller.pageYOffset:void 0!==this.scroller.scrollTop?this.scroller.scrollTop:(document.documentElement||document.body.parentNode||document.body).scrollTop},getViewportHeight:function(){return window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight},getElementPhysicalHeight:function(a){return Math.max(a.offsetHeight,a.clientHeight)},getScrollerPhysicalHeight:function(){return this.scroller===window||this.scroller===document.body?this.getViewportHeight():this.getElementPhysicalHeight(this.scroller)},getDocumentHeight:function(){var a=document.body,b=document.documentElement;return Math.max(a.scrollHeight,b.scrollHeight,a.offsetHeight,b.offsetHeight,a.clientHeight,b.clientHeight)},getElementHeight:function(a){return Math.max(a.scrollHeight,a.offsetHeight,a.clientHeight)},getScrollerHeight:function(){return this.scroller===window||this.scroller===document.body?this.getDocumentHeight():this.getElementHeight(this.scroller)},isOutOfBounds:function(a){var b=0>a,c=a+this.getScrollerPhysicalHeight()>this.getScrollerHeight();return b||c},toleranceExceeded:function(a,b){return Math.abs(a-this.lastKnownScrollY)>=this.tolerance[b]},shouldUnpin:function(a,b){var c=a>this.lastKnownScrollY,d=a>=this.offset;return c&&d&&b},shouldPin:function(a,b){var c=a<this.lastKnownScrollY,d=a<=this.offset;return c&&b||d},update:function(){var a=this.getScrollY(),b=a>this.lastKnownScrollY?"down":"up",c=this.toleranceExceeded(a,b);this.isOutOfBounds(a)||(a<=this.offset?this.top():this.notTop(),a+this.getViewportHeight()>=this.getScrollerHeight()?this.bottom():this.notBottom(),this.shouldUnpin(a,c)?this.unpin():this.shouldPin(a,c)&&this.pin(),this.lastKnownScrollY=a)}},e.options={tolerance:{up:0,down:0},offset:0,scroller:window,classes:{pinned:"headroom--pinned",unpinned:"headroom--unpinned",top:"headroom--top",notTop:"headroom--not-top",bottom:"headroom--bottom",notBottom:"headroom--not-bottom",initial:"headroom"}},e.cutsTheMustard="undefined"!=typeof f&&f.rAF&&f.bind&&f.classList,e});;
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof module === 'object' && module.exports) {
        module.exports = factory();
    } else {
        root.wishlistModule = factory();
    }
}(this, function () {

    var wishlistModule = {
        version: '1.0.0',
        placeholderSelector: '.js-wishlist-total'
    };

    wishlistModule.init = function () {
        wishlistModule.attachEventListeners();
    };

    function _handleAddToWishlistClick(e) {
        e.preventDefault();
        var thisButton = $(this),
            productCode = $('input[name="productCode"]').length > 0 ? $('input[name="productCode"]').val() : thisButton.parents('.associated-product').data('id'),
            rawData = {
                wishlistID: thisButton.data('wishlistid') || -1,
                stockID: thisButton.data('stockid') || -1,
                productID: thisButton.data('productid') || -1,
                basketID: thisButton.data('basketid') || -1,
                qty: thisButton.parents('.sizePicker') ? thisButton.parents('.sizePicker').find('[name="quantity"]').val() : 1
            },
            data = $.param(rawData),
            url = (rawData.basketID == -1) ? "/ajax/addtowishlist" : "/ajax/addbaskettowishlist";

        thisButton.attr("data-loading", "true");

        //$('.tooltip', thisButton.parent()).tooltip('hide');

        $.ajax({
            url: url,
            data: data,
            success: function (data) {
                if (data.error) {
                    if (data.error.message.indexOf("Please log in") != -1) {
                        //$('.quick-account-login a:eq(0)').trigger('click');
                        //WG-test
                        var stockCode = data.results.stock;
                        if ('credentials' in navigator) {
                            credentialHelper.attemptSignIn("/ajax/loginmodal?iswishlist=true&stockcode=" + stockCode);
                        } else {
                            OpenModal("/ajax/loginmodal?iswishlist=true&stockcode=" + stockCode);
                        }
                    } else {
                        alert(data.error.message);
                    }
                } else {

                    // Update the basket quantities if there was no error
                    wishlistModule.setPlaceholderValues(data.results.WishlistItems);
                    wishlistModule.updateHeader(data.results.loggedIn);
                    UpdateHeader();
                    thisButton.addClass("in-wishlist").find(".glyphicon-star-empty").removeClass("glyphicon-star-empty").addClass("glyphicon-star");
                    thisButton.find(".wishlist-heart").addClass("hidden");
                    thisButton.find(".wishlist-heart--added").removeClass("hidden");

                    thisButton.trigger('added.wishlist.remarkable');

                    $(document).trigger("rc-product-add-to-wishlist", {
                        productCode: productCode
                    });
                }
                thisButton.removeAttr("data-loading");
            },
            error: function () {
                alert("There has been an error\nPlease refresh and try again");
                thisButton.removeAttr("data-loading");
            }
        });
    }

    wishlistModule.attachEventListeners = function (context) {
        var _context = context || document;
        $(_context).on('click', '.js-add-to-wishlist', _handleAddToWishlistClick);
    };

    wishlistModule.updatePlaceholderValues = function () {
        wishlistModule.setPlaceholderValues(Remarkable.WishlistItems);
    };

    wishlistModule.setPlaceholderValues = function (items) {
        $(wishlistModule.placeholderSelector).html(items);
      
        if (items > 0) {
            $(wishlistModule.placeholderSelector).removeClass('hidden');
        } else {
            $(wishlistModule.placeholderSelector).addClass('hidden');
       }
    };


    wishlistModule.updateHeader = function (loggedIn) {

        var url = "/account/wishlist";

        if (!loggedIn) {
            $('.js-wishlist-url').attr('href', url);
        }
    };

    return wishlistModule;
}));;
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', ], factory);
    } else if (typeof module === 'object' && module.exports) {
        module.exports = factory(require('jquery'));
    } else {
        root.listingPage = factory(root.jQuery);
    }
}(this, function ($) {
    var $ = $;
    var listingPage = {};

    function _fixJqueryReference() {
        $ = window.jQuery;
    }

    listingPage.init = function () {
        _fixJqueryReference();
        console.log("Listing Page: Enter");

        $(document).trigger("rc-product-list-visible", {
            pageName: $('h1').text().trim()
        });

        _legacy();
        wishlistModule.init();
        listingPage.formCollectionCarousel();
        emailCapture.init();
        royalAscot();

        if ($(".js-infinite-scroll").length > 0 && window.location.pathname !== '/freds-edit') {
            listingPage.initInfiniteScroll();
        }

        document.addEventListener("scroll", function () {
            scrollBackToTheTop();
        });

        var isScrollToTop = false;
        var scrollBackToTheTop = Remarkable.debounce(function () {
            if ($(document).scrollTop() > 1000 && !isScrollToTop) {

                isScrollToTop = true;
                if (checkDYO()) {
                    DY.API("event", {
                        name: "scrollToTop",
                        properties: {
                            value: "show"
                        }
                    });
                }
            } 
        }, 150);


        $('.js-view-more').on('click', function (e) {
            e.preventDefault();

            var self = $(this);

            self.parents('.category-intro__description').toggleClass('active');
            self.toggleClass('active');

            if (self.hasClass('active')) {
                self.html('View Less');
            } else {
                self.html('View More');
            }
        });


        $('.js-seo-view-more').on('click', function (e) {
            e.preventDefault();

            var self = $(this);

            $('.seo-description').toggleClass('active');
            self.toggleClass('active');

            if (self.hasClass('active')) {

                self.html('View Less');

            } else {

                self.html('View More');

            }
        });

        $(document).on('click','.js-open-filters', function (e) {
            e.preventDefault();

            var id = $(this).data('name'); 

            $('.filter-draw').removeClass('filter-draw--hidden');
            $('.filter-draw-overlay').addClass('active');


            if (Remarkable.isMobile) {
                $('.filter-container__controls').addClass('active');
                $(".filter-group__product-no").addClass("opened");
                $('body').addClass('cart-assist--hide');
            }

            listingPage.openFilterByType(id);
        });


        $(document).on('click', '.js-close-filters', function (e) {
            e.preventDefault();

            $('.filter-draw').addClass('filter-draw--hidden');
            $('.filter-draw-overlay').removeClass('active');

            if (Remarkable.isMobile) {
                $('.filter-container__controls').removeClass('active');
                $(".filter-group__product-no").removeClass("opened");
                $('body').removeClass('cart-assist--hide');
            }
        });
    };

    function _legacy() {
        $(".filter-group__title a").on('click', function (e) {
            e.preventDefault();
        });

        if ($('.horizontal-filter').length > 0) {

            showSelectedFilters();

            if (!Remarkable.isMobile) {

                $(document).click(function (e) {
                    if (!$(e.target).is('.panel-body')) {
                        $('.filter-container .collapse').collapse('hide');
                    }
                });

                $('.collapse').on('show.bs.collapse', function () {
                    $('.collapse.in').each(function () {
                        $(this).collapse('hide');
                    });
                });

                var offset = $('#showListings').offset(),
                    offsetTop = offset.top,
                    filterHeight = $('.horizontal-filter-container').height(),
                    setHeight = filterHeight + 'px';

                $('.horizontal-filter-container').css('min-height', setHeight);

                var elm = document.querySelector('.headroom');

                var filters = new Headroom(elm, {
                    tolerance: {
                        'up': 50,
                        'down': 20
                    },
                    offset: offsetTop,
                    classes: {
                        "initial": "headroom",
                        "pinned": "slideDown",
                        "unpinned": "slideUp"
                    },
                    onPin: function () {
                        $('.headroom').addClass('headroom--fixed');
                    },
                    onUnpin: function () {
                        $('.headroom').removeClass('headroom--fixed');
                    },
                    onTop: function () {
                        $('.headroom').removeClass('headroom--fixed');
                    }
                });

                filters.init();

                $(window).scroll(function () {
                    if (offsetTop > $(window).scrollTop()) {
                        $('.headroom').removeClass('headroom--fixed');
                    }
                });

            }    
        }

        var allOK = _checkOldUrls();

        SetupFullWidthOwl();
        listingPage.multipleSashes();

        // Re written the event handler
        var dynamicContent = $('.dynamicContent');

        if (allOK) {
            History.init();
        }

        History.Adapter.bind(window, 'statechange', function () { 
            loadNewContent(History.getState().url);
        });

        // Attach the ajax too all paging links
        $(document).on('click', '.paging-module a:not(.paging-module__style a), .filter-container a:not(.no-ajax)', function (e) {
            e.preventDefault(); // Prevent the page from doing a normal load
            e.stopPropagation(); // Fix for iOS standalone picking up the click aswell

            // Toggle the active state
            $(this).parent('li').toggleClass('active');

            // Setup local variables so GC can kickin later
            var loadUrl = $(this).attr('href');
            var isClearFilters = $(this).hasClass('js-clear-all-filters');

            if (isClearFilters) {
                listingPage.clearFilterState();
            }

            // Scroll to the top
            if ($(e.target).parents('.paging-module').length && !isLoading) {
                isLoading = true;

                // All this part is a mess and needs re-doing - Aaron
                if (Remarkable.isMobile) {

                    if (allOK) {
                        if ($(this).hasClass('js-load-more')) {
                            loadNewContent(loadUrl, true);
                        } else {
                            // Push the history state
                            History.pushState(null, "Loading...", loadUrl);
                        }
                    } else {
                        window.location = loadUrl;
                    }
                } else {

                    ScrollToElement(".dynamicContent", 15, function () {
                        if (allOK) {
                            // Push the history state
                            History.pushState(null, "Loading...", loadUrl);
                        } else {
                            window.location = loadUrl;
                        }
                    });
                }
            } else {

                $("html, body").animate({ scrollTop: 0 }, "slow");

                if (allOK) {
                    // Push the history state
                    History.pushState(null, "Loading...", loadUrl);
                } else {
                    window.location = loadUrl;
                }
            }

            var filterName = $(this).parents(".filter-group").data("id");
            var filterProp = $(this).attr('title');

            if (!$(this).parents(".paging-module").length && $(this).parents(".filter-group").length) {
                
                listingPage.countFilter(filterName);


                $(document).trigger("rc-filters-clicked", {
                    filterName: filterName,
                    filterProp: filterProp 
                });
            }
        });

        // Select all items to use ajax filter on (With value)
        dynamicContent.on('change', '.js-filter-select', function (e) {
            // Stops the page following the href
            e.preventDefault();

            $("html, body").animate({ scrollTop: 0 }, "slow");

            // store the url in var so we can use it if there is an error
            var loadUrl = $(this).val();

            if (allOK) {
                // Push the history state
                History.pushState(null, "Loading...", loadUrl);
            } else {
                window.location = loadUrl;
            }

            var filterName = $(this).parents(".filter-group").find("> .filter-group__title:eq(0)").text();
            var filterProperty = $(this).attr('title');


            if ($(this).data("filtername")) {
                filterName = $(this).data("filtername");
            }

            // Scroll to the top
            if (Remarkable.isMobile) {
                ScrollToElement(".dynamicContent", 106);
            } else {
                $("html, body").animate({ scrollTop: 0 }, "slow");
            }

            var filterSort = "OTHER";
            var filterOrder = "DESC";

            if (filterName == "sort by") {
                filterProperty = $('.paging-module__sort select :selected').text();

                if (filterProperty == "Price High To Low") {
                    filterSort = "PRICE";
                    filterOrder = "DESC";
                }

                if (filterProperty == "Price Low To High") {
                    filterSort = "PRICE";
                    filterOrder = "ASC";
                }

                if (filterProperty == "Top Selling First") {
                    filterSort = "POPULARITY";
                    filterOrder = "DESC";
                }

            }

            $(document).trigger("rc-filters-clicked", {
                filterName: filterName,
                filterProp: filterProperty,
                filterSort: filterSort,
                filterOrder: filterOrder
            });
        });


        // Check the initial page viewstate
        checkListingImages();

        //dynamicContent.on("click", ".js-toggle-filters", function (e) {
        //    e.preventDefault();

        //    ScrollToElement(".filter-container", 117);
        //    $(".filter-container").toggleClass("opened");
        //    $(".filter-group__product-no").toggleClass("opened");
        //    $('body').toggleClass('cart-assist--hide');

        //    var page = $(".page-container");
        //    page.toggleClass("prevent-scroll");
        //    listingPage.saveFilterState();

        //    Remarkable.startFilterURL = location.href;
        //});

        //dynamicContent.on("click", ".btn-close-filters", function (e) {
        //    e.preventDefault();
        //    $("html, body").animate({ scrollTop: 0 }, "slow");
        //});


        //dynamicContent.on("click", ".js-cancel-filters", function (e) {
        //    e.preventDefault();

        //    History.pushState(null, "Loading...", Remarkable.startFilterURL);

        //    localStorage.removeItem('mobileFilterStep');

        //    $(".filter-container").removeClass("opened");
        //    $(".filter-group__product-no").removeClass("opened");
        //    $('body').toggleClass('cart-assist--hide');
        //    $(".page-container").removeClass("prevent-scroll");

        //});

        //dynamicContent.on("click", ".filter-group__clear--all", function (e) {
        //    localStorage.removeItem('mobileFilterStep');
        //});

        //dynamicContent.on('shown.bs.collapse hidden.bs.collapse', ".filter-group .panel-collapse", function (e) {
        //    e.preventDefault();
        //    listingPage.saveFilterState();
        //});

        //listingPage.setFilterState();
        //listingPage.reorderFilters();

        //dynamicContent.on("click", ".js-view-mode", function (e) {
        //    e.preventDefault();

        //    var mode = $(this).data('mode');

        //    // Set the cookie for next time
        //    setCookie("viewStyle", mode);

        //    // Set the viewstate
        //    setViewButtonState();
        //    modelImageSwap(mode);

        //    $(document).trigger("rc-viewmode", {
        //        filterName: mode
        //    });
        //});

        //setTileCascade(300);

        var scrollElm = Remarkable.isMobile ? $(".page-container") : $(document);

        scrollElm.scroll(function (event) {
            requestAnimFrame(listingPage.checkLoadMore);
        });

        dynamicContent.on('click', '.js-clear-filter-customisation', function () {
            //listingPage.clearFilterState();
            //$(this).addClass('hidden');
            
            window.location.reload();
        });

        dynamicContent.on('click', '.js-show-modal', function () {
            var uv = window.original_uv || universal_variable;
            if ($(this).data('href').indexOf("quickview") > 0) {

                var fullListName = getProductListName($(this));

                $(document).trigger("rc-quickview", {
                    productID: $(this).parents('.associated-product').data('id'),
                    listName: fullListName
                });
            }
        });

        dynamicContent.on('click', '.filter-group__list li a', function (e) {
            var clickedCategory = $(this).parents('.filter-group__body').attr('id');
            localStorage.removeItem('mobileFilterStep');
            localStorage.setItem("mobileFilterStep", '#' + clickedCategory);
        });

    }

    listingPage.formCollectionCarousel = function () {

        var owl = $('.formal-collection-carosuel');

        owl.on('resized.owl.carousel', function (event) {

            var width = $('.formal-collection-carosuel').width();
 
            aspectRatio(width);
        });

        owl.on('initialized.owl.carousel', function (event) {

            var width = $('.formal-collection-carosuel').width();

            aspectRatio(width);    
            formal_collection_video();
          
        });

         owl.owlCarousel({
            items: 1,
            merge: true,
             loop: true,
             autoplay: true,
             autoplayTimeout: 10000, 
             margin: 10,
             nav: true,
             dots: true,
             video: true,
             lazyLoad: true,
             center: true, 
             responsive: {
                 
                 0: {
                     dots: false
                 },
      
                 768: {
                     dots: true
                 }
             }      
        });   

        $('.formal-collection__video, .js-scroll-formal-collection').on('click', function (e) {
            e.preventDefault();
           
            ScrollToElement(".listing-items");
        });

    };

    function royalAscot() {

        var owl = $('.royal-ascot__enclosure');
        var totalItems = $('.royal-ascot__enclosure .associated-product').length;

        owl.owlCarousel({
            slideSpeed: 300,
            paginationSpeed: 400,
            items: 1,
            loop: true,
            slideBy: 1,
            autoSize: true,
            lazyLoad: false,
            responsiveClass: true,
            responsive: {
                // breakpoint from 0 up
                0: {
                    nav: (totalItems > 2),
                    mouseDrag: true,
                    items: 1,
                    margin: 15,
                    center: true
                },
                // breakpoint from 480 up
                768: {
                    nav: (totalItems > 3),
                    mouseDrag: true,
                    items: 3,
                    margin: 20,
                    center: false
                },
                // breakpoint from 768 up
                992: {
                    nav: (totalItems > 4),
                    mouseDrag: true,
                    items: 4,
                    margin: 28,
                    center: false
                },
                // breakpoint from 1600 up
                1600: {
                    nav: (totalItems > 4),
                    mouseDrag: true,
                    items: 4,
                    margin: 28
                }
            }
        });

    }

    function aspectRatio(width) {
        var height = 0;
        // Work out the correct height based on aspect ratio
        if (Remarkable.isMobile) {

             height = (1050 / 630) * width;
        } else {

             height = (800 / 1570) * width;
        }

        $('.formal-collection__video').css('height', height);
    }

    function formal_collection_video() {
        var video = $('#video');

        if (Remarkable.isMobile) {
            video.prepend('<source src="https://moss-bros.s3.amazonaws.com/videos/processed/webm/Portrait%20Clip%20v2.webm" type="video/webm" media="screen and (max-width: 768px)"> <source src="https://moss-bros.s3.amazonaws.com/videos/processed/ogg/Portrait%20Clip%20v2.ogg" type="video/ogg" media="screen and (max-width: 768px)">  <source src="https://moss-bros.s3.amazonaws.com/videos/processed/mp4/Portrait%20Clip%20v2.mp4" type="video/mp4" media="screen and (max-width: 768px)">');
        } 

        var myPlayer = videojs("video", {}, function () {});
        myPlayer.play();
    }

    function checkListingImages(html) {

        var state = getCookie("viewStyle"),
            defaultState = "model";

        // Lets check if a cookie exists
        if (state != undefined) {
            var viewState = state;
            /* Since the function is built for clicking and this is running when the page loads, if the cookie is viewStyleModel 
             - we need to trick it into thinking we clicked it. */
            modelImageSwap(viewState, html)
        } else {
            // No cookie, let's set the default and no need to do anything else.
            setCookie("viewStyle", defaultState);
        }

    }

    function loadNewContent(url, appendContent) {
        var dynamicContent = $('.dynamicContent');
      
        document.title = "Loading...";

        if (!appendContent) {
            listingPage.AjaxShow();
        }

        $('.js-load-more').text('Loading...');

        $.ajax({
            url: url,
            success: function (data) {
                var pageTitle = $('input[name="ajaxTitle"]', data).val(),
                    html = $(data),
                    filterData = {},
                    filterCats = [],
                    filterOpen = $('.filter-group__title[aria-expanded="true"]').parent(),
                    filterGroups = html.find('.filter-draw-content .filter-group');

                filterGroups.each(function (i, group) {
                    var elm = $(group);
                    var filters = elm.find('li');

                    filterCats.push(elm.data('id'));
                    filterData[elm.data('id')] = [];

                    filters.each(function (i, filter) {

                        var item = $(filter);

                        filterData[elm.data('id')].push({
                            'id': item.data('id'),
                            'title': item.data('title'),
                            'url': item.data('url')
                        });
                    });
                });

                listingPage.updateUniversalVariable(html);

                if (appendContent) {
                    var paging = $('.paging-module:not(.paging-module--top-bar)', dynamicContent),
                        pagingContainer = paging.parent();

                        paging.remove();
                        pagingContainer.append(html.find('.listing-items').next());
                        $('.listing-items', dynamicContent).append(html.find('.listing-items').html());
                   
                } else {
                    dynamicContent.html(html.find('.dynamicContent').html());
                    
                    filterCats.forEach(function (cat) {
                        if (cat === filterOpen.data('id')) {
                            filterData[cat].forEach(function (item) {
                                $('[data-id=' + item.id + '] a').attr('href', item.url);
                            });
                        } else {
                            $('#filter-' + cat).html(html.find('#filter-' + cat ).html());
                        }
                    })

                    toggleClearFilters(true);

                }

                document.title = pageTitle;

                SetupFullWidthOwl();

                $('[data-toggle="tooltip"]').tooltip();


                listingPage.AjaxHide();
                checkListingImages();

                // Sometimes the lazyload bugs so we just call it again to ensure it works
                setTimeout(function () {
                    Unveil();
                }, 500);

                // Reinitialize the ajax-owl-carousels
                ajaxOwlCarousel.init($('.ajax-owl-carousel'));


                // Track the ajax page view
                $(document).trigger("rc-pageview", {
                    url: getPath(url),
                    title: pageTitle
                });

             
                //Fix position of multiple sashes in same space/time
                listingPage.multipleSashes();

                setTimeout(function () {
                    isLoading = false;
                }, 1000);

                showSelectedFilters();
                createFilterIndicators();

                listingPage.formCollectionCarousel();
                listingPage.initInfiniteScroll();

            },
            error: function () {
                window.location = url;
            }
        });
    }

    function toggleClearFilters(isVisible) {
        if (isVisible) {
            $('.filter-draw-header').addClass('filter-draw-header--clear-filter');
        } else {
            $('.filter-draw-header').removeClass('filter-draw-header--clear-filter');
        }
    }

    function setViewButtonState() {
        var mode = getCookie("viewStyle");
        var container = $('.paging-module__style');

        // Remove all active classes
        container.find('.paging-module__btn').removeClass('btn-primary');
        $('[data-mode="' + mode + '"]', container).addClass('btn-primary');
    }

    function modelImageSwap(state, html) {
        var listingContainer = ".listing-items";
        var stateClass = "state-" + state;
        var needsChanging = false;

        if ($(listingContainer + '[class*="state-"]').length) {
            if (!$(listingContainer).hasClass(stateClass)) {
                needsChanging = true;
            }
        } else if (state == "product") {
            needsChanging = true;
        }

        setViewButtonState()

        if (needsChanging) {
            // Unbind the click first
            UnbindImgHover();

            var imageCollection = $('.listing-items img[data-eimageswap]:not(.noswap)', html);

            imageCollection.each(function () {

                var img = $(this),
                    src = img.attr('src'),
                    dataSrc = !img.attr('data-src') ? img.attr('src') : img.attr('data-src'),
                    swap = img.attr('data-eimageswap');


                if (img.attr("src").indexOf("blank") != -1) {
                    img.attr("data-src", swap);
                    img.attr("data-eimageswap", dataSrc);
                } else {
                    img.attr("src", swap) // image is already loaded so just need to swap that aswell
                    img.attr("data-src", swap);
                    img.attr("data-eimageswap", dataSrc);
                }

            });

            // Set the state
            $(listingContainer).removeClass("state-model state-product").addClass(stateClass);
        }
    }

 
    function getParameterByName(name, location) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    function getPath(url) {
        var pathArray = url.split('/');
        var newPathname = "";

        for (var i = 3; i < pathArray.length; i++) {
            newPathname += "/";
            newPathname += pathArray[i];
        }

        return newPathname;
    }


    listingPage.openFilterByType = function (id) {

        setTimeout(function() { 
            $('.filter-group[data-id=' + id.toLowerCase() + '] .filter-group__title').trigger('click');
        }, 500)
    }

    listingPage.AjaxShow = function () {
        //NProgress.start();
        $('.ajaxLoaderOverlay').addClass("show");
    };

    listingPage.AjaxHide = function () {
        //NProgress.done();
        $('.ajaxLoaderOverlay').removeClass("show");
    };

    listingPage.getFilterOrder = function (states) {
        var statesToSort = states || listingPage.getFilterStateLS();
        var sortable = [];

        for (var filter in statesToSort)
            sortable.push([filter, statesToSort[filter].clicked ? statesToSort[filter].clicked : 0])

        return sortable.sort(function (a, b) {
            return a[1] - b[1]
        });
    };

    listingPage.reorderFilters = function (context, min) {
        var minimumClicks = min || 10;
        var filterWeights = listingPage.getFilterOrder();

        for (var i = 0; i < filterWeights.length; i++) {
            if (filterWeights[i][1] > minimumClicks) {
                $('[data-id="' + filterWeights[i][0] + '"]', context).parent().detach().insertAfter($(".filter-container > .col:first-of-type", context));
                $('.js-clear-filter-customisation', context).removeClass('hidden');
            }
        }
    };

    function _checkOldUrls() {
        var hrefLocation = window.location.href;

        if (hrefLocation.indexOf('#!') != -1) {
            var urlSplit = hrefLocation.split("#!");
            newURL = urlSplit[0] + urlSplit[1] + "&isOldUrl=true";
            window.location = newURL;
            return false;
        } else if (hrefLocation.indexOf('#mrasn') != -1) {
            return false;
        } else {
            return true;
        }
    }

    function showSelectedFilters() {

        $('.filter-group').each(function (e) {

            var hasSelected = $(this).find('li.active'),
                selected = $(this).find('.filter-group__title'),
                selectedgroup = $(this).find('.filter-group__body'),
                selectedTitle = selected.find('h3 span'),
                numberSelected = ' (' + hasSelected.length + ')';

            if (hasSelected.length > 0) {
                selected.addClass('filter-group__title--selected');
                selectedgroup.addClass('filter-group__body--selected');
                selectedTitle.html(numberSelected);
            } else {
                selectedTitle.html('');
            }

        });
    }


    listingPage.clearFilterState = function () {

        $('.filter-group__list li').removeClass('active');
        $('.filter-group__title h3 span').html('');
    };




    listingPage.getFilterState = function (context) {
        var data = {};

        $('.filter-group[data-id]', context).each(function (i, e) {
            data[$(this).data('id')] = { collapsed: $('.panel-collapse.collapse', this).hasClass('in') ? true : false };
        });

        $('.filter-container', context).each(function (i, e) {
            data[$(this).data('id')] = { collapsed: $(this).hasClass('opened') };
        });

        return data;
    };

    listingPage.saveFilterState = function (context) {
        var data = listingPage.getFilterState(context);

        try {
            if (window.localStorage) {
                var storedData = JSON.parse(localStorage.getItem('FilterState'))
                var newData = $.extend(true, storedData, data);

                localStorage.setItem('FilterState', JSON.stringify(newData));
            }
        } catch (e) {
            console.log(e);
        }
    };

    listingPage.getFilterStateLS = function () {
        try {
            if (window.localStorage && localStorage.getItem('FilterState')) {
                var data = JSON.parse(localStorage.getItem('FilterState'));
                return data;
            }

            return {}
        } catch (e) {
            return {}
        }
    }

    listingPage.updateUniversalVariable = function (context) {

        context.filter('.qubitPageUV').each(function () {
            $.globalEval(this.text || this.textContent || this.innerHTML || '');
        });
        checkQubit();
    };

    listingPage.setFilterState = function (context) {

        try {
            if (window.localStorage && localStorage.getItem('FilterState')) {
                var data = JSON.parse(localStorage.getItem('FilterState'));

                if (data['filtercontainer'].collapsed == true && context) {
                    $('.filter-container', context).addClass("opened");
                    $('.filter-group__product-no', context).addClass("opened");
                }

                for (var key in data) {
                    if (data.hasOwnProperty(key)) {
                        var value = data[key].collapsed;

                        var parent = $('.filter-group[data-id=' + key + ']', context);
                        $('.filter-group__title[data-toggle="collapse"]', parent).toggleClass('collapsed', !value).attr('aria-expanded', value);
                        $('.panel-collapse', parent).toggleClass('in', value);
                    }
                }


                //var self = $(this);
                //collapse = $('.filter-group__collapse');

                //self.children().toggleClass('open');

            }
        } catch (e) { }
    };

    listingPage.countFilter = function (name) {
        var newData = {};
        var data = listingPage.getFilterStateLS();
        
        newData[name] = {
            clicked: data[name] && data[name].clicked ? data[name].clicked + 1 : 1
        };

        var mergedData = $.extend(true, data, newData);

        localStorage.setItem('FilterState', JSON.stringify(mergedData));
    }

    var deltaFooter = 5,
        scrollTopFooter = 0,
        lastScrollTopFooter = 0;

    listingPage.stickyFooter = function () {
        scrollTopElm = Remarkable.isMobile ? $(".page-container") : $(document);
        scrollTopFooter = scrollTopElm.scrollTop();

        // Make sure they scroll more than delta
        if (Math.abs(lastScrollTopFooter - scrollTopFooter) <= deltaFooter)
            return;

        if (scrollTopFooter > lastScrollTopFooter) {
            $('.fixed-filters-xs').addClass('offscreen');
        } else {
            $('.fixed-filters-xs').removeClass('offscreen');
        }

        lastScrollTopFooter = scrollTopFooter;
    };

    var isLoading = false;
    listingPage.checkLoadMore = function () {
        var bottomOffset = 450,
            scrollTopElm = Remarkable.isMobile ? $(".page-container") : $(document);

        if (scrollTopElm.scrollTop() >= (scrollTopElm[0].scrollHeight - scrollTopElm.height()) - bottomOffset && !isLoading) {
            $('.js-load-more').trigger('click');
        }
    };

    listingPage.multipleSashes = function() {
        if (typeof resizeSashes != 'undefined') {
            window.removeEventListener('resize', resizeSashes);
        }
        var $banner = $('.associated-product__sash.bottom-center + .associated-product__sash.bottom-center');
        if ($banner.length > 1) {
            //Two sashes occupying same space/time, so bump one up
            var resizeSashes = Remarkable.debounce(function () {
                $banner.prev().css({
                    'bottom': $banner.height()
                });
            }, 250);
            resizeSashes();
            window.addEventListener('resize', resizeSashes);
        }
    }


    listingPage.initInfiniteScroll = function () {
        var page = window.location.href.includes('page=') ? parseInt(window.location.href.split('page=')[1].split('&')[0]) : 1;

        var infiniteScroll = new window.infiniteScroll({
            endpoint: window.location.href.split('?')[0],
            element: '.js-infinite-scroll',
            page: page,
            outputClass: '.listing-items',
            initialFetch: false,
            scrollContainer: '.mobile-scroll-container',
            dataLayer: false,
            totalPages: $('input[name="totalpages"]').val(),
            scrollOffset: 0,
            pagination: true
        });
    };


    //Filter Indicators
    function createFilterIndicators() {

        var activeFilters = $('.filter-container li.active a') 
        var indicatorList = $('.filter-indicators__list')                

        activeFilters.each(function () {
            var filterText = $(this).text().split('(')[0].trim();
            var link = $(this).attr('href');
            var newIndicator = '<li><a href="' + link +'" class="js-indicator-close"></a>' + filterText + '</li>';

            $(indicatorList).append(newIndicator);
            
        })

        indicatorList.addClass('visible');
        
    }

    createFilterIndicators();


    listingPage.exit = function () {
        console.log("Listing Page: Exit");
    };

    return listingPage;
}));;
