/*! Picturefill - v2.1.0 - 2014-07-25
* http://scottjehl.github.io/picturefill
* Copyright (c) 2014 https://github.com/scottjehl/picturefill/blob/master/Authors.txt; Licensed MIT */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */

window.matchMedia || (window.matchMedia = function () {
    "use strict";

    // For browsers that support matchMedium api such as IE 9 and webkit
    var styleMedia = (window.styleMedia || window.media);

    // For those that don't support matchMedium
    if (!styleMedia) {
        var style = document.createElement('style'),
            script = document.getElementsByTagName('script')[0],
            info = null;

        style.type = 'text/css';
        style.id = 'matchmediajs-test';

        script.parentNode.insertBefore(style, script);

        // 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers
        info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle;

        styleMedia = {
            matchMedium: function (media) {
                var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }';

                // 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
                if (style.styleSheet) {
                    style.styleSheet.cssText = text;
                } else {
                    style.textContent = text;
                }

                // Test if media query is true or false
                return info.width === '1px';
            }
        };
    }

    return function (media) {
        return {
            matches: styleMedia.matchMedium(media || 'all'),
            media: media || 'all'
        };
    };
}());
/*! Picturefill - Responsive Images that work today.
*  Author: Scott Jehl, Filament Group, 2012 ( new proposal implemented by Shawn Jansepar )
*  License: MIT/GPLv2
*  Spec: http://picture.responsiveimages.org/
*/
(function (w, doc) {
    // Enable strict mode
    "use strict";

    // If picture is supported, well, that's awesome. Let's get outta here...
    if (w.HTMLPictureElement) {
        w.picturefill = function () { };
        return;
    }

    // HTML shim|v it for old IE (IE9 will still need the HTML video tag workaround)
    doc.createElement("picture");

    // local object for method references and testing exposure
    var pf = {};

    // namespace
    pf.ns = "picturefill";

    // srcset support test
    pf.srcsetSupported = "srcset" in doc.createElement("img");
    pf.sizesSupported = w.HTMLImageElement.sizes;

    // just a string trim workaround
    pf.trim = function (str) {
        return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, "");
    };

    // just a string endsWith workaround
    pf.endsWith = function (str, suffix) {
        return str.endsWith ? str.endsWith(suffix) : str.indexOf(suffix, str.length - suffix.length) !== -1;
    };

	/**
	 * Shortcut method for matchMedia ( for easy overriding in tests )
	 */
    pf.matchesMedia = function (media) {
        return w.matchMedia && w.matchMedia(media).matches;
    };

	/**
	 * Shortcut method for `devicePixelRatio` ( for easy overriding in tests )
	 */
    pf.getDpr = function () {
        return (w.devicePixelRatio || 1);
    };

	/**
	 * Get width in css pixel value from a "length" value
	 * http://dev.w3.org/csswg/css-values-3/#length-value
	 */
    pf.getWidthFromLength = function (length) {
        // If no length was specified, or it is 0 or negative, default to `100vw` (per the spec).
        length = length && (parseFloat(length) > 0 || length.indexOf("calc(") > -1) ? length : "100vw";

		/**
		* If length is specified in  `vw` units, use `%` instead since the div we�re measuring
		* is injected at the top of the document.
		*
		* TODO: maybe we should put this behind a feature test for `vw`?
		*/
        length = length.replace("vw", "%");

        // Create a cached element for getting length value widths
        if (!pf.lengthEl) {
            pf.lengthEl = doc.createElement("div");
            doc.documentElement.insertBefore(pf.lengthEl, doc.documentElement.firstChild);
        }

        // Positioning styles help prevent padding/margin/width on `html` from throwing calculations off.
        pf.lengthEl.style.cssText = "position: absolute; left: 0; width: " + length + ";";

        if (pf.lengthEl.offsetWidth <= 0) {
            // Something has gone wrong. `calc()` is in use and unsupported, most likely. Default to `100vw` (`100%`, for broader support.):
            pf.lengthEl.style.cssText = "width: 100%;";
        }

        return pf.lengthEl.offsetWidth;
    };

    // container of supported mime types that one might need to qualify before using
    pf.types = {};

    // Add support for standard mime types.
    pf.types["image/jpeg"] = true;
    pf.types["image/gif"] = true;
    pf.types["image/png"] = true;

    // test svg support
    pf.types["image/svg+xml"] = doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image", "1.1");

    // test webp support, only when the markup calls for it
    pf.types["image/webp"] = function () {
        // based on Modernizr's lossless img-webp test
        // note: asynchronous
        var img = new w.Image(),
            type = "image/webp";

        img.onerror = function () {
            pf.types[type] = false;
            picturefill();
        };
        img.onload = function () {
            pf.types[type] = img.width === 1;
            picturefill();
        };
        img.src = "data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=";
    };

	/**
	 * Takes a source element and checks if its type attribute is present and if so, supported
	 * Note: for type tests that require a async logic,
	 * you can define them as a function that'll run only if that type needs to be tested. Just make the test function call picturefill again when it is complete.
	 * see the async webp test above for example
	 */
    pf.verifyTypeSupport = function (source) {
        var type = source.getAttribute("type");
        // if type attribute exists, return test result, otherwise return true
        if (type === null || type === "") {
            return true;
        } else {
            // if the type test is a function, run it and return "pending" status. The function will rerun picturefill on pending elements once finished.
            if (typeof (pf.types[type]) === "function") {
                pf.types[type]();
                return "pending";
            } else {
                return pf.types[type];
            }
        }
    };

	/**
	* Parses an individual `size` and returns the length, and optional media query
	*/
    pf.parseSize = function (sourceSizeStr) {
        var match = /(\([^)]+\))?\s*(.+)/g.exec(sourceSizeStr);
        return {
            media: match && match[1],
            length: match && match[2]
        };
    };

	/**
	 * Takes a string of sizes and returns the width in pixels as a number
	 */
    pf.findWidthFromSourceSize = function (sourceSizeListStr) {
        // Split up source size list, ie ( max-width: 30em ) 100%, ( max-width: 50em ) 50%, 33%
        //                            or (min-width:30em) calc(30% - 15px)
        var sourceSizeList = pf.trim(sourceSizeListStr).split(/\s*,\s*/),
            winningLength;

        for (var i = 0, len = sourceSizeList.length; i < len; i++) {
            // Match <media-condition>? length, ie ( min-width: 50em ) 100%
            var sourceSize = sourceSizeList[i],
                // Split "( min-width: 50em ) 100%" into separate strings
                parsedSize = pf.parseSize(sourceSize),
                length = parsedSize.length,
                media = parsedSize.media;

            if (!length) {
                continue;
            }
            if (!media || pf.matchesMedia(media)) {
                // if there is no media query or it matches, choose this as our winning length
                // and end algorithm
                winningLength = length;
                break;
            }
        }

        // pass the length to a method that can properly determine length
        // in pixels based on these formats: http://dev.w3.org/csswg/css-values-3/#length-value
        return pf.getWidthFromLength(winningLength);
    };

    pf.parseSrcset = function (srcset) {
		/**
		* A lot of this was pulled from Boris Smus� parser for the now-defunct WHATWG `srcset`
		* https://github.com/borismus/srcset-polyfill/blob/master/js/srcset-info.js
		*
		* 1. Let input (`srcset`) be the value passed to this algorithm.
		* 2. Let position be a pointer into input, initially pointing at the start of the string.
		* 3. Let raw candidates be an initially empty ordered list of URLs with associated 
		*    unparsed descriptors. The order of entries in the list is the order in which entries 
		*    are added to the list.
		*/
        var candidates = [];

        while (srcset !== "") {
            srcset = srcset.replace(/^\s+/g, "");

            // 5. Collect a sequence of characters that are not space characters, and let that be url.
            var pos = srcset.search(/\s/g),
                url, descriptor = null;

            if (pos !== -1) {
                url = srcset.slice(0, pos);

                var last = url[url.length - 1];

                // 6. If url ends with a U+002C COMMA character (,), remove that character from url
                // and let descriptors be the empty string. Otherwise, follow these substeps
                // 6.1. If url is empty, then jump to the step labeled descriptor parser.

                if (last === "," || url === "") {
                    url = url.replace(/,+$/, "");
                    descriptor = "";
                }
                srcset = srcset.slice(pos + 1);

                // 6.2. Collect a sequence of characters that are not U+002C COMMA characters (,), and 
                // let that be descriptors.
                if (descriptor === null) {
                    var descpos = srcset.indexOf(",");
                    if (descpos !== -1) {
                        descriptor = srcset.slice(0, descpos);
                        srcset = srcset.slice(descpos + 1);
                    } else {
                        descriptor = srcset;
                        srcset = "";
                    }
                }
            } else {
                url = srcset;
                srcset = "";
            }

            // 7. Add url to raw candidates, associated with descriptors.
            if (url || descriptor) {
                candidates.push({
                    url: url,
                    descriptor: descriptor
                });
            }
        }
        return candidates;
    };

    pf.parseDescriptor = function (descriptor, sizesattr) {
        // 11. Descriptor parser: Let candidates be an initially empty source set. The order of entries in the list 
        // is the order in which entries are added to the list.
        var sizes = sizesattr || "100vw",
            sizeDescriptor = descriptor && descriptor.replace(/(^\s+|\s+$)/g, ""),
            widthInCssPixels = pf.findWidthFromSourceSize(sizes),
            resCandidate;

        if (sizeDescriptor) {
            var splitDescriptor = sizeDescriptor.split(" ");

            for (var i = splitDescriptor.length + 1; i >= 0; i--) {
                if (splitDescriptor[i] !== undefined) {
                    var curr = splitDescriptor[i],
                        lastchar = curr && curr.slice(curr.length - 1);

                    if ((lastchar === "h" || lastchar === "w") && !pf.sizesSupported) {
                        resCandidate = parseFloat((parseInt(curr, 10) / widthInCssPixels));
                    } else if (lastchar === "x") {
                        var res = curr && parseFloat(curr, 10);
                        resCandidate = res && !isNaN(res) ? res : 1;
                    }
                }
            }
        }
        return resCandidate || 1;
    };

	/**
	 * Takes a srcset in the form of url/
	 * ex. "images/pic-medium.png 1x, images/pic-medium-2x.png 2x" or
	 *     "images/pic-medium.png 400w, images/pic-medium-2x.png 800w" or
	 *     "images/pic-small.png"
	 * Get an array of image candidates in the form of
	 *      {url: "/foo/bar.png", resolution: 1}
	 * where resolution is http://dev.w3.org/csswg/css-values-3/#resolution-value
	 * If sizes is specified, resolution is calculated
	 */
    pf.getCandidatesFromSourceSet = function (srcset, sizes) {
        var candidates = pf.parseSrcset(srcset),
            formattedCandidates = [];

        for (var i = 0, len = candidates.length; i < len; i++) {
            var candidate = candidates[i];

            formattedCandidates.push({
                url: candidate.url,
                resolution: pf.parseDescriptor(candidate.descriptor, sizes)
            });
        }
        return formattedCandidates;
    };

	/*
	 * if it's an img element and it has a srcset property,
	 * we need to remove the attribute so we can manipulate src
	 * (the property's existence infers native srcset support, and a srcset-supporting browser will prioritize srcset's value over our winning picture candidate)
	 * this moves srcset's value to memory for later use and removes the attr
	 */
    pf.dodgeSrcset = function (img) {
        if (img.srcset) {
            img[pf.ns].srcset = img.srcset;
            img.removeAttribute("srcset");
        }
    };

	/*
	 * Accept a source or img element and process its srcset and sizes attrs
	 */
    pf.processSourceSet = function (el) {
        var srcset = el.getAttribute("srcset"),
            sizes = el.getAttribute("sizes"),
            candidates = [];

        // if it's an img element, use the cached srcset property (defined or not)
        if (el.nodeName.toUpperCase() === "IMG" && el[pf.ns] && el[pf.ns].srcset) {
            srcset = el[pf.ns].srcset;
        }

        if (srcset) {
            candidates = pf.getCandidatesFromSourceSet(srcset, sizes);
        }
        return candidates;
    };

    pf.applyBestCandidate = function (candidates, picImg) {
        var candidate,
            length,
            bestCandidate;

        candidates.sort(pf.ascendingSort);

        length = candidates.length;
        bestCandidate = candidates[length - 1];

        for (var i = 0; i < length; i++) {
            candidate = candidates[i];
            if (candidate.resolution >= pf.getDpr()) {
                bestCandidate = candidate;
                break;
            }
        }

        if (bestCandidate && !pf.endsWith(picImg.src, bestCandidate.url)) {
            picImg.src = bestCandidate.url;
            // currentSrc attribute and property to match
            // http://picture.responsiveimages.org/#the-img-element
            picImg.currentSrc = picImg.src;
        }
    };

    pf.ascendingSort = function (a, b) {
        return a.resolution - b.resolution;
    };

	/*
	 * In IE9, <source> elements get removed if they aren't children of
	 * video elements. Thus, we conditionally wrap source elements
	 * using <!--[if IE 9]><video style="display: none;"><![endif]-->
	 * and must account for that here by moving those source elements
	 * back into the picture element.
	 */
    pf.removeVideoShim = function (picture) {
        var videos = picture.getElementsByTagName("video");
        if (videos.length) {
            var video = videos[0],
                vsources = video.getElementsByTagName("source");
            while (vsources.length) {
                picture.insertBefore(vsources[0], video);
            }
            // Remove the video element once we're finished removing its children
            video.parentNode.removeChild(video);
        }
    };

	/*
	 * Find all `img` elements, and add them to the candidate list if they have
	 * a `picture` parent, a `sizes` attribute in basic `srcset` supporting browsers,
	 * a `srcset` attribute at all, and they haven�t been evaluated already.
	 */
    pf.getAllElements = function () {
        var elems = [],
            imgs = doc.getElementsByTagName("img");

        for (var h = 0, len = imgs.length; h < len; h++) {
            var currImg = imgs[h];

            if (currImg.parentNode.nodeName.toUpperCase() === "PICTURE" ||
                (currImg.getAttribute("srcset") !== null) || currImg[pf.ns] && currImg[pf.ns].srcset !== null) {
                elems.push(currImg);
            }
        }
        return elems;
    };

    pf.getMatch = function (img, picture) {
        var sources = picture.childNodes,
            match;

        // Go through each child, and if they have media queries, evaluate them
        for (var j = 0, slen = sources.length; j < slen; j++) {
            var source = sources[j];

            // ignore non-element nodes
            if (source.nodeType !== 1) {
                continue;
            }

            // Hitting the `img` element that started everything stops the search for `sources`.
            // If no previous `source` matches, the `img` itself is evaluated later.
            if (source === img) {
                return match;
            }

            // ignore non-`source` nodes
            if (source.nodeName.toUpperCase() !== "SOURCE") {
                continue;
            }
            // if it's a source element that has the `src` property set, throw a warning in the console
            if (source.getAttribute("src") !== null && typeof console !== undefined) {
                console.warn("The `src` attribute is invalid on `picture` `source` element; instead, use `srcset`.");
            }

            var media = source.getAttribute("media");

            // if source does not have a srcset attribute, skip
            if (!source.getAttribute("srcset")) {
                continue;
            }

            // if there's no media specified, OR w.matchMedia is supported
            if ((!media || pf.matchesMedia(media))) {
                var typeSupported = pf.verifyTypeSupport(source);

                if (typeSupported === true) {
                    match = source;
                    break;
                } else if (typeSupported === "pending") {
                    return false;
                }
            }
        }

        return match;
    };

    function picturefill(opt) {
        var elements,
            element,
            parent,
            firstMatch,
            candidates,

            options = opt || {};
        elements = options.elements || pf.getAllElements();

        // Loop through all elements
        for (var i = 0, plen = elements.length; i < plen; i++) {
            element = elements[i];
            parent = element.parentNode;
            firstMatch = undefined;
            candidates = undefined;

            // expando for caching data on the img
            if (!element[pf.ns]) {
                element[pf.ns] = {};
            }

            // if the element has already been evaluated, skip it
            // unless `options.force` is set to true ( this, for example,
            // is set to true when running `picturefill` on `resize` ).
            if (!options.reevaluate && element[pf.ns].evaluated) {
                continue;
            }

            // if `img` is in a `picture` element
            if (parent.nodeName.toUpperCase() === "PICTURE") {

                // IE9 video workaround
                pf.removeVideoShim(parent);

                // return the first match which might undefined
                // returns false if there is a pending source
                // TODO the return type here is brutal, cleanup
                firstMatch = pf.getMatch(element, parent);

                // if any sources are pending in this picture due to async type test(s)
                // remove the evaluated attr and skip for now ( the pending test will
                // rerun picturefill on this element when complete)
                if (firstMatch === false) {
                    continue;
                }
            } else {
                firstMatch = undefined;
            }

            // Cache and remove `srcset` if present and we�re going to be doing `picture`/`srcset`/`sizes` polyfilling to it.
            if (parent.nodeName.toUpperCase() === "PICTURE" ||
                (element.srcset && !pf.srcsetSupported) ||
                (!pf.sizesSupported && (element.srcset && element.srcset.indexOf("w") > -1))) {
                pf.dodgeSrcset(element);
            }

            if (firstMatch) {
                candidates = pf.processSourceSet(firstMatch);
                pf.applyBestCandidate(candidates, element);
            } else {
                // No sources matched, so we�re down to processing the inner `img` as a source.
                candidates = pf.processSourceSet(element);

                if (element.srcset === undefined || element[pf.ns].srcset) {
                    // Either `srcset` is completely unsupported, or we need to polyfill `sizes` functionality.
                    pf.applyBestCandidate(candidates, element);
                } // Else, resolution-only `srcset` is supported natively.
            }

            // set evaluated to true to avoid unnecessary reparsing
            element[pf.ns].evaluated = true;
        }
    }

	/**
	 * Sets up picture polyfill by polling the document and running
	 * the polyfill every 250ms until the document is ready.
	 * Also attaches picturefill on resize
	 */
    function runPicturefill() {
        picturefill();
        var intervalId = setInterval(function () {
            // When the document has finished loading, stop checking for new images
            // https://github.com/ded/domready/blob/master/ready.js#L15
            picturefill();
            if (/^loaded|^i|^c/.test(doc.readyState)) {
                clearInterval(intervalId);
                return;
            }
        }, 250);
        if (w.addEventListener) {
            var resizeThrottle;
            w.addEventListener("resize", function () {
                if (!w._picturefillWorking) {
                    w._picturefillWorking = true;
                    w.clearTimeout(resizeThrottle);
                    resizeThrottle = w.setTimeout(function () {
                        picturefill({ reevaluate: true });
                        w._picturefillWorking = false;
                    }, 60);
                }
            }, false);
        }
    }

    runPicturefill();

    /* expose methods for testing */
    picturefill._ = pf;

    /* expose picturefill */
    if (typeof module === "object" && typeof module.exports === "object") {
        // CommonJS, just export
        module.exports = picturefill;
    } else if (typeof define === "function" && define.amd) {
        // AMD support
        define(function () { return picturefill; });
    } else if (typeof w === "object") {
        // If no AMD and we are in the browser, attach to window
        w.picturefill = picturefill;
    }

})(this, this.document);

/*! lazysizes - v1.1.3 -  Licensed MIT */
!function (a, b) { var c = b(a, a.document); a.lazySizes = c, "object" == typeof module && module.exports ? module.exports = c : "function" == typeof define && define.amd && define(c) }(window, function (a, b) { "use strict"; if (b.getElementsByClassName) { var c, d = b.documentElement, e = a.addEventListener, f = a.setTimeout, g = a.requestAnimationFrame || f, h = /^picture$/i, i = ["load", "error", "lazyincluded", "_lazyloaded"], j = function (a, b) { var c = new RegExp("(\\s|^)" + b + "(\\s|$)"); return a.className.match(c) && c }, k = function (a, b) { j(a, b) || (a.className += " " + b) }, l = function (a, b) { var c; (c = j(a, b)) && (a.className = a.className.replace(c, " ")) }, m = function (a, b, c) { var d = c ? "addEventListener" : "removeEventListener"; c && m(a, b), i.forEach(function (c) { a[d](c, b) }) }, n = function (a, c, d, e, f) { var g = b.createEvent("CustomEvent"); return g.initCustomEvent(c, !e, !f, d || {}), g.details = g.detail, a.dispatchEvent(g), g }, o = function (b, d) { var e; a.HTMLPictureElement || ((e = a.picturefill || a.respimage || c.pf) ? e({ reevaluate: !0, elements: [b] }) : d && d.src && (b.src = d.src)) }, p = function (a, b) { return getComputedStyle(a, null)[b] }, q = function (a, b, d) { for (d = d || a.offsetWidth; d < c.minSize && b && !a._lazysizesWidth;) d = b.offsetWidth, b = b.parentNode; return d }, r = function (b) { var d, e = 0, h = a.Date, i = function () { d = !1, e = h.now(), b() }, j = function () { f(i) }, k = function () { g(j) }; return function () { if (!d) { var a = c.throttle - (h.now() - e); d = !0, 9 > a && (a = 9), f(k, a) } } }, s = function () { var i, q, s, u, v, w, x, y, z, A, B, C, D, E = /^img$/i, F = /^iframe$/i, G = "onscroll" in a && !/glebot/.test(navigator.userAgent), H = 0, I = 0, J = 0, K = 1, L = function (a) { J--, a && a.target && m(a.target, L), (!a || 0 > J || !a.target) && (J = 0) }, M = function (a, b) { var c, d = a, e = "hidden" != p(a, "visibility"); for (y -= b, B += b, z -= b, A += b; e && (d = d.offsetParent) ;) e = (p(d, "opacity") || 1) > 0, e && "visible" != p(d, "overflow") && (c = d.getBoundingClientRect(), e = A > c.left && z < c.right && B > c.top - 1 && y < c.bottom + 1); return e }, N = function () { var a, b, d, e, f, g, h, j, k; if ((v = c.loadMode) && 8 > J && (a = i.length)) { for (b = 0, K++, D > I && 1 > J && K > 3 && v > 2 ? (I = D, K = 0) : I = I != C && v > 1 && K > 2 && 6 > J ? C : H; a > b; b++) i[b] && !i[b]._lazyRace && (G ? ((j = i[b].getAttribute("data-expand")) && (g = 1 * j) || (g = I), k !== g && (w = innerWidth + g, x = innerHeight + g, h = -1 * g, k = g), d = i[b].getBoundingClientRect(), (B = d.bottom) >= h && (y = d.top) <= x && (A = d.right) >= h && (z = d.left) <= w && (B || A || z || y) && (s && 3 > J && !j && (3 > v || 4 > K) || M(i[b], g)) ? (S(i[b], d.width), f = !0) : !f && s && !e && 3 > J && 4 > K && v > 2 && (q[0] || c.preloadAfterLoad) && (q[0] || !j && (B || A || z || y || "auto" != i[b].getAttribute(c.sizesAttr))) && (e = q[0] || i[b])) : S(i[b])); e && !f && S(e) } }, O = r(N), P = function (a) { k(a.target, c.loadedClass), l(a.target, c.loadingClass), m(a.target, P) }, Q = function (a, b) { try { a.contentWindow.location.replace(b) } catch (c) { a.setAttribute("src", b) } }, R = function () { var a, b = [], c = function () { for (; b.length;) b.shift()(); a = !1 }; return function (d) { b.push(d), a || (a = !0, g(c)) } }(), S = function (a, b) { var d, e, g, i, p, q, r, v, w, x, y, z = E.test(a.nodeName), A = a.getAttribute(c.sizesAttr) || a.getAttribute("sizes"), B = "auto" == A; (!B && s || !z || !a.src && !a.srcset || a.complete || j(a, c.errorClass)) && (a._lazyRace = !0, J++, R(function () { if (a._lazyRace && delete a._lazyRace, l(a, c.lazyClass), !(w = n(a, "lazybeforeunveil")).defaultPrevented) { if (A && (B ? (t.updateElem(a, !0, b), k(a, c.autosizesClass)) : a.setAttribute("sizes", A)), q = a.getAttribute(c.srcsetAttr), p = a.getAttribute(c.srcAttr), z && (r = a.parentNode, v = r && h.test(r.nodeName || "")), x = w.detail.firesLoad || "src" in a && (q || p || v), w = { target: a }, x && (m(a, L, !0), clearTimeout(u), u = f(L, 2500), k(a, c.loadingClass), m(a, P, !0)), v) for (d = r.getElementsByTagName("source"), e = 0, g = d.length; g > e; e++) (y = c.customMedia[d[e].getAttribute("data-media") || d[e].getAttribute("media")]) && d[e].setAttribute("media", y), i = d[e].getAttribute(c.srcsetAttr), i && d[e].setAttribute("srcset", i); q ? a.setAttribute("srcset", q) : p && (F.test(a.nodeName) ? Q(a, p) : a.setAttribute("src", p)), (q || v) && o(a, { src: p }) } (!x || a.complete) && (x ? L(w) : J--, P(w)) })) }, T = function () { var a, b = function () { c.loadMode = 3, O() }; s = !0, K += 8, c.loadMode = 3, e("scroll", function () { 3 == c.loadMode && (c.loadMode = 2), clearTimeout(a), a = f(b, 99) }, !0) }; return { _: function () { i = b.getElementsByClassName(c.lazyClass), q = b.getElementsByClassName(c.lazyClass + " " + c.preloadClass), C = c.expand, D = Math.round(C * c.expFactor), e("scroll", O, !0), e("resize", O, !0), a.MutationObserver ? new MutationObserver(O).observe(d, { childList: !0, subtree: !0, attributes: !0 }) : (d.addEventListener("DOMNodeInserted", O, !0), d.addEventListener("DOMAttrModified", O, !0), setInterval(O, 999)), e("hashchange", O, !0), ["focus", "mouseover", "click", "load", "transitionend", "animationend", "webkitAnimationEnd"].forEach(function (a) { b.addEventListener(a, O, !0) }), (s = /d$|^c/.test(b.readyState)) ? T() : (e("load", T), b.addEventListener("DOMContentLoaded", O)), O() }, checkElems: O, unveil: S } }(), t = function () { var a, d = function (a, b, c) { var d, e, f, g, i = a.parentNode; if (i && (c = q(a, i, c), g = n(a, "lazybeforesizes", { width: c, dataAttr: !!b }), !g.defaultPrevented && (c = g.detail.width, c && c !== a._lazysizesWidth))) { if (a._lazysizesWidth = c, c += "px", a.setAttribute("sizes", c), h.test(i.nodeName || "")) for (d = i.getElementsByTagName("source"), e = 0, f = d.length; f > e; e++) d[e].setAttribute("sizes", c); g.detail.dataAttr || o(a, g.detail) } }, f = function () { var b, c = a.length; if (c) for (b = 0; c > b; b++) d(a[b]) }, g = r(f); return { _: function () { a = b.getElementsByClassName(c.autosizesClass), e("resize", g) }, checkElems: g, updateElem: d } }(), u = function () { u.i || (u.i = !0, t._(), s._()) }; return function () { var b, d = { lazyClass: "lazyload", loadedClass: "lazyloaded", loadingClass: "lazyloading", preloadClass: "lazypreload", errorClass: "lazyerror", autosizesClass: "lazyautosizes", srcAttr: "data-src", srcsetAttr: "data-srcset", sizesAttr: "data-sizes", minSize: 40, customMedia: {}, init: !0, expFactor: 2, expand: 359, loadMode: 2, throttle: 125 }; c = a.lazySizesConfig || a.lazysizesConfig || {}; for (b in d) b in c || (c[b] = d[b]); a.lazySizesConfig = c, f(function () { c.init && u() }) }(), { cfg: c, autoSizer: t, loader: s, init: u, uP: o, aC: k, rC: l, hC: j, fire: n, gW: q } } });
/*! jCarousel - v0.3.9 - 2018-07-30
* http://sorgalla.com/jcarousel/
* Copyright (c) 2006-2018 Jan Sorgalla; Licensed MIT */

!function (t) { "use strict"; var i = t.jCarousel = {}; i.version = "0.3.9"; var s = /^([+\-]=)?(.+)$/; i.parseTarget = function (t) { var i = !1, e = "object" != typeof t ? s.exec(t) : null; return e ? (t = parseInt(e[2], 10) || 0, e[1] && (i = !0, "-=" === e[1] && (t *= -1))) : "object" != typeof t && (t = parseInt(t, 10) || 0), { target: t, relative: i } }, i.detectCarousel = function (t) { for (var i; t.length > 0;) { if ((i = t.filter("[data-jcarousel]")).length > 0) return i; if ((i = t.find("[data-jcarousel]")).length > 0) return i; t = t.parent() } return null }, i.base = function (s) { return { version: i.version, _options: {}, _element: null, _carousel: null, _init: t.noop, _create: t.noop, _destroy: t.noop, _reload: t.noop, create: function () { return this._element.attr("data-" + s.toLowerCase(), !0).data(s, this), !1 === this._trigger("create") ? this : (this._create(), this._trigger("createend"), this) }, destroy: function () { return !1 === this._trigger("destroy") ? this : (this._destroy(), this._trigger("destroyend"), this._element.removeData(s).removeAttr("data-" + s.toLowerCase()), this) }, reload: function (t) { return !1 === this._trigger("reload") ? this : (t && this.options(t), this._reload(), this._trigger("reloadend"), this) }, element: function () { return this._element }, options: function (i, s) { if (0 === arguments.length) return t.extend({}, this._options); if ("string" == typeof i) { if (void 0 === s) return void 0 === this._options[i] ? null : this._options[i]; this._options[i] = s } else this._options = t.extend({}, this._options, i); return this }, carousel: function () { return this._carousel || (this._carousel = i.detectCarousel(this.options("carousel") || this._element), this._carousel || t.error('Could not detect carousel for plugin "' + s + '"')), this._carousel }, _trigger: function (i, e, r) { var n, o = !1; return r = [this].concat(r || []), (e || this._element).each(function () { n = t.Event((s + ":" + i).toLowerCase()), t(this).trigger(n, r), n.isDefaultPrevented() && (o = !0) }), !o } } }, i.plugin = function (s, e) { var r = t[s] = function (i, s) { this._element = t(i), this.options(s), this._init(), this.create() }; return r.fn = r.prototype = t.extend({}, i.base(s), e), t.fn[s] = function (i) { var e = Array.prototype.slice.call(arguments, 1), n = this; return "string" == typeof i ? this.each(function () { var r = t(this).data(s); if (!r) return t.error("Cannot call methods on " + s + ' prior to initialization; attempted to call method "' + i + '"'); if (!t.isFunction(r[i]) || "_" === i.charAt(0)) return t.error('No such method "' + i + '" for ' + s + " instance"); var o = r[i].apply(r, e); return o !== r && void 0 !== o ? (n = o, !1) : void 0 }) : this.each(function () { var e = t(this).data(s); e instanceof r ? e.reload(i) : new r(this, i) }), n }, r } }(jQuery), function (t, i) { "use strict"; var s = t(i), e = function (t) { return parseFloat(t) || 0 }; t.jCarousel.plugin("jcarousel", { animating: !1, tail: 0, inTail: !1, resizeState: null, resizeTimer: null, lt: null, vertical: !1, rtl: !1, circular: !1, underflow: !1, relative: !1, _options: { list: function () { return this.element().children().eq(0) }, items: function () { return this.list().children() }, animation: 400, transitions: !1, wrap: null, vertical: null, rtl: null, center: !1 }, _list: null, _items: null, _target: t(), _first: t(), _last: t(), _visible: t(), _fullyvisible: t(), _init: function () { var t = this; return t.resizeState = s.width() + "x" + s.height(), this.onWindowResize = function () { t.resizeTimer && clearTimeout(t.resizeTimer), t.resizeTimer = setTimeout(function () { var i = s.width() + "x" + s.height(); i !== t.resizeState && (t.resizeState = i, t.reload()) }, 100) }, this }, _create: function () { this._reload(), s.on("resize.jcarousel", this.onWindowResize) }, _destroy: function () { s.off("resize.jcarousel", this.onWindowResize) }, _reload: function () { this.vertical = this.options("vertical"), null == this.vertical && (this.vertical = e(this.list().height()) > e(this.list().width())), this.rtl = this.options("rtl"), null == this.rtl && (this.rtl = function (i) { if ("rtl" === ("" + i.attr("dir")).toLowerCase()) return !0; var s = !1; return i.parents("[dir]").each(function () { if (/rtl/i.test(t(this).attr("dir"))) return s = !0, !1 }), s }(this._element)), this.lt = this.vertical ? "top" : "left", this.relative = "relative" === this.list().css("position"), this._list = null, this._items = null; var i = this.index(this._target) >= 0 ? this._target : this.closest(); this.circular = "circular" === this.options("wrap"), this.underflow = !1; var s = { left: 0, top: 0 }; return i.length > 0 && (this._prepare(i), this.list().find("[data-jcarousel-clone]").remove(), this._items = null, this.underflow = this._fullyvisible.length >= this.items().length, this.circular = this.circular && !this.underflow, s[this.lt] = this._position(i) + "px"), this.move(s), this }, list: function () { if (null === this._list) { var i = this.options("list"); this._list = t.isFunction(i) ? i.call(this) : this._element.find(i) } return this._list }, items: function () { if (null === this._items) { var i = this.options("items"); this._items = (t.isFunction(i) ? i.call(this) : this.list().find(i)).not("[data-jcarousel-clone]") } return this._items }, index: function (t) { return this.items().index(t) }, closest: function () { var i, s = this, r = this.list().position()[this.lt], n = t(), o = !1, l = this.vertical ? "bottom" : this.rtl && !this.relative ? "left" : "right"; return this.rtl && this.relative && !this.vertical && (r += e(this.list().width()) - this.clipping()), this.items().each(function () { if (n = t(this), o) return !1; var a = s.dimension(n); if ((r += a) >= 0) { if (i = a - e(n.css("margin-" + l)), !(Math.abs(r) - a + i / 2 <= 0)) return !1; o = !0 } }), n }, target: function () { return this._target }, first: function () { return this._first }, last: function () { return this._last }, visible: function () { return this._visible }, fullyvisible: function () { return this._fullyvisible }, hasNext: function () { if (!1 === this._trigger("hasnext")) return !0; var t = this.options("wrap"), i = this.items().length - 1, s = this.options("center") ? this._target : this._last; return !!(i >= 0 && !this.underflow && (t && "first" !== t || this.index(s) < i || this.tail && !this.inTail)) }, hasPrev: function () { if (!1 === this._trigger("hasprev")) return !0; var t = this.options("wrap"); return !!(this.items().length > 0 && !this.underflow && (t && "last" !== t || this.index(this._first) > 0 || this.tail && this.inTail)) }, clipping: function () { return e(this._element["inner" + (this.vertical ? "Height" : "Width")]()) }, dimension: function (t) { return e(t["outer" + (this.vertical ? "Height" : "Width")](!0)) }, scroll: function (i, s, e) { if (this.animating) return this; if (!1 === this._trigger("scroll", null, [i, s])) return this; t.isFunction(s) && (e = s, s = !0); var r = t.jCarousel.parseTarget(i); if (r.relative) { var n, o, l, a, h, u, c, f, d = this.items().length - 1, _ = Math.abs(r.target), p = this.options("wrap"); if (r.target > 0) { var g = this.index(this._last); if (g >= d && this.tail) this.inTail ? "both" === p || "last" === p ? this._scroll(0, s, e) : t.isFunction(e) && e.call(this, !1) : this._scrollTail(s, e); else if (n = this.index(this._target), this.underflow && n === d && ("circular" === p || "both" === p || "last" === p) || !this.underflow && g === d && ("both" === p || "last" === p)) this._scroll(0, s, e); else if (l = n + _, this.circular && l > d) { for (f = d, h = this.items().get(-1); f++ < l;)h = this.items().eq(0), (u = this._visible.index(h) >= 0) && h.after(h.clone(!0).attr("data-jcarousel-clone", !0)), this.list().append(h), u || ((c = {})[this.lt] = this.dimension(h), this.moveBy(c)), this._items = null; this._scroll(h, s, e) } else this._scroll(Math.min(l, d), s, e) } else if (this.inTail) this._scroll(Math.max(this.index(this._first) - _ + 1, 0), s, e); else if (o = this.index(this._first), n = this.index(this._target), l = (a = this.underflow ? n : o) - _, a <= 0 && (this.underflow && "circular" === p || "both" === p || "first" === p)) this._scroll(d, s, e); else if (this.circular && l < 0) { for (f = l, h = this.items().get(0); f++ < 0;) { h = this.items().eq(-1), (u = this._visible.index(h) >= 0) && h.after(h.clone(!0).attr("data-jcarousel-clone", !0)), this.list().prepend(h), this._items = null; var m = this.dimension(h); (c = {})[this.lt] = -m, this.moveBy(c) } this._scroll(h, s, e) } else this._scroll(Math.max(l, 0), s, e) } else this._scroll(r.target, s, e); return this._trigger("scrollend"), this }, moveBy: function (t, i) { var s = this.list().position(), r = 1, n = 0; return this.rtl && !this.vertical && (r = -1, this.relative && (n = e(this.list().width()) - this.clipping())), t.left && (t.left = e(s.left) + n + e(t.left) * r + "px"), t.top && (t.top = e(s.top) + n + e(t.top) * r + "px"), this.move(t, i) }, move: function (i, s) { s = s || {}; var e = this.options("transitions"), r = !!e, n = !!e.transforms, o = !!e.transforms3d, l = s.duration || 0, a = this.list(); if (!r && l > 0) a.animate(i, s); else { var h = s.complete || t.noop, u = {}; if (r) { var c = { transitionDuration: a.css("transitionDuration"), transitionTimingFunction: a.css("transitionTimingFunction"), transitionProperty: a.css("transitionProperty") }, f = h; h = function () { t(this).css(c), f.call(this) }, u = { transitionDuration: (l > 0 ? l / 1e3 : 0) + "s", transitionTimingFunction: e.easing || s.easing, transitionProperty: l > 0 ? n || o ? "all" : i.left ? "left" : "top" : "none", transform: "none" } } o ? u.transform = "translate3d(" + (i.left || 0) + "," + (i.top || 0) + ",0)" : n ? u.transform = "translate(" + (i.left || 0) + "," + (i.top || 0) + ")" : t.extend(u, i), r && l > 0 && a.one("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd", h), a.css(u), l <= 0 && a.each(function () { h.call(this) }) } }, _scroll: function (i, s, r) { if (this.animating) return t.isFunction(r) && r.call(this, !1), this; if ("object" != typeof i ? i = this.items().eq(i) : void 0 === i.jquery && (i = t(i)), 0 === i.length) return t.isFunction(r) && r.call(this, !1), this; this.inTail = !1, this._prepare(i); var n = this._position(i); if (n === e(this.list().position()[this.lt])) return t.isFunction(r) && r.call(this, !1), this; var o = {}; return o[this.lt] = n + "px", this._animate(o, s, r), this }, _scrollTail: function (i, s) { if (this.animating || !this.tail) return t.isFunction(s) && s.call(this, !1), this; var r = this.list().position()[this.lt]; this.rtl && this.relative && !this.vertical && (r += e(this.list().width()) - this.clipping()), this.rtl && !this.vertical ? r += this.tail : r -= this.tail, this.inTail = !0; var n = {}; return n[this.lt] = r + "px", this._update({ target: this._target.next(), fullyvisible: this._fullyvisible.slice(1).add(this._visible.last()) }), this._animate(n, i, s), this }, _animate: function (i, s, e) { if (e = e || t.noop, !1 === this._trigger("animate")) return e.call(this, !1), this; this.animating = !0; var r = this.options("animation"), n = t.proxy(function () { this.animating = !1; var t = this.list().find("[data-jcarousel-clone]"); t.length > 0 && (t.remove(), this._reload()), this._trigger("animateend"), e.call(this, !0) }, this), o = "object" == typeof r ? t.extend({}, r) : { duration: r }, l = o.complete || t.noop; return !1 === s ? o.duration = 0 : void 0 !== t.fx.speeds[o.duration] && (o.duration = t.fx.speeds[o.duration]), o.complete = function () { n(), l.call(this) }, this.move(i, o), this }, _prepare: function (i) { var s, r, n, o = this.index(i), l = o, a = this.dimension(i), h = this.clipping(), u = this.vertical ? "bottom" : this.rtl ? "left" : "right", c = this.options("center"), f = { target: i, first: i, last: i, visible: i, fullyvisible: a <= h ? i : t() }; if (c && (a /= 2, h /= 2), a < h) for (; ;) { if (0 === (s = this.items().eq(++l)).length) { if (!this.circular) break; if (s = this.items().eq(0), i.get(0) === s.get(0)) break; if ((r = this._visible.index(s) >= 0) && s.after(s.clone(!0).attr("data-jcarousel-clone", !0)), this.list().append(s), !r) { var d = {}; d[this.lt] = this.dimension(s), this.moveBy(d) } this._items = null } if (0 === (n = this.dimension(s))) break; if (a += n, f.last = s, f.visible = f.visible.add(s), a - e(s.css("margin-" + u)) <= h && (f.fullyvisible = f.fullyvisible.add(s)), a >= h) break } if (!this.circular && !c && a < h) for (l = o; !(--l < 0 || 0 === (s = this.items().eq(l)).length || 0 === (n = this.dimension(s)) || (a += n, f.first = s, f.visible = f.visible.add(s), a - e(s.css("margin-" + u)) <= h && (f.fullyvisible = f.fullyvisible.add(s)), a >= h));); return this._update(f), this.tail = 0, c || "circular" === this.options("wrap") || "custom" === this.options("wrap") || this.index(f.last) !== this.items().length - 1 || (a -= e(f.last.css("margin-" + u))) > h && (this.tail = a - h), this }, _position: function (t) { var i = this._first, s = e(i.position()[this.lt]), r = this.options("center"), n = r ? this.clipping() / 2 - this.dimension(i) / 2 : 0; return this.rtl && !this.vertical ? (this.relative ? s -= e(this.list().width()) - this.dimension(i) : s -= this.clipping() - this.dimension(i), s += n) : s -= n, !r && (this.index(t) > this.index(i) || this.inTail) && this.tail ? (s = this.rtl && !this.vertical ? s - this.tail : s + this.tail, this.inTail = !0) : this.inTail = !1, -s }, _update: function (i) { var s, e = this, r = { target: this._target, first: this._first, last: this._last, visible: this._visible, fullyvisible: this._fullyvisible }, n = this.index(i.first || r.first) < this.index(r.first), o = function (s) { var o = [], l = []; i[s].each(function () { r[s].index(this) < 0 && o.push(this) }), r[s].each(function () { i[s].index(this) < 0 && l.push(this) }), n ? o = o.reverse() : l = l.reverse(), e._trigger(s + "in", t(o)), e._trigger(s + "out", t(l)), e["_" + s] = i[s] }; for (s in i) o(s); return this } }) }(jQuery, window), function (t) { "use strict"; t.jcarousel.fn.scrollIntoView = function (i, s, e) { var r, n = t.jCarousel.parseTarget(i), o = this.index(this._fullyvisible.first()), l = this.index(this._fullyvisible.last()); if ((r = n.relative ? n.target < 0 ? Math.max(0, o + n.target) : l + n.target : "object" != typeof n.target ? n.target : this.index(n.target)) < o) return this.scroll(r, s, e); if (r >= o && r <= l) return t.isFunction(e) && e.call(this, !1), this; for (var a, h = this.items(), u = this.clipping(), c = this.vertical ? "bottom" : this.rtl ? "left" : "right", f = 0; 0 !== (a = h.eq(r)).length;) { if ((f += this.dimension(a)) >= u) { f - (parseFloat(a.css("margin-" + c)) || 0) !== u && r++; break } if (r <= 0) break; r-- } return this.scroll(r, s, e) } }(jQuery), function (t) { "use strict"; t.jCarousel.plugin("jcarouselControl", { _options: { target: "+=1", event: "click", method: "scroll" }, _active: null, _init: function () { this.onDestroy = t.proxy(function () { this._destroy(), this.carousel().one("jcarousel:createend", t.proxy(this._create, this)) }, this), this.onReload = t.proxy(this._reload, this), this.onEvent = t.proxy(function (i) { i.preventDefault(); var s = this.options("method"); t.isFunction(s) ? s.call(this) : this.carousel().jcarousel(this.options("method"), this.options("target")) }, this) }, _create: function () { this.carousel().one("jcarousel:destroy", this.onDestroy).on("jcarousel:reloadend jcarousel:scrollend", this.onReload), this._element.on(this.options("event") + ".jcarouselcontrol", this.onEvent), this._reload() }, _destroy: function () { this._element.off(".jcarouselcontrol", this.onEvent), this.carousel().off("jcarousel:destroy", this.onDestroy).off("jcarousel:reloadend jcarousel:scrollend", this.onReload) }, _reload: function () { var i, s = t.jCarousel.parseTarget(this.options("target")), e = this.carousel(); if (s.relative) i = e.jcarousel(s.target > 0 ? "hasNext" : "hasPrev"); else { var r = "object" != typeof s.target ? e.jcarousel("items").eq(s.target) : s.target; i = e.jcarousel("target").index(r) >= 0 } return this._active !== i && (this._trigger(i ? "active" : "inactive"), this._active = i), this } }) }(jQuery), function (t) { "use strict"; t.jCarousel.plugin("jcarouselPagination", { _options: { perPage: null, item: function (t) { return '<a href="#' + t + '">' + t + "</a>" }, event: "click", method: "scroll" }, _carouselItems: null, _pages: {}, _items: {}, _currentPage: null, _init: function () { this.onDestroy = t.proxy(function () { this._destroy(), this.carousel().one("jcarousel:createend", t.proxy(this._create, this)) }, this), this.onReload = t.proxy(this._reload, this), this.onScroll = t.proxy(this._update, this) }, _create: function () { this.carousel().one("jcarousel:destroy", this.onDestroy).on("jcarousel:reloadend", this.onReload).on("jcarousel:scrollend", this.onScroll), this._reload() }, _destroy: function () { this._clear(), this.carousel().off("jcarousel:destroy", this.onDestroy).off("jcarousel:reloadend", this.onReload).off("jcarousel:scrollend", this.onScroll), this._carouselItems = null }, _reload: function () { var i = this.options("perPage"); if (this._pages = {}, this._items = {}, t.isFunction(i) && (i = i.call(this)), null == i) this._pages = this._calculatePages(); else for (var s, e = parseInt(i, 10) || 0, r = this._getCarouselItems(), n = 1, o = 0; 0 !== (s = r.eq(o++)).length;)this._pages[n] ? this._pages[n] = this._pages[n].add(s) : this._pages[n] = s, o % e == 0 && n++; this._clear(); var l = this, a = this.carousel().data("jcarousel"), h = this._element, u = this.options("item"), c = this._getCarouselItems().length; t.each(this._pages, function (i, s) { var e = l._items[i] = t(u.call(l, i, s)); e.on(l.options("event") + ".jcarouselpagination", t.proxy(function () { var t = s.eq(0); if (a.circular) { var e = a.index(a.target()), r = a.index(t); parseFloat(i) > parseFloat(l._currentPage) ? r < e && (t = "+=" + (c - e + r)) : r > e && (t = "-=" + (e + (c - r))) } a[this.options("method")](t) }, l)), h.append(e) }), this._update() }, _update: function () { var i, s = this.carousel().jcarousel("target"); t.each(this._pages, function (t, e) { if (e.each(function () { if (s.is(this)) return i = t, !1 }), i) return !1 }), this._currentPage !== i && (this._trigger("inactive", this._items[this._currentPage]), this._trigger("active", this._items[i])), this._currentPage = i }, items: function () { return this._items }, reloadCarouselItems: function () { return this._carouselItems = null, this }, _clear: function () { this._element.empty(), this._currentPage = null }, _calculatePages: function () { for (var t, i, s = this.carousel().data("jcarousel"), e = this._getCarouselItems(), r = s.clipping(), n = 0, o = 0, l = 1, a = {}; 0 !== (t = e.eq(o++)).length;)n + (i = s.dimension(t)) > r && (l++ , n = 0), n += i, a[l] ? a[l] = a[l].add(t) : a[l] = t; return a }, _getCarouselItems: function () { return this._carouselItems || (this._carouselItems = this.carousel().jcarousel("items")), this._carouselItems } }) }(jQuery), function (t, i) { "use strict"; var s, e; t.each({ hidden: "visibilitychange", mozHidden: "mozvisibilitychange", msHidden: "msvisibilitychange", webkitHidden: "webkitvisibilitychange" }, function (t, r) { if (void 0 !== i[t]) return s = t, e = r, !1 }), t.jCarousel.plugin("jcarouselAutoscroll", { _options: { target: "+=1", interval: 3e3, autostart: !0, method: "scroll" }, _timer: null, _started: !1, _init: function () { this.onDestroy = t.proxy(function () { this._destroy(), this.carousel().one("jcarousel:createend", t.proxy(this._create, this)) }, this), this.onAnimateEnd = t.proxy(this._start, this), this.onVisibilityChange = t.proxy(function () { i[s] ? this._stop() : this._start() }, this) }, _create: function () { this.carousel().one("jcarousel:destroy", this.onDestroy), t(i).on(e, this.onVisibilityChange), this.options("autostart") && this.start() }, _destroy: function () { this._stop(), this.carousel().off("jcarousel:destroy", this.onDestroy), t(i).off(e, this.onVisibilityChange) }, _start: function () { if (this._stop(), this._started) return this.carousel().one("jcarousel:animateend", this.onAnimateEnd), this._timer = setTimeout(t.proxy(function () { this.carousel().jcarousel(this.options("method"), this.options("target")) }, this), this.options("interval")), this }, _stop: function () { return this._timer && (this._timer = clearTimeout(this._timer)), this.carousel().off("jcarousel:animateend", this.onAnimateEnd), this }, start: function () { return this._started = !0, this._start(), this }, stop: function () { return this._started = !1, this._stop(), this } }) }(jQuery, document);
/** ==========================================================

* jquery lightGallery.js v1.1.4
* http://sachinchoolur.github.io/lightGallery/
* Released under the MIT License - http://opensource.org/licenses/mit-license.html  ---- FREE ----

=========================================================/**/
;
(function ($) {
    "use strict";
    $.fn.lightGallery = function (options) {
        var defaults = {
            mode: 'slide',
            useCSS: true,
            cssEasing: 'ease', //'cubic-bezier(0.25, 0, 0.25, 1)',//
            easing: 'linear', //'for jquery animation',//
            speed: 600,
            addClass: '',

            closable: true,
            loop: false,
            auto: false,
            pause: 4000,
            escKey: true,
            controls: true,
            hideControlOnEnd: false,

            preload: 1, //number of preload slides. will exicute only after the current slide is fully loaded. ex:// you clicked on 4th image and if preload = 1 then 3rd slide and 5th slide will be loaded in the background after the 4th slide is fully loaded.. if preload is 2 then 2nd 3rd 5th 6th slides will be preloaded.. ... ...
            showAfterLoad: true,
            selector: null,
            index: false,

            lang: {
                allPhotos: 'All photos'
            },
            counter: false,

            exThumbImage: false,
            thumbnail: true,
            showThumbByDefault: false,
            animateThumb: true,
            currentPagerPosition: 'middle',
            thumbWidth: 100,
            thumbMargin: 5,


            mobileSrc: false,
            mobileSrcMaxWidth: 640,
            swipeThreshold: 50,
            enableTouch: true,
            enableDrag: true,

            vimeoColor: 'CCCCCC',
            videoAutoplay: true,
            videoMaxWidth: '855px',

            dynamic: false,
            dynamicEl: [],
            //callbacks

            onOpen: function (plugin) { },
            onSlideBefore: function (plugin) { },
            onSlideAfter: function (plugin) { },
            onSlideNext: function (plugin) { },
            onSlidePrev: function (plugin) { },
            onBeforeClose: function (plugin) { },
            onCloseAfter: function (plugin) { }
        },
            el = $(this),
            plugin = this,
            $children = null,
            index = 0,
            isActive = false,
            lightGalleryOn = false,
            isTouch = document.createTouch !== undefined || ('ontouchstart' in window) || ('onmsgesturechange' in window) || navigator.msMaxTouchPoints,
            $gallery, $galleryCont, $slider, $slide, $prev, $next, prevIndex, $thumb_cont, $thumb, windowWidth, interval, usingThumb = false,
            aTiming = false,
            aSpeed = false;
        var settings = $.extend(true, {}, defaults, options);
        var lightGallery = {
            init: function () {
                el.each(function () {
                    var $this = $(this);
                    if (settings.dynamic) {
                        $children = settings.dynamicEl;
                        index = 0;
                        prevIndex = index;
                        setUp.init(index);
                    } else {
                        if (settings.selector !== null) {
                            $children = $(settings.selector);
                        } else {
                            $children = $this.children();
                        }
                        $children.on('click', function (e) {
                            if (settings.selector !== null) {
                                $children = $(settings.selector);
                            } else {
                                $children = $this.children();
                            }
                            e.preventDefault();
                            e.stopPropagation();
                            index = $children.index(this);
                            prevIndex = index;
                            setUp.init(index);
                        });
                    }
                });
            }
        };
        var setUp = {
            init: function () {
                isActive = true;
                this.structure();
                this.getWidth();
                this.closeSlide();
                this.autoStart();
                this.counter();
                this.slideTo();
                this.buildThumbnail();
                this.keyPress();
                if (settings.index) {
                    this.slide(settings.index);
                    this.animateThumb(settings.index);
                } else {
                    this.slide(index);
                    this.animateThumb(index);
                }
                if (settings.enableDrag) {
                    this.touch();
                };
                if (settings.enableTouch) {
                    this.enableTouch();
                }

                setTimeout(function () {
                    $gallery.addClass('opacity');
                }, 50);
            },
            structure: function () {
                $('body').append('<div id="lightGallery-outer" class="' + settings.addClass + '"><div id="lightGallery-Gallery"><div id="lightGallery-slider"></div><a id="lightGallery-close" class="close"></a></div></div>').addClass('lightGallery');
                $galleryCont = $('#lightGallery-outer');
                $gallery = $('#lightGallery-Gallery');
                if (settings.showAfterLoad === true) {
                    $gallery.addClass('showAfterLoad');
                } 
                
                $slider = $gallery.find('#lightGallery-slider');
                var slideList = '';
                if (settings.dynamic) {
                    for (var i = 0; i < settings.dynamicEl.length; i++) {
                        slideList += '<div class="lightGallery-slide"></div>';
                    }
                } else {
                    $children.each(function () {
                        slideList += '<div class="lightGallery-slide"></div>';
                    });
                }
                $slider.append(slideList);
                $slide = $gallery.find('.lightGallery-slide');
            },
            closeSlide: function () {
                var $this = this;
                if (settings.closable) {
                    $('#lightGallery-outer')
                        .on('click', function (event) {
                            if ($(event.target).is('.lightGallery-slide')) {
                                plugin.destroy(false);
                            }
                        });
                }
                $('#lightGallery-close').bind('click touchend', function () {
                    plugin.destroy(false);
                });
            },
            getWidth: function () {
                var resizeWindow = function () {
                    windowWidth = $(window).width();
                };
                $(window).bind('resize.lightGallery', resizeWindow());
            },
            doCss: function () {
                var support = function () {
                    var transition = ['transition', 'MozTransition', 'WebkitTransition', 'OTransition', 'msTransition', 'KhtmlTransition'];
                    var root = document.documentElement;
                    for (var i = 0; i < transition.length; i++) {
                        if (transition[i] in root.style) {
                            return true;
                        }
                    }
                };
                if (settings.useCSS && support()) {
                    return true;
                }
                return false;
            },
            enableTouch: function () {
                var $this = this;
                if (isTouch) {
                    var startCoords = {},
                        endCoords = {};
                    $('body').on('touchstart.lightGallery', function (e) {
                        endCoords = e.originalEvent.targetTouches[0];
                        startCoords.pageX = e.originalEvent.targetTouches[0].pageX;
                        startCoords.pageY = e.originalEvent.targetTouches[0].pageY;
                    });
                    $('body').on('touchmove.lightGallery', function (e) {
                        var orig = e.originalEvent;
                        endCoords = orig.targetTouches[0];
                        e.preventDefault();
                    });
                    $('body').on('touchend.lightGallery', function (e) {
                        var distance = endCoords.pageX - startCoords.pageX,
                            swipeThreshold = settings.swipeThreshold;
                        if (distance >= swipeThreshold) {
                            $this.prevSlide();
                            clearInterval(interval);
                        } else if (distance <= -swipeThreshold) {
                            $this.nextSlide();
                            clearInterval(interval);
                        }
                    });
                }
            },
            touch: function () {
                var xStart, xEnd;
                var $this = this;
                $('.lightGallery').bind('mousedown', function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                    xStart = e.pageX;
                });
                $('.lightGallery').bind('mouseup', function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                    xEnd = e.pageX;
                    if (xEnd - xStart > 20) {
                        $this.prevSlide();
                    } else if (xStart - xEnd > 20) {
                        $this.nextSlide();
                    }
                });
            },
            isVideo: function (src, index) {
                var youtube = src.match(/\/\/(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=|embed\/)?([a-z0-9_\-]+)/i);
                var vimeo = src.match(/\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+)/i);
                var iframe = false;
                if (settings.dynamic) {
                    if (settings.dynamicEl[index].iframe == 'true') {
                        iframe = true;
                    }
                } else {
                    if ($children.eq(index).attr('data-iframe') == 'true') {
                        iframe = true;
                    }
                }
                if (youtube || vimeo || iframe) {
                    return true;
                }
            },
            loadVideo: function (src, _id) {
                var youtube = src.match(/\/\/(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=|embed\/)?([a-z0-9_\-]+)/i);
                var vimeo = src.match(/\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+)/i);
                var video = '';
                var a = '';
                if (youtube) {
                    if (settings.videoAutoplay === true && lightGalleryOn === false) {
                        a = '?autoplay=1&rel=0&wmode=opaque';
                    } else {
                        a = '?wmode=opaque';
                    }
                    video = '<iframe class="object" width="560" height="315" src="//www.youtube.com/embed/' + youtube[1] + a + '" frameborder="0" allowfullscreen></iframe>';
                } else if (vimeo) {
                    if (settings.videoAutoplay === true && lightGalleryOn === false) {
                        a = 'autoplay=1&amp;';
                    } else {
                        a = '';
                    }
                    video = '<iframe class="object" id="video' + _id + '" width="560" height="315"  src="http://player.vimeo.com/video/' + vimeo[1] + '?' + a + 'byline=0&amp;portrait=0&amp;color=' + settings.vimeoColor + '" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
                } else {
                    video = '<iframe class="object" frameborder="0" src="' + src + '"  allowfullscreen="true"></iframe>';
                }
                return '<div class="video_cont" style="max-width:' + settings.videoMaxWidth + ' !important;"><div class="video">' + video + '</div></div>';
            },
            addHtml: function (index) {
                var dataSubHtml = null;
                if (settings.dynamic) {
                    dataSubHtml = settings.dynamicEl[index]['sub-html'];
                } else {
                    dataSubHtml = $children.eq(index).attr('data-sub-html');
                }
                if (typeof dataSubHtml !== 'undefined' && dataSubHtml !== null) {
                    var fL = dataSubHtml.substring(0, 1);
                    if (fL == '.' || fL == '#') {
                        dataSubHtml = $(dataSubHtml).html();
                    } else {
                        dataSubHtml = dataSubHtml;
                    }
                    $slide.eq(index).append(dataSubHtml);
                }
            },
            preload: function (index) {
                var newIndex = index;
                for (var k = 0; k <= settings.preload; k++) {
                    if (k >= $children.length - index) {
                        break;
                    }
                    this.loadContent(newIndex + k, true);
                }
                for (var h = 0; h <= settings.preload; h++) {
                    if (newIndex - h < 0) {
                        break;
                    }
                    this.loadContent(newIndex - h, true);
                }
            },
            loadObj: function (r, index) {
                var $this = this;
                $slide.eq(index).find('.object').on('load error', function () {
                    $slide.eq(index).addClass('complete');
                });
                if (r === false) {
                    if (!$slide.eq(index).hasClass('complete')) {
                        $slide.eq(index).find('.object').on('load error', function () {
                            $this.preload(index);
                        });
                    } else {
                        $this.preload(index);
                    }
                }
            },
            loadContent: function (index, rec) {
                var $this = this;
                var i, j, l = $children.length - index;
                var src;

                if (settings.preload > $children.length) {
                    settings.preload = $children.length;
                }
                if (settings.mobileSrc === true && windowWidth <= settings.mobileSrcMaxWidth) {
                    if (settings.dynamic) {
                        src = settings.dynamicEl[index].mobileSrc;
                    } else {
                        src = $children.eq(index).attr('data-responsive-src');
                    }
                } else {
                    if (settings.dynamic) {
                        src = settings.dynamicEl[index].src;
                    } else {
                        src = $children.eq(index).attr('data-src');
                    }
                }
                var time = 0;
                if (rec === true) {
                    time = settings.speed + 400;
                }




                if (typeof src !== 'undefined' && src !== '') {
                    if (!$this.isVideo(src, index)) {
                        setTimeout(function () {
                            if (!$slide.eq(index).hasClass('loaded')) {
                                $slide.eq(index).prepend('<img class="object" src="' + src + '" />');
                                $this.addHtml(index);
                                $slide.eq(index).addClass('loaded');
                            }
                            $this.loadObj(rec, index);
                        }, time);
                    } else {
                        setTimeout(function () {
                            if (!$slide.eq(index).hasClass('loaded')) {
                                $slide.eq(index).prepend($this.loadVideo(src, index));
                                $this.addHtml(index);
                                $slide.eq(index).addClass('loaded');

                                if (settings.auto && settings.videoAutoplay === true) {
                                    clearInterval(interval);
                                }
                            }
                            $this.loadObj(rec, index);
                        }, time);

                    }
                } else {
                    setTimeout(function () {
                        if (!$slide.eq(index).hasClass('loaded')) {
                            var dataHtml = null;
                            if (settings.dynamic) {
                                dataHtml = settings.dynamicEl[index].html;
                            } else {
                                dataHtml = $children.eq(index).attr('data-html');
                            }
                            if (typeof dataHtml !== 'undefined' && dataHtml !== null) {
                                var fL = dataHtml.substring(0, 1);
                                if (fL == '.' || fL == '#') {
                                    dataHtml = $(dataHtml).html();
                                } else {
                                    dataHtml = dataHtml;
                                }
                            }
                            if (typeof dataHtml !== 'undefined' && dataHtml !== null) {
                                $slide.eq(index).append('<div class="video_cont" style="max-width:' + settings.videoMaxWidth + ' !important;"><div class="video">' + dataHtml + '</div></div>');
                            }
                            $this.addHtml(index);
                            $slide.eq(index).addClass('loaded complete');

                            if (settings.auto && settings.videoAutoplay === true) {
                                clearInterval(interval);
                            }
                        }
                        $this.loadObj(rec, index);
                    }, time);
                }

            },
            counter: function () {
                if (settings.counter === true) {
                    var slideCount = $("#lightGallery-slider > div").length;
                    $gallery.append("<div id='lightGallery_counter'><span id='lightGallery_counter_current'></span> / <span id='lightGallery_counter_all'>" + slideCount + "</span></div>");
                }
            },
            buildThumbnail: function () {
                if (settings.thumbnail === true && $children.length > 1) {
                    var $this = this,
                        $close = '<span class="close ib"><i class="bUi-iCn-rMv-16" aria-hidden="true"></i></span>';
                    if (settings.showThumbByDefault) {
                        $close = '<span class="close ib"><i class="bUi-iCn-rMv-16" aria-hidden="true"></i></span>';
                    }
                    $gallery.append('<div class="thumb_cont"><div class="thumb_info">' + $close + '</div><div class="thumb_inner"></div></div>');
                    $thumb_cont = $gallery.find('.thumb_cont');
                    $prev.after('<a class="cLthumb"></a>');
                    $prev.parent().addClass('hasThumb');
                    $gallery.find('.cLthumb').bind('click touchend', function () {
                        $gallery.addClass('open');
                        if ($this.doCss() && settings.mode === 'slide') {
                            $slide.eq(index).prevAll().removeClass('nextSlide').addClass('prevSlide');
                            $slide.eq(index).nextAll().removeClass('prevSlide').addClass('nextSlide');
                        }
                    });
                    $gallery.find('.thumb_cont .close').bind('click touchend', function () {
                        $gallery.removeClass('open');
                    });
                    var thumbInfo = $gallery.find('.thumb_info');
                    var $thumb_inner = $gallery.find('.thumb_inner');
                    var thumbList = '';
                    var thumbImg;
                    if (settings.dynamic) {
                        for (var i = 0; i < settings.dynamicEl.length; i++) {
                            thumbImg = settings.dynamicEl[i].thumb;
                            thumbList += '<div class="thumb"><img src="' + thumbImg + '" /></div>';
                        }
                    } else {
                        $children.each(function () {
                            if (settings.exThumbImage === false || typeof $(this).attr(settings.exThumbImage) == 'undefined' || $(this).attr(settings.exThumbImage) === null) {
                                thumbImg = $(this).find('img').attr('src');
                            } else {
                                thumbImg = $(this).attr(settings.exThumbImage);
                            }
                            thumbList += '<div class="thumb"><img src="' + thumbImg + '" /></div>';
                        });
                    }
                    $thumb_inner.append(thumbList);
                    $thumb = $thumb_inner.find('.thumb');
                    $thumb.css({
                        'margin-right': settings.thumbMargin + 'px',
                        'width': settings.thumbWidth + 'px'
                    });
                    if (settings.animateThumb === true) {
                        var width = ($children.length * (settings.thumbWidth + settings.thumbMargin));
                        $gallery.find('.thumb_inner').css({
                            'width': width + 'px',
                            'position': 'relative',
                            'transition-duration': settings.speed + 'ms'
                        });
                    }
                    $thumb.bind('click touchend', function () {
                        usingThumb = true;
                        var index = $(this).index();
                        $thumb.removeClass('active');
                        $(this).addClass('active');
                        $this.slide(index);
                        $this.animateThumb(index);
                        clearInterval(interval);
                    });
                    thumbInfo.prepend('<span class="ib count">' + settings.lang.allPhotos + ' (' + $thumb.length + ')</span>');
                    if (settings.showThumbByDefault) {
                        $gallery.addClass('open');
                    }
                }
            },
            animateThumb: function (index) {
                if (settings.animateThumb === true) {
                    var thumb_contW = $gallery.find('.thumb_cont').width();
                    var position;
                    switch (settings.currentPagerPosition) {
                        case 'left':
                            position = 0;
                            break;
                        case 'middle':
                            position = (thumb_contW / 2) - (settings.thumbWidth / 2);
                            break;
                        case 'right':
                            position = thumb_contW - settings.thumbWidth;
                    }
                    var left = ((settings.thumbWidth + settings.thumbMargin) * index - 1) - position;
                    var width = ($children.length * (settings.thumbWidth + settings.thumbMargin));
                    if (left > (width - thumb_contW)) {
                        left = width - thumb_contW;
                    }
                    if (left < 0) {
                        left = 0;
                    }
                    if (this.doCss()) {
                        $gallery.find('.thumb_inner').css('transform', 'translate3d(-' + left + 'px, 0px, 0px)');
                    } else {
                        $gallery.find('.thumb_inner').animate({
                            left: -left + "px"
                        }, settings.speed);
                    }
                }
            },
            slideTo: function () {
                var $this = this;
                if (settings.controls === true && $children.length > 1) {
                    $gallery.append('<div id="lightGallery-action"><a id="lightGallery-prev"></a><a id="lightGallery-next"></a></div>');
                    $prev = $gallery.find('#lightGallery-prev');
                    $next = $gallery.find('#lightGallery-next');
                    $prev.bind('click', function () {
                        $this.prevSlide();
                        clearInterval(interval);
                    });
                    $next.bind('click', function () {
                        $this.nextSlide();
                        clearInterval(interval);
                    });
                }
            },
            autoStart: function () {
                var $this = this;
                if (settings.auto === true) {
                    interval = setInterval(function () {
                        if (index + 1 < $children.length) {
                            index = index;
                        } else {
                            index = -1;
                        }
                        index++;
                        $this.slide(index);
                    }, settings.pause);
                }
            },
            keyPress: function () {
                var $this = this;
                $(window).bind('keyup.lightGallery', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (e.keyCode === 37) {
                        $this.prevSlide();
                        clearInterval(interval);
                    }
                    if (e.keyCode === 38 && settings.thumbnail === true && $children.length > 1) {
                        if (!$gallery.hasClass('open')) {
                            if ($this.doCss() && settings.mode === 'slide') {
                                $slide.eq(index).prevAll().removeClass('nextSlide').addClass('prevSlide');
                                $slide.eq(index).nextAll().removeClass('prevSlide').addClass('nextSlide');
                            }
                            $gallery.addClass('open');
                        }
                    } else if (e.keyCode === 39) {
                        $this.nextSlide();
                        clearInterval(interval);
                    }
                    if (e.keyCode === 40 && settings.thumbnail === true && $children.length > 1 && !settings.showThumbByDefault) {
                        if ($gallery.hasClass('open')) {
                            $gallery.removeClass('open');
                        }
                    } else if (settings.escKey === true && e.keyCode === 27) {
                        if (!settings.showThumbByDefault && $gallery.hasClass('open')) {
                            $gallery.removeClass('open');
                        } else {
                            plugin.destroy(false);
                        }
                    }
                });
            },
            nextSlide: function () {
                var $this = this;
                index = $slide.index($slide.eq(prevIndex));
                if (index + 1 < $children.length) {
                    index++;
                    $this.slide(index);
                } else {
                    if (settings.loop) {
                        index = 0;
                        $this.slide(index);
                    } else if (settings.thumbnail === true && $children.length > 1 && !settings.showThumbByDefault) {
                        $gallery.addClass('open');
                    } else {
                        $slide.eq(index).find('.object').addClass('rightEnd');
                        setTimeout(function () {
                            $slide.find('.object').removeClass('rightEnd');
                        }, 400);
                    }
                }
                $this.animateThumb(index);
                settings.onSlideNext.call(this, plugin);
            },
            prevSlide: function () {
                var $this = this;
                index = $slide.index($slide.eq(prevIndex));
                if (index > 0) {
                    index--;
                    $this.slide(index);
                } else {
                    if (settings.loop) {
                        index = $children.length - 1;
                        $this.slide(index);
                    } else if (settings.thumbnail === true && $children.length > 1 && !settings.showThumbByDefault) {
                        $gallery.addClass('open');
                    } else {
                        $slide.eq(index).find('.object').addClass('leftEnd');
                        setTimeout(function () {
                            $slide.find('.object').removeClass('leftEnd');
                        }, 400);
                    }
                }
                $this.animateThumb(index);
                settings.onSlidePrev.call(this, plugin);
            },
            slide: function (index) {
                var $this = this;
                if (lightGalleryOn) {
                    setTimeout(function () {
                        $this.loadContent(index, false);
                    }, settings.speed + 400);
                    if (!$slider.hasClass('on')) {
                        $slider.addClass('on');
                    }
                    if (this.doCss() && settings.speed !== '') {
                        if (!$slider.hasClass('speed')) {
                            $slider.addClass('speed');
                        }
                        if (aSpeed === false) {
                            $slider.css('transition-duration', settings.speed + 'ms');
                            aSpeed = true;
                        }
                    }
                    if (this.doCss() && settings.cssEasing !== '') {
                        if (!$slider.hasClass('timing')) {
                            $slider.addClass('timing');
                        }
                        if (aTiming === false) {
                            $slider.css('transition-timing-function', settings.cssEasing);
                            aTiming = true;
                        }
                    }
                    settings.onSlideBefore.call(this, plugin);
                } else {
                    $this.loadContent(index, false);
                }
                if (settings.mode === 'slide') {
                    var isiPad = navigator.userAgent.match(/iPad/i) !== null;
                    if (this.doCss() && !$slider.hasClass('slide') && !isiPad) {
                        $slider.addClass('slide');
                    } else if (this.doCss() && !$slider.hasClass('useLeft') && isiPad) {
                        $slider.addClass('useLeft');
                    }
                    /*                  if(this.doCss()){
                        $slider.css({ 'transform' : 'translate3d('+(-index*100)+'%, 0px, 0px)' });
                    }*/
                    if (!this.doCss() && !lightGalleryOn) {
                        $slider.css({
                            left: (-index * 100) + '%'
                        });
                        //$slide.eq(index).css('transition','none');
                    } else if (!this.doCss() && lightGalleryOn) {
                        $slider.animate({
                            left: (-index * 100) + '%'
                        }, settings.speed, settings.easing);
                    }
                } else if (settings.mode === 'fade') {
                    if (this.doCss() && !$slider.hasClass('fadeM')) {
                        $slider.addClass('fadeM');
                    } else if (!this.doCss() && !$slider.hasClass('animate')) {
                        $slider.addClass('animate');
                    }
                    if (!this.doCss() && !lightGalleryOn) {
                        $slide.fadeOut(100);
                        $slide.eq(index).fadeIn(100);
                    } else if (!this.doCss() && lightGalleryOn) {
                        $slide.eq(prevIndex).fadeOut(settings.speed, settings.easing);
                        $slide.eq(index).fadeIn(settings.speed, settings.easing);
                    }
                }
                if (index + 1 >= $children.length && settings.auto && settings.loop === false) {
                    clearInterval(interval);
                }
                $slide.eq(prevIndex).removeClass('current');
                $slide.eq(index).addClass('current');
                if (this.doCss() && settings.mode === 'slide') {
                    if (usingThumb === false) {
                        $('.prevSlide').removeClass('prevSlide');
                        $('.nextSlide').removeClass('nextSlide');
                        $slide.eq(index - 1).addClass('prevSlide');
                        $slide.eq(index + 1).addClass('nextSlide');
                    } else {
                        $slide.eq(index).prevAll().removeClass('nextSlide').addClass('prevSlide');
                        $slide.eq(index).nextAll().removeClass('prevSlide').addClass('nextSlide');
                    }
                }
                if (settings.thumbnail === true && $children.length > 1) {
                    $thumb.removeClass('active');
                    $thumb.eq(index).addClass('active');
                }
                if (settings.controls && settings.hideControlOnEnd && settings.loop === false && $children.length > 1) {
                    var l = $children.length;
                    l = parseInt(l) - 1;
                    if (index === 0) {
                        $prev.addClass('disabled');
                        $next.removeClass('disabled');
                    } else if (index === l) {
                        $prev.removeClass('disabled');
                        $next.addClass('disabled');
                    } else {
                        $prev.add($next).removeClass('disabled');
                    }
                }
                prevIndex = index;
                lightGalleryOn === false ? settings.onOpen.call(this, plugin) : settings.onSlideAfter.call(this, plugin);
                setTimeout(function () {
                    lightGalleryOn = true;
                });
                usingThumb = false;
                if (settings.counter) {
                    $("#lightGallery_counter_current").text(index + 1);
                }
                $(window).bind('resize.lightGallery', function () {
                    setTimeout(function () {
                        $this.animateThumb(index);
                    }, 200);
                });
            }
        };
        plugin.isActive = function () {
            if (isActive === true) {
                return true;
            } else {
                return false;
            }

        };
        plugin.destroy = function (d) {
            isActive = false;
            d = typeof d !== 'undefined' ? false : true;
            settings.onBeforeClose.call(this, plugin);
            var lightGalleryOnT = lightGalleryOn;
            lightGalleryOn = false;
            aTiming = false;
            aSpeed = false;
            usingThumb = false;
            clearInterval(interval);
            if (d === true) {
                $children.off('click touch touchstart');
            }
            $('.lightGallery').off('mousedown mouseup');
            $('body').off('touchstart.lightGallery touchmove.lightGallery touchend.lightGallery');
            $(window).off('resize.lightGallery keyup.lightGallery');
            if (lightGalleryOnT === true) {
                $gallery.addClass('fadeM');
                setTimeout(function () {
                    $galleryCont.remove();
                    $('body').removeClass('lightGallery');
                }, 500);
            }
            settings.onCloseAfter.call(this, plugin);
        };
        lightGallery.init();
        return this;
    };
}(jQuery));
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.mapView = window.eviivo.mapView ? window.eviivo.mapView : {};

window.eviivo.mapView = function ($) {

    var defaultOptions = {
        googleMapsApiUrl: null,
        lat: null,
        lng: null,
        resources: {
            switchToMap: "Switch to Map View",
            switchToImage: "Switch back to Image View"
        },
        showMapByDefault: true
    };
    var options;

	var isMapScriptLoaded = false;
	var $mapContainer;
    var $mapView;
    var map;
    
    ///<summary>Main init method of the eviivo.mapView object</summary>
    ///<param name="settings">external settings</param>
	function init(settings) {
	    //extend internal settings with external ones
	    options = $.extend(defaultOptions, settings);
	    $mapContainer = $("#map-canvas");
	    $mapView = $("#view-address");
	    
	    if (options.showMapByDefault) {
	        showMap();
	    } else {
	        $mapView.on("click", function() {
	            eviivo.popup.display({
	                html: "<div id='map-canvas'></div>",
	                bodyClass: "dialogue-map"
	            });

                $mapContainer = $(".mod-dialogueBox > #map-canvas");

	            showMap();
	        });
	    }
	}

    ///<summary>Callback method from google maps once the google maps api script is loaded</summary>
	function loadMap() {
	    if (typeof (google.maps.Map) === "function") {
	        //only add geo location if we have coordinates
	        if (options.lat != null && options.lng != null) {
	            var position = new google.maps.LatLng(options.lat, options.lng);
	            var mapOptions = {
	                zoom: 13,
	                center: position,
	                disableDoubleClickZoom: true,
	                scrollwheel: false,
	                mapTypeControl: false,
	                panControl: false
	                //zoomControl: false,
	                //streetViewControl: false
	            };
	            
	            map = new google.maps.Map($mapContainer[0], mapOptions);
	            var pin = new google.maps.Marker({ position: position, clickable: false, map: map, animation: google.maps.Animation.DROP });
	            google.maps.event.trigger(map, 'resize');
	            google.maps.event.addDomListener(window, 'resize', resizeGoogleMap);

	        } else {
	            console.log('eviivo warning: no location data.');
	        }
	    }
	}

	///<summary>Loading the google maps script</summary>
	function loadMapScript() {
	    if (options.googleMapsApiUrl != "" && options.googleMapsApiUrl != null) {
	        //use script tag appender (much safer and much simpler)
	        $(document.body).append($("<script src=\"" + options.googleMapsApiUrl + "window.eviivo.mapView.loadMap\" type=\"text/javascript\" />"));
	        isMapScriptLoaded = true;
	    }
	}

    function resizeGoogleMap(){
        var center = map.getCenter();
        google.maps.event.trigger(map, 'resize');
        map.setCenter(center);
    }

    ///<summary>Show map handler</summary>
	function showMap() {

        //load map and script if not done already; otherwise, just load map
        if (!isMapScriptLoaded) {
            loadMapScript();
        } else {
            loadMap();
        }
    }

	///<summary>Expose the internal "private" methods for external use (make them public)</summary>
	return {
	    init: init,
	    loadMap: loadMap
	};
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.stickyContainer = window.eviivo.stickyContainer ? window.eviivo.stickyContainer : {};

window.eviivo.stickyContainer = function ($) {

    var defaultOptions = {
        resources: {
            room: "Room",
            found: "found"
        }
    };
    var options;

    var $resultContainer;
    var $groupPriceLabel;
    var $groupContent;

    ///<summary>Main init method of the eviivo.stickyContainer object</summary>
    ///<param name="settings">external settings</param>
	function init(settings) {
	    //extend internal settings with external ones
	    options = $.extend(defaultOptions, settings);

	    $resultContainer = $("#mod-results");
	    $groupPriceLabel = $(".results-price label");
	    $groupContent = $(".group-content");

	    if ($(".radio-buttons").length > 0) {
	        showFoundRooms();
	    }
	}
    
    ///<summary>Shou found rooms</summary>
    function showFoundRooms() {
        var rooms = $groupContent.length;
        //clean all existing room group links
        $("div.mod-sticky-inner div.column a").remove();
        //loop through all rooms and autogenerate the group links in the header container
        for (var i = 1; i <= rooms; i++) {
            var roomsFound = $("#group-" + i + "-content section").length;
            $('<a/>', {
                id: ("group-" + i),
                href: ("#group-room-" + i),
                class: "target-scroll selected"
            }).html(options.resources.room + " " + i + " <span>(<i>" + roomsFound + "</i> " + options.resources.found + ")</span>").appendTo("div.mod-sticky-inner div.column:first-child");
        }
    }
  
	///<summary>Expose the internal "private" methods for external use (make them public)</summary>
	return {
	    init: init
	};
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.smoothScrolling = window.eviivo.smoothScrolling ? window.eviivo.smoothScrolling : {};

window.eviivo.smoothScrolling = function ($) {

    var defaultOptions = {
        resources: {
        }
    };
    var options;
    var bodyAnimation;

    ///<summary>Main init method of the eviivo.smoothScrolling object</summary>
    ///<param name="settings">external settings</param>
    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);

        $("body div.main").on("click", "a.target-scroll, #cheapestPriceCta", smoothScrollHandler);
        $("body div.main").on("click", "a.target-scroll, #view-address", smoothScrollHandler);
        $(document).on("scroll", toggleScrollTopLink);
        $("a[href='#top']").on("click", scrollToTop);
    }

    ///<summary>the "smooth scroll" action handler</summary>
    function smoothScrollHandler(e, callback, obj) {
        e.preventDefault();
        if (obj == null) {
            obj = this;
        }
        var hash = obj.hash ? obj.hash : $(obj).data("anchor");
        var hashTop = $(hash);
        if (hashTop.length > 0) {
            hashTop = hashTop.offset().top;
            var delta = $(document).height() - $(window).height();
            var dest = hashTop > delta ? delta : hashTop;

            if (callback == null) {
                $('html,body').animate({ scrollTop: dest }, 500, 'swing');
            } else {
                //go to destination
                $('html,body').animate({ scrollTop: dest }, 500, 'swing', callback);
            }

            window.location.hash = hash;
        }
        return false;
    }

    ///<summary>toggle scroll to top link display</summary>
    function toggleScrollTopLink() {
        var scroll = $(window).scrollTop();
        if (scroll >= 500) {
            $("html").removeClass("not-scrolled");
        } else {
            $("html").addClass("not-scrolled");
        }
    }

    ///<summary>scroll to top handler</summary>
    function scrollToTop() {
        $("html, body").animate({ scrollTop: 0 }, "slow");
        return false;
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        smoothScrollHandler: smoothScrollHandler
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.bookingFlow = window.eviivo.bookingFlow ? window.eviivo.bookingFlow : {};

window.eviivo.bookingFlow = function ($) {
    var defaultOptions = {
    };
    var options;

    var $bookButtons;
    var $submitForm;
    var $bookButtonMultiple;
    var $radioButtons;
    var $radioButtonLabels;
    var $radioButtonsInputs;
    var $stickyContainer;
    var $stickyContainerButton;
    var $showPricesButtons;
    var $viewportWidth;

    ///<summary>Main init method of the eviivo.bookingFlow object</summary>
    ///<param name="settings">external settings</param>
    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);

        $bookButtons = $("#mod-results div.results-price button.cp-button-book");
        $bookButtonMultyRoom = $("div.mod-sticky-inner button.cp-button");
        $bookButtonMultiple = $("#mod-results div.mod-sticky-inner");
        $submitForm = $("#submit-reservation");
        $radioButtons = $(".radio-buttons");
        $radioButtonLabels = $(".radio-buttons label");
        $radioButtonsInputs = $(".radio-buttons input");
        $stickyContainer = $("#mod-results .mod-sticky");
        $stickyContainerButton = $(".mod-sticky-inner button");
        $showPricesButtons = $("#mod-results div.results-price button.cp-button-showprices");
        $viewportWidth = $(window).width();

        $bookButtons.on("click", submitOrder);
        $bookButtonMultyRoom.on("click", submitMultiRoomOrder);

        if ($bookButtonMultiple.length > 0) {
            $bookButtonMultiple.on("click", selectMultipleOrder);
            $stickyContainerButton.on("click", submitForm);
            $radioButtonsInputs.on("change", groupPriceClickHandler);


            if ($radioButtons.length > 0) {
                $radioButtons.buttonset();
                $radioButtonLabels.on("click", selectorClickHandler);
                $radioButtonLabels.each(function () {
                    selectorClickHandler(this);
                });
            }
            $stickyContainer.fadeIn(600);
            groupPriceClickHandler();
        }

        $showPricesButtons.on("click", showStartDateCalendar);
    }

    ///<summary>handle room selection for group availability results</summary>
    function selectorClickHandler(e) {
        var elem = e != null ? e : this;
        var roomItem = $(elem).parents("section.results-item");
        roomItem.siblings().removeClass("results-item-gallery-selected");
        roomItem.addClass("results-item-gallery-selected");
    }

    ///<summary>Handle header group links click handler</summary>
    function groupPriceClickHandler() {
        selectMultipleOrder();

        var allProducts = $submitForm.find("input[name^='product']");
        var selectedProducts = $submitForm.find("input[name^='product'][value]");
        if (allProducts.length == selectedProducts.length) {
            $stickyContainerButton.removeAttr("disabled");
        } else {
            $stickyContainerButton.attr("disabled", "disabled");
        }
    }


    ///<summary>Google Analytics Tracking Event, when the user clicks book</summary>
    function trackPropertyViewBookEvent() {
        if (typeof ga != "undefined") {
            ga("send", "event", "ViewProperty", "Book");
            if (typeof ga.getByName == "function") {
                var propertyTracker = ga.getByName('propertyTracker');
                if (typeof propertyTracker != "undefined") {
                    ga("propertyTracker.send", "event", "ViewProperty", "Book");
                }
            }

        }
    }

    ///<summary></summary>
    function submitOrder() {
        trackPropertyViewBookEvent();
        var isInIframe = (window.location != window.parent.location) ? true : false;
        var productId = $(this).parents(".results-price").find("input[type='hidden']");

        if (isInIframe) {
            $submitForm.attr("target", "_top");
        }
        $submitForm.find("input[name^='product']").val(productId.val());
        submitForm();
    }


    function submitMultiRoomOrder() {
        trackPropertyViewBookEvent();
        var isInIframe = (window.location != window.parent.location) ? true : false;
        if (isInIframe) {
            $submitForm.attr("target", "_top");
        }
        submitForm();
    }

    ///<summary></summary>
    function selectMultipleOrder() {
        var selectedRoom = $("#mod-results").find("input[type='radio']:checked");
        selectedRoom.each(function (i, e) {
            var index = i + 1;
            var productId = $(e).parents(".results-price").find("input[type='hidden']");
            $submitForm.find("input[name^='product-" + index + "']").val(productId.val());
            var adults = $(e).parents(".group-content").find("input[name='adults']");
            $submitForm.find("input[name^='adults-" + index + "']").val(adults.val());
            var children = $(e).parents(".group-content").find("input[name='children']");
            $submitForm.find("input[name^='children-" + index + "']").val(children.val());
            var occupancyId = $(e).parents(".group-content").find("input[name='occupancy-id']");
            $submitForm.find("input[name^='occupancy-id-" + index + "']").val(occupancyId.val());
        });
    }

    ///<summary></summary>
    function submitForm() {
        $submitForm.attr("action", window.location.href);
        $submitForm.trigger("submit");
    }

    function showStartDateCalendar(e) {
        if (!$viewportWidth < 768) { //smaller than ipad
            eviivo.smoothScrolling.smoothScrollHandler(e, function () {
                //$startDate.datepicker("show");
            }, this);
        }
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init
    };
}(jQuery);
/*! Magnific Popup - v1.1.0 - 2016-02-20
* http://dimsemenov.com/plugins/magnific-popup/
* Copyright (c) 2016 Dmitry Semenov; */
; (function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module. 
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS 
        factory(require('jquery'));
    } else {
        // Browser globals 
        factory(window.jQuery || window.Zepto);
    }
}(function ($) {

    /*>>core*/
    /**
     * 
     * Magnific Popup Core JS file
     * 
     */


    /**
     * Private static constants
     */
    var CLOSE_EVENT = 'Close',
        BEFORE_CLOSE_EVENT = 'BeforeClose',
        AFTER_CLOSE_EVENT = 'AfterClose',
        BEFORE_APPEND_EVENT = 'BeforeAppend',
        MARKUP_PARSE_EVENT = 'MarkupParse',
        OPEN_EVENT = 'Open',
        CHANGE_EVENT = 'Change',
        NS = 'mfp',
        EVENT_NS = '.' + NS,
        READY_CLASS = 'mfp-ready',
        REMOVING_CLASS = 'mfp-removing',
        PREVENT_CLOSE_CLASS = 'mfp-prevent-close';


    /**
     * Private vars 
     */
    /*jshint -W079 */
    var mfp, // As we have only one instance of MagnificPopup object, we define it locally to not to use 'this'
        MagnificPopup = function () { },
        _isJQ = !!(window.jQuery),
        _prevStatus,
        _window = $(window),
        _document,
        _prevContentType,
        _wrapClasses,
        _currPopupType;


    /**
     * Private functions
     */
    var _mfpOn = function (name, f) {
        mfp.ev.on(NS + name + EVENT_NS, f);
    },
        _getEl = function (className, appendTo, html, raw) {
            var el = document.createElement('div');
            el.className = 'mfp-' + className;
            if (html) {
                el.innerHTML = html;
            }
            if (!raw) {
                el = $(el);
                if (appendTo) {
                    el.appendTo(appendTo);
                }
            } else if (appendTo) {
                appendTo.appendChild(el);
            }
            return el;
        },
        _mfpTrigger = function (e, data) {
            mfp.ev.triggerHandler(NS + e, data);

            if (mfp.st.callbacks) {
                // converts "mfpEventName" to "eventName" callback and triggers it if it's present
                e = e.charAt(0).toLowerCase() + e.slice(1);
                if (mfp.st.callbacks[e]) {
                    mfp.st.callbacks[e].apply(mfp, $.isArray(data) ? data : [data]);
                }
            }
        },
        _getCloseBtn = function (type) {
            if (type !== _currPopupType || !mfp.currTemplate.closeBtn) {
                mfp.currTemplate.closeBtn = $(mfp.st.closeMarkup.replace('%title%', mfp.st.tClose));
                _currPopupType = type;
            }
            return mfp.currTemplate.closeBtn;
        },
        // Initialize Magnific Popup only when called at least once
        _checkInstance = function () {
            if (!$.magnificPopup.instance) {
                /*jshint -W020 */
                mfp = new MagnificPopup();
                mfp.init();
                $.magnificPopup.instance = mfp;
            }
        },
        // CSS transition detection, http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr
        supportsTransitions = function () {
            var s = document.createElement('p').style, // 's' for style. better to create an element if body yet to exist
                v = ['ms', 'O', 'Moz', 'Webkit']; // 'v' for vendor

            if (s['transition'] !== undefined) {
                return true;
            }

            while (v.length) {
                if (v.pop() + 'Transition' in s) {
                    return true;
                }
            }

            return false;
        };



    /**
     * Public functions
     */
    MagnificPopup.prototype = {

        constructor: MagnificPopup,

        /**
         * Initializes Magnific Popup plugin. 
         * This function is triggered only once when $.fn.magnificPopup or $.magnificPopup is executed
         */
        init: function () {
            var appVersion = navigator.appVersion;
            mfp.isLowIE = mfp.isIE8 = document.all && !document.addEventListener;
            mfp.isAndroid = (/android/gi).test(appVersion);
            mfp.isIOS = (/iphone|ipad|ipod/gi).test(appVersion);
            mfp.supportsTransition = supportsTransitions();

            // We disable fixed positioned lightbox on devices that don't handle it nicely.
            // If you know a better way of detecting this - let me know.
            mfp.probablyMobile = (mfp.isAndroid || mfp.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent));
            _document = $(document);

            mfp.popupsCache = {};
        },

        /**
         * Opens popup
         * @param  data [description]
         */
        open: function (data) {

            var i;

            if (data.isObj === false) {
                // convert jQuery collection to array to avoid conflicts later
                mfp.items = data.items.toArray();

                mfp.index = 0;
                var items = data.items,
                    item;
                for (i = 0; i < items.length; i++) {
                    item = items[i];
                    if (item.parsed) {
                        item = item.el[0];
                    }
                    if (item === data.el[0]) {
                        mfp.index = i;
                        break;
                    }
                }
            } else {
                mfp.items = $.isArray(data.items) ? data.items : [data.items];
                mfp.index = data.index || 0;
            }

            // if popup is already opened - we just update the content
            if (mfp.isOpen) {
                mfp.updateItemHTML();
                return;
            }

            mfp.types = [];
            _wrapClasses = '';
            if (data.mainEl && data.mainEl.length) {
                mfp.ev = data.mainEl.eq(0);
            } else {
                mfp.ev = _document;
            }

            if (data.key) {
                if (!mfp.popupsCache[data.key]) {
                    mfp.popupsCache[data.key] = {};
                }
                mfp.currTemplate = mfp.popupsCache[data.key];
            } else {
                mfp.currTemplate = {};
            }



            mfp.st = $.extend(true, {}, $.magnificPopup.defaults, data);
            mfp.fixedContentPos = mfp.st.fixedContentPos === 'auto' ? !mfp.probablyMobile : mfp.st.fixedContentPos;

            if (mfp.st.modal) {
                mfp.st.closeOnContentClick = false;
                mfp.st.closeOnBgClick = false;
                mfp.st.showCloseBtn = false;
                mfp.st.enableEscapeKey = false;
            }


            // Building markup
            // main containers are created only once
            if (!mfp.bgOverlay) {

                // Dark overlay
                mfp.bgOverlay = _getEl('bg').on('click' + EVENT_NS, function () {
                    mfp.close();
                });

                mfp.wrap = _getEl('wrap').attr('tabindex', -1).on('click' + EVENT_NS, function (e) {
                    if (mfp._checkIfClose(e.target)) {
                        mfp.close();
                    }
                });

                mfp.container = _getEl('container', mfp.wrap);
            }

            mfp.contentContainer = _getEl('content');
            if (mfp.st.preloader) {
                mfp.preloader = _getEl('preloader', mfp.container, mfp.st.tLoading);
            }


            // Initializing modules
            var modules = $.magnificPopup.modules;
            for (i = 0; i < modules.length; i++) {
                var n = modules[i];
                n = n.charAt(0).toUpperCase() + n.slice(1);
                mfp['init' + n].call(mfp);
            }
            _mfpTrigger('BeforeOpen');


            if (mfp.st.showCloseBtn) {
                // Close button
                if (!mfp.st.closeBtnInside) {
                    mfp.wrap.append(_getCloseBtn());
                } else {
                    _mfpOn(MARKUP_PARSE_EVENT, function (e, template, values, item) {
                        values.close_replaceWith = _getCloseBtn(item.type);
                    });
                    _wrapClasses += ' mfp-close-btn-in';
                }
            }

            if (mfp.st.alignTop) {
                _wrapClasses += ' mfp-align-top';
            }



            if (mfp.fixedContentPos) {
                mfp.wrap.css({
                    overflow: mfp.st.overflowY,
                    overflowX: 'hidden',
                    overflowY: mfp.st.overflowY
                });
            } else {
                mfp.wrap.css({
                    top: _window.scrollTop(),
                    position: 'absolute'
                });
            }
            if (mfp.st.fixedBgPos === false || (mfp.st.fixedBgPos === 'auto' && !mfp.fixedContentPos)) {
                mfp.bgOverlay.css({
                    height: _document.height(),
                    position: 'absolute'
                });
            }



            if (mfp.st.enableEscapeKey) {
                // Close on ESC key
                _document.on('keyup' + EVENT_NS, function (e) {
                    if (e.keyCode === 27) {
                        mfp.close();
                    }
                });
            }

            _window.on('resize' + EVENT_NS, function () {
                mfp.updateSize();
            });


            if (!mfp.st.closeOnContentClick) {
                _wrapClasses += ' mfp-auto-cursor';
            }

            if (_wrapClasses)
                mfp.wrap.addClass(_wrapClasses);


            // this triggers recalculation of layout, so we get it once to not to trigger twice
            var windowHeight = mfp.wH = _window.height();


            var windowStyles = {};

            if (mfp.fixedContentPos) {
                if (mfp._hasScrollBar(windowHeight)) {
                    var s = mfp._getScrollbarSize();
                    if (s) {
                        windowStyles.marginRight = s;
                    }
                }
            }

            if (mfp.fixedContentPos) {
                if (!mfp.isIE7) {
                    windowStyles.overflow = 'hidden';
                } else {
                    // ie7 double-scroll bug
                    $('body, html').css('overflow', 'hidden');
                }
            }



            var classesToadd = mfp.st.mainClass;
            if (mfp.isIE7) {
                classesToadd += ' mfp-ie7';
            }
            if (classesToadd) {
                mfp._addClassToMFP(classesToadd);
            }

            // add content
            mfp.updateItemHTML();

            _mfpTrigger('BuildControls');

            // remove scrollbar, add margin e.t.c
            $('html').css(windowStyles);

            // add everything to DOM
            mfp.bgOverlay.add(mfp.wrap).prependTo(mfp.st.prependTo || $(document.body));

            // Save last focused element
            mfp._lastFocusedEl = document.activeElement;

            // Wait for next cycle to allow CSS transition
            setTimeout(function () {

                if (mfp.content) {
                    mfp._addClassToMFP(READY_CLASS);
                    mfp._setFocus();
                } else {
                    // if content is not defined (not loaded e.t.c) we add class only for BG
                    mfp.bgOverlay.addClass(READY_CLASS);
                }

                // Trap the focus in popup
                _document.on('focusin' + EVENT_NS, mfp._onFocusIn);

            }, 16);

            mfp.isOpen = true;
            mfp.updateSize(windowHeight);
            _mfpTrigger(OPEN_EVENT);

            return data;
        },

        /**
         * Closes the popup
         */
        close: function () {
            if (!mfp.isOpen) return;
            _mfpTrigger(BEFORE_CLOSE_EVENT);

            mfp.isOpen = false;
            // for CSS3 animation
            if (mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition) {
                mfp._addClassToMFP(REMOVING_CLASS);
                setTimeout(function () {
                    mfp._close();
                }, mfp.st.removalDelay);
            } else {
                mfp._close();
            }
        },

        /**
         * Helper for close() function
         */
        _close: function () {
            _mfpTrigger(CLOSE_EVENT);

            var classesToRemove = REMOVING_CLASS + ' ' + READY_CLASS + ' ';

            mfp.bgOverlay.detach();
            mfp.wrap.detach();
            mfp.container.empty();

            if (mfp.st.mainClass) {
                classesToRemove += mfp.st.mainClass + ' ';
            }

            mfp._removeClassFromMFP(classesToRemove);

            if (mfp.fixedContentPos) {
                var windowStyles = { marginRight: '' };
                if (mfp.isIE7) {
                    $('body, html').css('overflow', '');
                } else {
                    windowStyles.overflow = '';
                }
                $('html').css(windowStyles);
            }

            _document.off('keyup' + EVENT_NS + ' focusin' + EVENT_NS);
            mfp.ev.off(EVENT_NS);

            // clean up DOM elements that aren't removed
            mfp.wrap.attr('class', 'mfp-wrap').removeAttr('style');
            mfp.bgOverlay.attr('class', 'mfp-bg');
            mfp.container.attr('class', 'mfp-container');

            // remove close button from target element
            if (mfp.st.showCloseBtn &&
                (!mfp.st.closeBtnInside || mfp.currTemplate[mfp.currItem.type] === true)) {
                if (mfp.currTemplate.closeBtn)
                    mfp.currTemplate.closeBtn.detach();
            }


            if (mfp.st.autoFocusLast && mfp._lastFocusedEl) {
                $(mfp._lastFocusedEl).focus(); // put tab focus back
            }
            mfp.currItem = null;
            mfp.content = null;
            mfp.currTemplate = null;
            mfp.prevHeight = 0;

            _mfpTrigger(AFTER_CLOSE_EVENT);
        },

        updateSize: function (winHeight) {

            if (mfp.isIOS) {
                // fixes iOS nav bars https://github.com/dimsemenov/Magnific-Popup/issues/2
                var zoomLevel = document.documentElement.clientWidth / window.innerWidth;
                var height = window.innerHeight * zoomLevel;
                mfp.wrap.css('height', height);
                mfp.wH = height;
            } else {
                mfp.wH = winHeight || _window.height();
            }
            // Fixes #84: popup incorrectly positioned with position:relative on body
            if (!mfp.fixedContentPos) {
                mfp.wrap.css('height', mfp.wH);
            }

            _mfpTrigger('Resize');

        },

        /**
         * Set content of popup based on current index
         */
        updateItemHTML: function () {
            var item = mfp.items[mfp.index];

            // Detach and perform modifications
            mfp.contentContainer.detach();

            if (mfp.content)
                mfp.content.detach();

            if (!item.parsed) {
                item = mfp.parseEl(mfp.index);
            }

            var type = item.type;

            _mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : '', type]);
            // BeforeChange event works like so:
            // _mfpOn('BeforeChange', function(e, prevType, newType) { });

            mfp.currItem = item;

            if (!mfp.currTemplate[type]) {
                var markup = mfp.st[type] ? mfp.st[type].markup : false;

                // allows to modify markup
                _mfpTrigger('FirstMarkupParse', markup);

                if (markup) {
                    mfp.currTemplate[type] = $(markup);
                } else {
                    // if there is no markup found we just define that template is parsed
                    mfp.currTemplate[type] = true;
                }
            }

            if (_prevContentType && _prevContentType !== item.type) {
                mfp.container.removeClass('mfp-' + _prevContentType + '-holder');
            }

            var newContent = mfp['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, mfp.currTemplate[type]);
            mfp.appendContent(newContent, type);

            item.preloaded = true;

            _mfpTrigger(CHANGE_EVENT, item);
            _prevContentType = item.type;

            // Append container back after its content changed
            mfp.container.prepend(mfp.contentContainer);

            _mfpTrigger('AfterChange');
        },


        /**
         * Set HTML content of popup
         */
        appendContent: function (newContent, type) {
            mfp.content = newContent;

            if (newContent) {
                if (mfp.st.showCloseBtn && mfp.st.closeBtnInside &&
                    mfp.currTemplate[type] === true) {
                    // if there is no markup, we just append close button element inside
                    if (!mfp.content.find('.mfp-close').length) {
                        mfp.content.append(_getCloseBtn());
                    }
                } else {
                    mfp.content = newContent;
                }
            } else {
                mfp.content = '';
            }

            _mfpTrigger(BEFORE_APPEND_EVENT);
            mfp.container.addClass('mfp-' + type + '-holder');

            mfp.contentContainer.append(mfp.content);
        },


        /**
         * Creates Magnific Popup data object based on given data
         * @param  {int} index Index of item to parse
         */
        parseEl: function (index) {
            var item = mfp.items[index],
                type;

            if (item.tagName) {
                item = { el: $(item) };
            } else {
                type = item.type;
                item = { data: item, src: item.src };
            }

            if (item.el) {
                var types = mfp.types;

                // check for 'mfp-TYPE' class
                for (var i = 0; i < types.length; i++) {
                    if (item.el.hasClass('mfp-' + types[i])) {
                        type = types[i];
                        break;
                    }
                }

                item.src = item.el.attr('data-mfp-src');
                if (!item.src) {
                    item.src = item.el.attr('href');
                }
            }

            item.type = type || mfp.st.type || 'inline';
            item.index = index;
            item.parsed = true;
            mfp.items[index] = item;
            _mfpTrigger('ElementParse', item);

            return mfp.items[index];
        },


        /**
         * Initializes single popup or a group of popups
         */
        addGroup: function (el, options) {
            var eHandler = function (e) {
                e.mfpEl = this;
                mfp._openClick(e, el, options);
            };

            if (!options) {
                options = {};
            }

            var eName = 'click.magnificPopup';
            options.mainEl = el;

            if (options.items) {
                options.isObj = true;
                el.off(eName).on(eName, eHandler);
            } else {
                options.isObj = false;
                if (options.delegate) {
                    el.off(eName).on(eName, options.delegate, eHandler);
                } else {
                    options.items = el;
                    el.off(eName).on(eName, eHandler);
                }
            }
        },
        _openClick: function (e, el, options) {
            var midClick = options.midClick !== undefined ? options.midClick : $.magnificPopup.defaults.midClick;


            if (!midClick && (e.which === 2 || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey)) {
                return;
            }

            var disableOn = options.disableOn !== undefined ? options.disableOn : $.magnificPopup.defaults.disableOn;

            if (disableOn) {
                if ($.isFunction(disableOn)) {
                    if (!disableOn.call(mfp)) {
                        return true;
                    }
                } else { // else it's number
                    if (_window.width() < disableOn) {
                        return true;
                    }
                }
            }

            if (e.type) {
                e.preventDefault();

                // This will prevent popup from closing if element is inside and popup is already opened
                if (mfp.isOpen) {
                    e.stopPropagation();
                }
            }

            options.el = $(e.mfpEl);
            if (options.delegate) {
                options.items = el.find(options.delegate);
            }
            mfp.open(options);
        },


        /**
         * Updates text on preloader
         */
        updateStatus: function (status, text) {

            if (mfp.preloader) {
                if (_prevStatus !== status) {
                    mfp.container.removeClass('mfp-s-' + _prevStatus);
                }

                if (!text && status === 'loading') {
                    text = mfp.st.tLoading;
                }

                var data = {
                    status: status,
                    text: text
                };
                // allows to modify status
                _mfpTrigger('UpdateStatus', data);

                status = data.status;
                text = data.text;

                mfp.preloader.html(text);

                mfp.preloader.find('a').on('click', function (e) {
                    e.stopImmediatePropagation();
                });

                mfp.container.addClass('mfp-s-' + status);
                _prevStatus = status;
            }
        },


        /*
            "Private" helpers that aren't private at all
         */
        // Check to close popup or not
        // "target" is an element that was clicked
        _checkIfClose: function (target) {

            if ($(target).hasClass(PREVENT_CLOSE_CLASS)) {
                return;
            }

            var closeOnContent = mfp.st.closeOnContentClick;
            var closeOnBg = mfp.st.closeOnBgClick;

            if (closeOnContent && closeOnBg) {
                return true;
            } else {

                // We close the popup if click is on close button or on preloader. Or if there is no content.
                if (!mfp.content || $(target).hasClass('mfp-close') || (mfp.preloader && target === mfp.preloader[0])) {
                    return true;
                }

                // if click is outside the content
                if ((target !== mfp.content[0] && !$.contains(mfp.content[0], target))) {
                    if (closeOnBg) {
                        // last check, if the clicked element is in DOM, (in case it's removed onclick)
                        if ($.contains(document, target)) {
                            return true;
                        }
                    }
                } else if (closeOnContent) {
                    return true;
                }

            }
            return false;
        },
        _addClassToMFP: function (cName) {
            mfp.bgOverlay.addClass(cName);
            mfp.wrap.addClass(cName);
        },
        _removeClassFromMFP: function (cName) {
            this.bgOverlay.removeClass(cName);
            mfp.wrap.removeClass(cName);
        },
        _hasScrollBar: function (winHeight) {
            return ((mfp.isIE7 ? _document.height() : document.body.scrollHeight) > (winHeight || _window.height()));
        },
        _setFocus: function () {
            (mfp.st.focus ? mfp.content.find(mfp.st.focus).eq(0) : mfp.wrap).focus();
        },
        _onFocusIn: function (e) {
            if (e.target !== mfp.wrap[0] && !$.contains(mfp.wrap[0], e.target)) {
                mfp._setFocus();
                return false;
            }
        },
        _parseMarkup: function (template, values, item) {
            var arr;
            if (item.data) {
                values = $.extend(item.data, values);
            }
            _mfpTrigger(MARKUP_PARSE_EVENT, [template, values, item]);

            $.each(values, function (key, value) {
                if (value === undefined || value === false) {
                    return true;
                }
                arr = key.split('_');
                if (arr.length > 1) {
                    var el = template.find(EVENT_NS + '-' + arr[0]);

                    if (el.length > 0) {
                        var attr = arr[1];
                        if (attr === 'replaceWith') {
                            if (el[0] !== value[0]) {
                                el.replaceWith(value);
                            }
                        } else if (attr === 'img') {
                            if (el.is('img')) {
                                el.attr('src', value);
                            } else {
                                el.replaceWith($('<img>').attr('src', value).attr('class', el.attr('class')));
                            }
                        } else {
                            el.attr(arr[1], value);
                        }
                    }

                } else {
                    template.find(EVENT_NS + '-' + key).html(value);
                }
            });
        },

        _getScrollbarSize: function () {
            // thx David
            if (mfp.scrollbarSize === undefined) {
                var scrollDiv = document.createElement("div");
                scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
                document.body.appendChild(scrollDiv);
                mfp.scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth;
                document.body.removeChild(scrollDiv);
            }
            return mfp.scrollbarSize;
        }

    }; /* MagnificPopup core prototype end */




    /**
     * Public static functions
     */
    $.magnificPopup = {
        instance: null,
        proto: MagnificPopup.prototype,
        modules: [],

        open: function (options, index) {
            _checkInstance();

            if (!options) {
                options = {};
            } else {
                options = $.extend(true, {}, options);
            }

            options.isObj = true;
            options.index = index || 0;
            return this.instance.open(options);
        },

        close: function () {
            return $.magnificPopup.instance && $.magnificPopup.instance.close();
        },

        registerModule: function (name, module) {
            if (module.options) {
                $.magnificPopup.defaults[name] = module.options;
            }
            $.extend(this.proto, module.proto);
            this.modules.push(name);
        },

        defaults: {

            // Info about options is in docs:
            // http://dimsemenov.com/plugins/magnific-popup/documentation.html#options

            disableOn: 0,

            key: null,

            midClick: false,

            mainClass: '',

            preloader: true,

            focus: '', // CSS selector of input to focus after popup is opened

            closeOnContentClick: false,

            closeOnBgClick: true,

            closeBtnInside: true,

            showCloseBtn: true,

            enableEscapeKey: true,

            modal: false,

            alignTop: false,

            removalDelay: 0,

            prependTo: null,

            fixedContentPos: 'auto',

            fixedBgPos: 'auto',

            overflowY: 'auto',

            closeMarkup: '<button title="%title%" type="button" class="mfp-close">&#215;</button>',

            tClose: 'Close (Esc)',

            tLoading: 'Loading...',

            autoFocusLast: true

        }
    };



    $.fn.magnificPopup = function (options) {
        _checkInstance();

        var jqEl = $(this);

        // We call some API method of first param is a string
        if (typeof options === "string") {

            if (options === 'open') {
                var items,
                    itemOpts = _isJQ ? jqEl.data('magnificPopup') : jqEl[0].magnificPopup,
                    index = parseInt(arguments[1], 10) || 0;

                if (itemOpts.items) {
                    items = itemOpts.items[index];
                } else {
                    items = jqEl;
                    if (itemOpts.delegate) {
                        items = items.find(itemOpts.delegate);
                    }
                    items = items.eq(index);
                }
                mfp._openClick({ mfpEl: items }, jqEl, itemOpts);
            } else {
                if (mfp.isOpen)
                    mfp[options].apply(mfp, Array.prototype.slice.call(arguments, 1));
            }

        } else {
            // clone options obj
            options = $.extend(true, {}, options);

            /*
             * As Zepto doesn't support .data() method for objects
             * and it works only in normal browsers
             * we assign "options" object directly to the DOM element. FTW!
             */
            if (_isJQ) {
                jqEl.data('magnificPopup', options);
            } else {
                jqEl[0].magnificPopup = options;
            }

            mfp.addGroup(jqEl, options);

        }
        return jqEl;
    };

    /*>>core*/

    /*>>inline*/

    var INLINE_NS = 'inline',
        _hiddenClass,
        _inlinePlaceholder,
        _lastInlineElement,
        _putInlineElementsBack = function () {
            if (_lastInlineElement) {
                _inlinePlaceholder.after(_lastInlineElement.addClass(_hiddenClass)).detach();
                _lastInlineElement = null;
            }
        };

    $.magnificPopup.registerModule(INLINE_NS, {
        options: {
            hiddenClass: 'hide', // will be appended with `mfp-` prefix
            markup: '',
            tNotFound: 'Content not found'
        },
        proto: {

            initInline: function () {
                mfp.types.push(INLINE_NS);

                _mfpOn(CLOSE_EVENT + '.' + INLINE_NS, function () {
                    _putInlineElementsBack();
                });
            },

            getInline: function (item, template) {

                _putInlineElementsBack();

                if (item.src) {
                    var inlineSt = mfp.st.inline,
                        el = $(item.src);

                    if (el.length) {

                        // If target element has parent - we replace it with placeholder and put it back after popup is closed
                        var parent = el[0].parentNode;
                        if (parent && parent.tagName) {
                            if (!_inlinePlaceholder) {
                                _hiddenClass = inlineSt.hiddenClass;
                                _inlinePlaceholder = _getEl(_hiddenClass);
                                _hiddenClass = 'mfp-' + _hiddenClass;
                            }
                            // replace target inline element with placeholder
                            _lastInlineElement = el.after(_inlinePlaceholder).detach().removeClass(_hiddenClass);
                        }

                        mfp.updateStatus('ready');
                    } else {
                        mfp.updateStatus('error', inlineSt.tNotFound);
                        el = $('<div>');
                    }

                    item.inlineElement = el;
                    return el;
                }

                mfp.updateStatus('ready');
                mfp._parseMarkup(template, {}, item);
                return template;
            }
        }
    });

    /*>>inline*/

    /*>>ajax*/
    var AJAX_NS = 'ajax',
        _ajaxCur,
        _removeAjaxCursor = function () {
            if (_ajaxCur) {
                $(document.body).removeClass(_ajaxCur);
            }
        },
        _destroyAjaxRequest = function () {
            _removeAjaxCursor();
            if (mfp.req) {
                mfp.req.abort();
            }
        };

    $.magnificPopup.registerModule(AJAX_NS, {

        options: {
            settings: null,
            cursor: 'mfp-ajax-cur',
            tError: '<a href="%url%">The content</a> could not be loaded.'
        },

        proto: {
            initAjax: function () {
                mfp.types.push(AJAX_NS);
                _ajaxCur = mfp.st.ajax.cursor;

                _mfpOn(CLOSE_EVENT + '.' + AJAX_NS, _destroyAjaxRequest);
                _mfpOn('BeforeChange.' + AJAX_NS, _destroyAjaxRequest);
            },
            getAjax: function (item) {

                if (_ajaxCur) {
                    $(document.body).addClass(_ajaxCur);
                }

                mfp.updateStatus('loading');

                var opts = $.extend({
                    url: item.src,
                    success: function (data, textStatus, jqXHR) {
                        var temp = {
                            data: data,
                            xhr: jqXHR
                        };

                        _mfpTrigger('ParseAjax', temp);

                        mfp.appendContent($(temp.data), AJAX_NS);

                        item.finished = true;

                        _removeAjaxCursor();

                        mfp._setFocus();

                        setTimeout(function () {
                            mfp.wrap.addClass(READY_CLASS);
                        }, 16);

                        mfp.updateStatus('ready');

                        _mfpTrigger('AjaxContentAdded');
                    },
                    error: function () {
                        _removeAjaxCursor();
                        item.finished = item.loadError = true;
                        mfp.updateStatus('error', mfp.st.ajax.tError.replace('%url%', item.src));
                    }
                }, mfp.st.ajax.settings);

                mfp.req = $.ajax(opts);

                return '';
            }
        }
    });

    /*>>ajax*/

    /*>>image*/
    var _imgInterval,
        _getTitle = function (item) {
            if (item.data && item.data.title !== undefined)
                return item.data.title;

            var src = mfp.st.image.titleSrc;

            if (src) {
                if ($.isFunction(src)) {
                    return src.call(mfp, item);
                } else if (item.el) {
                    return item.el.attr(src) || '';
                }
            }
            return '';
        };

    $.magnificPopup.registerModule('image', {

        options: {
            markup: '<div class="mfp-figure">' +
                '<div class="mfp-close"></div>' +
                '<figure>' +
                '<div class="mfp-img"></div>' +
                '<figcaption>' +
                '<div class="mfp-bottom-bar">' +
                '<div class="mfp-title"></div>' +
                '<div class="mfp-counter"></div>' +
                '</div>' +
                '</figcaption>' +
                '</figure>' +
                '</div>',
            cursor: 'mfp-zoom-out-cur',
            titleSrc: 'title',
            verticalFit: true,
            tError: '<a href="%url%">The image</a> could not be loaded.'
        },

        proto: {
            initImage: function () {
                var imgSt = mfp.st.image,
                    ns = '.image';

                mfp.types.push('image');

                _mfpOn(OPEN_EVENT + ns, function () {
                    if (mfp.currItem.type === 'image' && imgSt.cursor) {
                        $(document.body).addClass(imgSt.cursor);
                    }
                });

                _mfpOn(CLOSE_EVENT + ns, function () {
                    if (imgSt.cursor) {
                        $(document.body).removeClass(imgSt.cursor);
                    }
                    _window.off('resize' + EVENT_NS);
                });

                _mfpOn('Resize' + ns, mfp.resizeImage);
                if (mfp.isLowIE) {
                    _mfpOn('AfterChange', mfp.resizeImage);
                }
            },
            resizeImage: function () {
                var item = mfp.currItem;
                if (!item || !item.img) return;

                if (mfp.st.image.verticalFit) {
                    var decr = 0;
                    // fix box-sizing in ie7/8
                    if (mfp.isLowIE) {
                        decr = parseInt(item.img.css('padding-top'), 10) + parseInt(item.img.css('padding-bottom'), 10);
                    }
                    item.img.css('max-height', mfp.wH - decr);
                }
            },
            _onImageHasSize: function (item) {
                if (item.img) {

                    item.hasSize = true;

                    if (_imgInterval) {
                        clearInterval(_imgInterval);
                    }

                    item.isCheckingImgSize = false;

                    _mfpTrigger('ImageHasSize', item);

                    if (item.imgHidden) {
                        if (mfp.content)
                            mfp.content.removeClass('mfp-loading');

                        item.imgHidden = false;
                    }

                }
            },

            /**
             * Function that loops until the image has size to display elements that rely on it asap
             */
            findImageSize: function (item) {

                var counter = 0,
                    img = item.img[0],
                    mfpSetInterval = function (delay) {

                        if (_imgInterval) {
                            clearInterval(_imgInterval);
                        }
                        // decelerating interval that checks for size of an image
                        _imgInterval = setInterval(function () {
                            if (img.naturalWidth > 0) {
                                mfp._onImageHasSize(item);
                                return;
                            }

                            if (counter > 200) {
                                clearInterval(_imgInterval);
                            }

                            counter++;
                            if (counter === 3) {
                                mfpSetInterval(10);
                            } else if (counter === 40) {
                                mfpSetInterval(50);
                            } else if (counter === 100) {
                                mfpSetInterval(500);
                            }
                        }, delay);
                    };

                mfpSetInterval(1);
            },

            getImage: function (item, template) {

                var guard = 0,

                    // image load complete handler
                    onLoadComplete = function () {
                        if (item) {
                            if (item.img[0].complete) {
                                item.img.off('.mfploader');

                                if (item === mfp.currItem) {
                                    mfp._onImageHasSize(item);

                                    mfp.updateStatus('ready');
                                }

                                item.hasSize = true;
                                item.loaded = true;

                                _mfpTrigger('ImageLoadComplete');

                            }
                            else {
                                // if image complete check fails 200 times (20 sec), we assume that there was an error.
                                guard++;
                                if (guard < 200) {
                                    setTimeout(onLoadComplete, 100);
                                } else {
                                    onLoadError();
                                }
                            }
                        }
                    },

                    // image error handler
                    onLoadError = function () {
                        if (item) {
                            item.img.off('.mfploader');
                            if (item === mfp.currItem) {
                                mfp._onImageHasSize(item);
                                mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src));
                            }

                            item.hasSize = true;
                            item.loaded = true;
                            item.loadError = true;
                        }
                    },
                    imgSt = mfp.st.image;


                var el = template.find('.mfp-img');
                if (el.length) {
                    var img = document.createElement('img');
                    img.className = 'mfp-img';
                    if (item.el && item.el.find('img').length) {
                        img.alt = item.el.find('img').attr('alt');
                    }
                    item.img = $(img).on('load.mfploader', onLoadComplete).on('error.mfploader', onLoadError);
                    img.src = item.src;

                    // without clone() "error" event is not firing when IMG is replaced by new IMG
                    // TODO: find a way to avoid such cloning
                    if (el.is('img')) {
                        item.img = item.img.clone();
                    }

                    img = item.img[0];
                    if (img.naturalWidth > 0) {
                        item.hasSize = true;
                    } else if (!img.width) {
                        item.hasSize = false;
                    }
                }

                mfp._parseMarkup(template, {
                    title: _getTitle(item),
                    img_replaceWith: item.img
                }, item);

                mfp.resizeImage();

                if (item.hasSize) {
                    if (_imgInterval) clearInterval(_imgInterval);

                    if (item.loadError) {
                        template.addClass('mfp-loading');
                        mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src));
                    } else {
                        template.removeClass('mfp-loading');
                        mfp.updateStatus('ready');
                    }
                    return template;
                }

                mfp.updateStatus('loading');
                item.loading = true;

                if (!item.hasSize) {
                    item.imgHidden = true;
                    template.addClass('mfp-loading');
                    mfp.findImageSize(item);
                }

                return template;
            }
        }
    });

    /*>>image*/

    /*>>zoom*/
    var hasMozTransform,
        getHasMozTransform = function () {
            if (hasMozTransform === undefined) {
                hasMozTransform = document.createElement('p').style.MozTransform !== undefined;
            }
            return hasMozTransform;
        };

    $.magnificPopup.registerModule('zoom', {

        options: {
            enabled: false,
            easing: 'ease-in-out',
            duration: 300,
            opener: function (element) {
                return element.is('img') ? element : element.find('img');
            }
        },

        proto: {

            initZoom: function () {
                var zoomSt = mfp.st.zoom,
                    ns = '.zoom',
                    image;

                if (!zoomSt.enabled || !mfp.supportsTransition) {
                    return;
                }

                var duration = zoomSt.duration,
                    getElToAnimate = function (image) {
                        var newImg = image.clone().removeAttr('style').removeAttr('class').addClass('mfp-animated-image'),
                            transition = 'all ' + (zoomSt.duration / 1000) + 's ' + zoomSt.easing,
                            cssObj = {
                                position: 'fixed',
                                zIndex: 9999,
                                left: 0,
                                top: 0,
                                '-webkit-backface-visibility': 'hidden'
                            },
                            t = 'transition';

                        cssObj['-webkit-' + t] = cssObj['-moz-' + t] = cssObj['-o-' + t] = cssObj[t] = transition;

                        newImg.css(cssObj);
                        return newImg;
                    },
                    showMainContent = function () {
                        mfp.content.css('visibility', 'visible');
                    },
                    openTimeout,
                    animatedImg;

                _mfpOn('BuildControls' + ns, function () {
                    if (mfp._allowZoom()) {

                        clearTimeout(openTimeout);
                        mfp.content.css('visibility', 'hidden');

                        // Basically, all code below does is clones existing image, puts in on top of the current one and animated it

                        image = mfp._getItemToZoom();

                        if (!image) {
                            showMainContent();
                            return;
                        }

                        animatedImg = getElToAnimate(image);

                        animatedImg.css(mfp._getOffset());

                        mfp.wrap.append(animatedImg);

                        openTimeout = setTimeout(function () {
                            animatedImg.css(mfp._getOffset(true));
                            openTimeout = setTimeout(function () {

                                showMainContent();

                                setTimeout(function () {
                                    animatedImg.remove();
                                    image = animatedImg = null;
                                    _mfpTrigger('ZoomAnimationEnded');
                                }, 16); // avoid blink when switching images

                            }, duration); // this timeout equals animation duration

                        }, 16); // by adding this timeout we avoid short glitch at the beginning of animation


                        // Lots of timeouts...
                    }
                });
                _mfpOn(BEFORE_CLOSE_EVENT + ns, function () {
                    if (mfp._allowZoom()) {

                        clearTimeout(openTimeout);

                        mfp.st.removalDelay = duration;

                        if (!image) {
                            image = mfp._getItemToZoom();
                            if (!image) {
                                return;
                            }
                            animatedImg = getElToAnimate(image);
                        }

                        animatedImg.css(mfp._getOffset(true));
                        mfp.wrap.append(animatedImg);
                        mfp.content.css('visibility', 'hidden');

                        setTimeout(function () {
                            animatedImg.css(mfp._getOffset());
                        }, 16);
                    }

                });

                _mfpOn(CLOSE_EVENT + ns, function () {
                    if (mfp._allowZoom()) {
                        showMainContent();
                        if (animatedImg) {
                            animatedImg.remove();
                        }
                        image = null;
                    }
                });
            },

            _allowZoom: function () {
                return mfp.currItem.type === 'image';
            },

            _getItemToZoom: function () {
                if (mfp.currItem.hasSize) {
                    return mfp.currItem.img;
                } else {
                    return false;
                }
            },

            // Get element postion relative to viewport
            _getOffset: function (isLarge) {
                var el;
                if (isLarge) {
                    el = mfp.currItem.img;
                } else {
                    el = mfp.st.zoom.opener(mfp.currItem.el || mfp.currItem);
                }

                var offset = el.offset();
                var paddingTop = parseInt(el.css('padding-top'), 10);
                var paddingBottom = parseInt(el.css('padding-bottom'), 10);
                offset.top -= ($(window).scrollTop() - paddingTop);


                /*
    
                Animating left + top + width/height looks glitchy in Firefox, but perfect in Chrome. And vice-versa.
    
                 */
                var obj = {
                    width: el.width(),
                    // fix Zepto height+padding issue
                    height: (_isJQ ? el.innerHeight() : el[0].offsetHeight) - paddingBottom - paddingTop
                };

                // I hate to do this, but there is no another option
                if (getHasMozTransform()) {
                    obj['-moz-transform'] = obj['transform'] = 'translate(' + offset.left + 'px,' + offset.top + 'px)';
                } else {
                    obj.left = offset.left;
                    obj.top = offset.top;
                }
                return obj;
            }

        }
    });



    /*>>zoom*/

    /*>>iframe*/

    var IFRAME_NS = 'iframe',
        _emptyPage = '//about:blank',

        _fixIframeBugs = function (isShowing) {
            if (mfp.currTemplate[IFRAME_NS]) {
                var el = mfp.currTemplate[IFRAME_NS].find('iframe');
                if (el.length) {
                    // reset src after the popup is closed to avoid "video keeps playing after popup is closed" bug
                    if (!isShowing) {
                        el[0].src = _emptyPage;
                    }

                    // IE8 black screen bug fix
                    if (mfp.isIE8) {
                        el.css('display', isShowing ? 'block' : 'none');
                    }
                }
            }
        };

    $.magnificPopup.registerModule(IFRAME_NS, {

        options: {
            markup: '<div class="mfp-iframe-scaler">' +
                '<div class="mfp-close"></div>' +
                '<iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe>' +
                '</div>',

            srcAction: 'iframe_src',

            // we don't care and support only one default type of URL by default
            patterns: {
                youtube: {
                    index: 'youtube.com',
                    id: 'v=',
                    src: '//www.youtube.com/embed/%id%?autoplay=1'
                },
                vimeo: {
                    index: 'vimeo.com/',
                    id: '/',
                    src: '//player.vimeo.com/video/%id%?autoplay=1'
                },
                gmaps: {
                    index: '//maps.google.',
                    src: '%id%&output=embed'
                }
            }
        },

        proto: {
            initIframe: function () {
                mfp.types.push(IFRAME_NS);

                _mfpOn('BeforeChange', function (e, prevType, newType) {
                    if (prevType !== newType) {
                        if (prevType === IFRAME_NS) {
                            _fixIframeBugs(); // iframe if removed
                        } else if (newType === IFRAME_NS) {
                            _fixIframeBugs(true); // iframe is showing
                        }
                    }// else {
                    // iframe source is switched, don't do anything
                    //}
                });

                _mfpOn(CLOSE_EVENT + '.' + IFRAME_NS, function () {
                    _fixIframeBugs();
                });
            },

            getIframe: function (item, template) {
                var embedSrc = item.src;
                var iframeSt = mfp.st.iframe;

                $.each(iframeSt.patterns, function () {
                    if (embedSrc.indexOf(this.index) > -1) {
                        if (this.id) {
                            if (typeof this.id === 'string') {
                                embedSrc = embedSrc.substr(embedSrc.lastIndexOf(this.id) + this.id.length, embedSrc.length);
                            } else {
                                embedSrc = this.id.call(this, embedSrc);
                            }
                        }
                        embedSrc = this.src.replace('%id%', embedSrc);
                        return false; // break;
                    }
                });

                var dataObj = {};
                if (iframeSt.srcAction) {
                    dataObj[iframeSt.srcAction] = embedSrc;
                }
                mfp._parseMarkup(template, dataObj, item);

                mfp.updateStatus('ready');

                return template;
            }
        }
    });



    /*>>iframe*/

    /*>>gallery*/
    /**
     * Get looped index depending on number of slides
     */
    var _getLoopedId = function (index) {
        var numSlides = mfp.items.length;
        if (index > numSlides - 1) {
            return index - numSlides;
        } else if (index < 0) {
            return numSlides + index;
        }
        return index;
    },
        _replaceCurrTotal = function (text, curr, total) {
            return text.replace(/%curr%/gi, curr + 1).replace(/%total%/gi, total);
        };

    $.magnificPopup.registerModule('gallery', {

        options: {
            enabled: false,
            arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',
            preload: [0, 2],
            navigateByImgClick: true,
            arrows: true,

            tPrev: 'Previous (Left arrow key)',
            tNext: 'Next (Right arrow key)',
            tCounter: '%curr% of %total%'
        },

        proto: {
            initGallery: function () {

                var gSt = mfp.st.gallery,
                    ns = '.mfp-gallery';

                mfp.direction = true; // true - next, false - prev

                if (!gSt || !gSt.enabled) return false;

                _wrapClasses += ' mfp-gallery';

                _mfpOn(OPEN_EVENT + ns, function () {

                    if (gSt.navigateByImgClick) {
                        mfp.wrap.on('click' + ns, '.mfp-img', function () {
                            if (mfp.items.length > 1) {
                                mfp.next();
                                return false;
                            }
                        });
                    }

                    _document.on('keydown' + ns, function (e) {
                        if (e.keyCode === 37) {
                            mfp.prev();
                        } else if (e.keyCode === 39) {
                            mfp.next();
                        }
                    });
                });

                _mfpOn('UpdateStatus' + ns, function (e, data) {
                    if (data.text) {
                        data.text = _replaceCurrTotal(data.text, mfp.currItem.index, mfp.items.length);
                    }
                });

                _mfpOn(MARKUP_PARSE_EVENT + ns, function (e, element, values, item) {
                    var l = mfp.items.length;
                    values.counter = l > 1 ? _replaceCurrTotal(gSt.tCounter, item.index, l) : '';
                });

                _mfpOn('BuildControls' + ns, function () {
                    if (mfp.items.length > 1 && gSt.arrows && !mfp.arrowLeft) {
                        var markup = gSt.arrowMarkup,
                            arrowLeft = mfp.arrowLeft = $(markup.replace(/%title%/gi, gSt.tPrev).replace(/%dir%/gi, 'left')).addClass(PREVENT_CLOSE_CLASS),
                            arrowRight = mfp.arrowRight = $(markup.replace(/%title%/gi, gSt.tNext).replace(/%dir%/gi, 'right')).addClass(PREVENT_CLOSE_CLASS);

                        arrowLeft.click(function () {
                            mfp.prev();
                        });
                        arrowRight.click(function () {
                            mfp.next();
                        });

                        mfp.container.append(arrowLeft.add(arrowRight));
                    }
                });

                _mfpOn(CHANGE_EVENT + ns, function () {
                    if (mfp._preloadTimeout) clearTimeout(mfp._preloadTimeout);

                    mfp._preloadTimeout = setTimeout(function () {
                        mfp.preloadNearbyImages();
                        mfp._preloadTimeout = null;
                    }, 16);
                });


                _mfpOn(CLOSE_EVENT + ns, function () {
                    _document.off(ns);
                    mfp.wrap.off('click' + ns);
                    mfp.arrowRight = mfp.arrowLeft = null;
                });

            },
            next: function () {
                mfp.direction = true;
                mfp.index = _getLoopedId(mfp.index + 1);
                mfp.updateItemHTML();
            },
            prev: function () {
                mfp.direction = false;
                mfp.index = _getLoopedId(mfp.index - 1);
                mfp.updateItemHTML();
            },
            goTo: function (newIndex) {
                mfp.direction = (newIndex >= mfp.index);
                mfp.index = newIndex;
                mfp.updateItemHTML();
            },
            preloadNearbyImages: function () {
                var p = mfp.st.gallery.preload,
                    preloadBefore = Math.min(p[0], mfp.items.length),
                    preloadAfter = Math.min(p[1], mfp.items.length),
                    i;

                for (i = 1; i <= (mfp.direction ? preloadAfter : preloadBefore); i++) {
                    mfp._preloadItem(mfp.index + i);
                }
                for (i = 1; i <= (mfp.direction ? preloadBefore : preloadAfter); i++) {
                    mfp._preloadItem(mfp.index - i);
                }
            },
            _preloadItem: function (index) {
                index = _getLoopedId(index);

                if (mfp.items[index].preloaded) {
                    return;
                }

                var item = mfp.items[index];
                if (!item.parsed) {
                    item = mfp.parseEl(index);
                }

                _mfpTrigger('LazyLoad', item);

                if (item.type === 'image') {
                    item.img = $('<img class="mfp-img" />').on('load.mfploader', function () {
                        item.hasSize = true;
                    }).on('error.mfploader', function () {
                        item.hasSize = true;
                        item.loadError = true;
                        _mfpTrigger('LazyLoadError', item);
                    }).attr('src', item.src);
                }


                item.preloaded = true;
            }
        }
    });

    /*>>gallery*/

    /*>>retina*/

    var RETINA_NS = 'retina';

    $.magnificPopup.registerModule(RETINA_NS, {
        options: {
            replaceSrc: function (item) {
                return item.src.replace(/\.\w+$/, function (m) { return '@2x' + m; });
            },
            ratio: 1 // Function or number.  Set to 1 to disable.
        },
        proto: {
            initRetina: function () {
                if (window.devicePixelRatio > 1) {

                    var st = mfp.st.retina,
                        ratio = st.ratio;

                    ratio = !isNaN(ratio) ? ratio : ratio();

                    if (ratio > 1) {
                        _mfpOn('ImageHasSize' + '.' + RETINA_NS, function (e, item) {
                            item.img.css({
                                'max-width': item.img[0].naturalWidth / ratio,
                                'width': '100%'
                            });
                        });
                        _mfpOn('ElementParse' + '.' + RETINA_NS, function (e, item) {
                            item.src = st.replaceSrc(item, ratio);
                        });
                    }
                }

            }
        }
    });

    /*>>retina*/
    _checkInstance();
}));
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.imageMainGallery = window.eviivo.imageMainGallery ? window.eviivo.imageMainGallery : {};

window.eviivo.imageMainGallery = function ($) {

    var defaultOptions = {
        initializeGalleryByDefault: true,
        initializeGalleryOnClick: true,
        initializeGalleryForRooms: true,
        trigger: '.trigger',
        heroSlide: '#hero-slider',
        heroNav: '#hero-nav',
        thumbSlider: "#hero-nav-single"
    };

    var options;
    var trigger;
    var thumbSlider;
    var virtualTourButton;
    var galleryButton;
    var imageGalleryContainer;
    var closeVTButton;

    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);

        trigger = $(options.trigger);
        thumbSlider = $(options.thumbSlider);

        virtualTourButton = $(".s-vt-virtual-tour");
        galleryButton = $(".s-vt-image-gallery");

        imageGalleryContainer = $(".mfp-arrow,.mfp-content");
        virtualTourContainer = $(".s-vt-container");
        closeVTButton = $(".s-vt-close");

        if (options.initializeGalleryByDefault === true && options.initializeGalleryOnClick === true) {
            throw "Initializing the Gallery with both options Initialize By Default and OnClick will generate conflicts as the classes are shared.";
        }

        // This condition should be used for scenarios where we want to load the gallery by DEFAULT on the page. e.g.: via pages that load the gallery on load
        if (options.initializeGalleryByDefault === true) {
            initDummyGallery();
        }

        // This function should be used for scenarios where we want to load the gallery only when a CLICK EVENT occurs. e.g.: toprooms/partners property pages
        if (options.initializeGalleryOnClick === true) {
            trigger.on('click', function () {
                initMainGallery();
            });
        }
    }

    $('.results-trigger').on('click', function () {
        $(this).next().magnificPopup('open');
    });

    // Click on Virtual tour icon on Homepage & Photos, except for Fullscape templates
    $('.page-type-1 .gallery-details .virtual-tour-icon, .page-type-5 .gallery-details .virtual-tour-icon').on('click', function () {
        if (!$("body").hasClass("template-13", "template-14")) {
            var iFrameUrl = $(this).parent().parent("a").data('iframe-url');

            $("body").addClass("mfp-hidden");
            virtualTourButton.addClass('active');
            galleryButton.removeClass('active');
            virtualTourContainer.removeClass("hidden");
            // Pass Virtual tour URL into an iFrame
            vtIframe.attr("src", iFrameUrl);
        }
    });
    // Click on Virtual tour icon on RoomType
    $('.page-type-2 .gallery-details .virtual-tour-icon').on('click', function () {
        $(this).closest('.lightbox-gallery-link').next().magnificPopup('open');
        $('.s-vt-virtual-tour.cp-button').trigger('click');
    });

    var vtIframe = $("#s-vt-iframe");

    $('.lightbox-gallery').each(function () {
        $(this).magnificPopup({
            delegate: 'a',
            type: 'image',
            gallery: {
                enabled: true,
                navigateByImgClick: true
            },
            fixedContentPos: true,
            callbacks: {
                open: function () {
                    launchGallery();
                },
                close: function () {
                    // Will fire when popup gallery is closed
                    hideVirtualTour();
                }
            }
        });
    });

    function virtualTourToggle() {

        virtualTourButton.on("click", function () {
            galleryButton.removeClass("active");
            virtualTourButton.addClass("active");
            $("body").addClass("mfp-hidden");

            virtualTourContainer.removeClass("hidden");
            imageGalleryContainer.hide();
        });

        galleryButton.on("click", function () {
            galleryButton.addClass("active");
            virtualTourButton.removeClass("active");
            $("body").removeClass("mfp-hidden");

            virtualTourContainer.addClass("hidden");
            imageGalleryContainer.show();
        });

        closeVTButton.on("click", function () {
            $.magnificPopup.close(); // Close popup that is currently opened (shorthand)
        });
    }

    /*=============================
    toprooms Main gallery
    =============================*/

    function initMainGallery() {
        $('.lightbox-gallery').magnificPopup({
            delegate: 'a',
            type: 'image',
            gallery: {
                enabled: true,
                navigateByImgClick: true
            },
            fixedContentPos: true,
            callbacks: {
                open: function () {
                    launchGallery();
                },
                close: function () {
                    // Will fire when popup gallery is closed
                    hideVirtualTour();
                }
            }
        });
    }

    /*=========================================
    Dummy her gallery with thumbnail slider
    =========================================*/
    // THIS INITIATES SLIDERS FOR ONLY TEMPLATES 7 AND 12
    function initDummyGallery() {
        thumbSlider.jcarousel({
            wrap: 'last'
        });

        $('.slide-prev').on("click", function () {
            if (window.innerWidth > 768) {
                thumbSlider.jcarousel('scroll', '-=3');
            }
            // if on small screen, scroll by a sigle image
            else {
                thumbSlider.jcarousel('scroll', '-=1');
            }
        });

        $('.slide-next').on("click", function () {
            
            if (window.innerWidth > 768) {
                thumbSlider.jcarousel('scroll', '+=3');
            }
            // if on small screen, scroll by a sigle image
            else {
                thumbSlider.jcarousel('scroll', '+=1');
            }
        });

        $(".lightbox-trigger-container").magnificPopup({
            delegate: 'a',
            type: 'image',
            gallery: {
                enabled: true,
                navigateByImgClick: true
            },
            fixedContentPos: true,
            callbacks: {
                open: function () {
                    launchGallery();
                },
                close: function () {
                    // Will fire when popup gallery is closed
                    hideVirtualTour();
                }
            }
        });
    }
    // IW template 13-14 or for inline galleries without an overlay
    $(".s-virtual-tour-launch").on("click", function () {
            $("body").addClass("virtual-tour-enabled");

            virtualTourContainer.removeClass("hidden");

            closeVTButton.on("click", function () {
                hideVirtualTour();
            });
    });

    $(document).on('keyup', function (e) {
        if (e.key === "Escape") hideVirtualTour();
    });

    function launchGallery() {
        var popUpGallery = $.magnificPopup.instance,
            firstImage = $(popUpGallery.currItem.el);

        var iFrameUrl = firstImage.data('iframe-url');

        if (iFrameUrl != null) {
            $("body").addClass("virtual-tour-enabled");

            virtualTourToggle();

            // Pass Virtual tour URL into an iFrame
            vtIframe.attr("src", iFrameUrl)
        }
    }

    function hideVirtualTour() {
        // Will fire when popup gallery is closed
        $("body").removeClass("virtual-tour-enabled mfp-hidden");
        $(".s-vt-container").addClass("hidden");

        // Reset buttons to a default state
        $(".s-vt-image-gallery").addClass("active");
        $(".s-vt-virtual-tour").removeClass("active");
        if (!$("body").hasClass("template-13", "template-14")) {
            // Clear iFrame's src
            vtIframe.attr("src", "");
        }

    }

    return {
        init: init
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.reviews = window.eviivo.reviews ? window.eviivo.reviews : {};

window.eviivo.reviews = function ($, ajaxHelper) {

    var defaultOptions = {
        propertyReviewsUrl: "",
        resources: {
            ReadMore: "Read more",
            ReadLess: "Read less"
        }
    };
    var ajaxRequestId = "reviewsAjaxRequest";
    var options;
    var currentPage = 1;
    var pages;
    var isNextDisabled;
    var isPreviousDisabled;
    var $firstArrow;
    var $lastArrow;
    var $lastArrowLink;
    var $firstArrowLink;
    var $reviewsSection;
    ///<summary>Main init method of the eviivo.reviews object</summary>
    ///<param name="settings">external settings</param>
    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);
        $reviewsSection = $(".reviews-section");

        if (!$reviewsSection.length) { //In cases when comments are disabled.
            return;
        }

        pages = $reviewsSection.data("numberofpages");

        ajaxHelper.init(ajaxRequestId, options.ajaxLoaderResources, $reviewsSection, updatePageContent, loadPageError);

        loadReviewWhenReviewsSectionIsVisible();
    }

    function loadReviewWhenReviewsSectionIsVisible() {
        if (isReviewsSectionVisible()) {
            navigateToPage(1);
        } else {
            $(window).scroll(function () {
                if (isReviewsSectionVisible()) {
                    $(window).unbind('scroll');
                    navigateToPage(1);
                }
            });
        }
    }

    function isReviewsSectionVisible() {
        return $(window).scrollTop() + $(window).height() + 70 >= $reviewsSection.offset().top;
    }

    function navigatePrevious() {
        if (currentPage - 1 > 0) {
            navigateToPage(currentPage - 1);
            return true;
        }
        return false;
    }

    function navigateNext() {
        if (currentPage + 1 <= pages) {
            navigateToPage(currentPage + 1);
            return true;
        }
        return false;
    }

    function updatePagination() {
        $firstArrow = $(".mod-paginate li.arrow:first-child");
        $lastArrow = $(".mod-paginate li.arrow:last-child");
        $firstArrowLink = $firstArrow.find("a");
        $lastArrowLink = $lastArrow.find("a");

        $firstArrowLink.on("click", navigatePrevious);
        $lastArrowLink.on("click", navigateNext);

        //$('.mod-paginate li[class!="arrow"]').remove();

        var currentPageHtml = $('<li class="current"><a class="link-bg" href="javascript:;">' + currentPage + '</a></li>');
        currentPageHtml.insertAfter($firstArrow);

        var pageBefore = currentPage - 1;
        if (pageBefore > 0) {
            $firstArrow.removeAttr("disabled");
            $('<li><a href="javascript:eviivo.reviews.navigateToPage(' + pageBefore + ');">' + pageBefore + '</a></li>').insertAfter($firstArrow);

            if (pageBefore - 2 >= 0) {
                $('<li><a href="javascript:;">&hellip;</a></li>').insertAfter($firstArrow);
                $('<li><a href="javascript:eviivo.reviews.navigateToPage(1);">1</a></li>').insertAfter($firstArrow);
            }
        }

        var pageAfter = currentPage + 1;
        if (pageAfter <= pages) {
            $('<li><a href="javascript:eviivo.reviews.navigateToPage(' + pageAfter + ');">' + pageAfter + '</a></li>').insertBefore($lastArrow);
        }

        if (currentPage + 2 <= pages) {
            $('<li><a href="javascript:;">&hellip;</a></li>').insertBefore($lastArrow);
            $('<li><a href="javascript:eviivo.reviews.navigateToPage(' + pages + ');">' + pages + '</a></li>').insertBefore($lastArrow);
        }

        if (currentPage == 1) {
            $firstArrowLink.off("click");
            isPreviousDisabled = true;
        }
        else if (isPreviousDisabled) {
            $firstArrowLink.on("click", navigatePrevious);
            isPreviousDisabled = false;
        }

        if (currentPage == pages) {
            $lastArrowLink.off("click");
            isNextDisabled = true;
        }
        else if (isNextDisabled) {
            $lastArrowLink.on("click", navigateNext);
            isNextDisabled = false;
        }
    }

    function loadPageError(jqXhr, textStatus, errorThrown) {
        console.log(textStatus);
        console.log(errorThrown);
    }

    function updatePageContent(data) {
        $reviewsSection.html(data);

        updatePagination();

        //reviews read more action

        $("#reviews-list .column-review-content p a").on("click", function () {
            $(this).parent().siblings(".review-item-details").slideToggle();
            $(this).parent().parent().toggleClass("active");
            var textDefault = options.resources.ReadMore;
            var textExpanded = options.resources.ReadLess;
            $(this).text(function (i, text) {
                return text === textExpanded ? textDefault : textExpanded;
            });
        });
    }

    function loadPage() {
        ajaxHelper.executeAjax({
            requestId: ajaxRequestId,
            url: options.propertyReviewsUrl + "/" + currentPage,
            method: "GET",
            cache: false,
            dataType: "html"
        });
    }

    function navigateToPage(page) {
        currentPage = page;
        loadPage();
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        navigateToPage: navigateToPage
    };
}(jQuery, eviivo.utils.ajaxHelper);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.popup = window.eviivo.popup ? window.eviivo.popup : {};

window.eviivo.popup = function ($) {

    var defaultOptions = {
        resources: {
        },
        bypassClose: false,
        bypassBodyHtml: false,
        popupBox: null,
        bypassHeaderHtml: false
    };
    var options;
    var $popupBox;
    var $popupContent;
    var $popupClose;
    var $popupHeaderTitle;

    ///<summary>Main init method of the eviivo.popup object</summary>
    ///<param name="settings">external settings</param>
    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);
        $popupBox = $(".dialogue-outer");
        $popupContent = $popupBox.find(".mod-dialogueBox");
        $popupHeaderTitle = $popupBox.find(".dialogue-header h3");
        $popupClose = $popupBox.find(".cp-link");
        $popupHeaderTitle = $popupBox.find(".dialogue-header h3");
        $popupClose.on("click", close);
        $(document).on("keydown", close);
        popUpVisibility();
    }

    function display(showOptions) {
        if (showOptions.popupBox != null && showOptions.popupBox != "") {
            $popupBox = $(showOptions.popupBox);
            $popupContent = $popupBox.find(".mod-dialogueBox");
            $popupHeaderTitle = $popupBox.find(".dialogue-header h3");
            $popupClose = $popupBox.find(".cp-link");
            $popupHeaderTitle = $popupBox.find(".dialogue-header h3");
        }

        if (showOptions.bypassClose) {
            $popupClose.hide();
            $popupClose.off("click", close);
            $(document).off("keydown", close);
        } else {
            $popupClose.show();
            $popupClose.on("click", close);
            $(document).on("keydown", close);
        }

        if (showOptions.bypassBodyHtml === false || showOptions.bypassBodyHtml == undefined) {
            $popupContent.html(showOptions.html);
        }

        if (showOptions.bypassHeaderHtml === false || showOptions.bypassHeaderHtml == undefined) {
            $popupHeaderTitle.html(showOptions.headerTitle).text();
        }

        if (showOptions.bodyClass) {
            $popupBox.removeClass().addClass('dialogue-outer').addClass(showOptions.bodyClass);
        }

        if (typeof showOptions.popupCloseCallBack === "function") {
            options.popupCloseCallBack = showOptions.popupCloseCallBack;
        }

        $popupBox.css("display", "table");
    }

    function close(e) {
        if (e.which === 1 || e.keyCode === 27) {
            $popupContent.html("");
            $popupBox.css("display", "none");
            $popupHeaderTitle.text("");
            if (typeof options.popupCloseCallBack === "function") {
                options.popupCloseCallBack();
            }

            if ($popupBox.hasClass('mod_announcement-popup')) {
                window.eviivo.webcore.cookieManager.setCookie("announcement_popup", "announcement_" + $('#announcement-popup_business_shortname').val() + "=1", 1);
                $popupBox.remove('.mod_announcement-popup');
            }
            $("body").removeClass("overflow-hidden");
        }
    }

    function popUpVisibility() {
        if ($(".mod_announcement-popup").is(':visible')) {
            $("body").addClass("overflow-hidden");
        }
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        display: display
    };
}(jQuery);
document.addEventListener("DOMContentLoaded", function () {
    // Open modal
    function openModal(event) {
        event.preventDefault();
        var targetId = event.currentTarget.getAttribute('id').replace('openModal-', 'moreInfoModal-');
        var modal = document.getElementById(targetId);
        if (modal) {
            modal.style.display = "block";
            modal.classList.add("modal-open");
            document.body.classList.add("modal-open");
        }
    }

    // Close modal
    function closeModal(event) {
        event.preventDefault();
        var targetId = event.currentTarget.getAttribute('data-target').replace('#', '');
        var modal = document.getElementById(targetId);
        if (modal) {
            modal.style.display = "none";
            modal.classList.remove("modal-open");
            document.body.classList.remove("modal-open");
        }
    }

    // Close modal by modal element
    function closeModalByElement(modal) {
        if (modal) {
            modal.style.display = "none";
            modal.classList.remove("modal-open");
            document.body.classList.remove("modal-open");
        }
    }

    // Attach event listeners to open modal links
    var openModalLinks = document.querySelectorAll('.modal-rooms-toggle');
    openModalLinks.forEach(function (link) {
        link.addEventListener('click', openModal);
    });

    // Attach event listeners to close modal links
    var closeModalLinks = document.querySelectorAll('.modal-close');
    closeModalLinks.forEach(function (link) {
        link.addEventListener('click', closeModal);
    });

    // Close modal when clicking outside of it
    window.addEventListener('click', function (event) {
        if (event.target.classList.contains('modal')) {
            closeModalByElement(event.target);
        }
    });

    // Close modal when pressing the Escape key
    document.addEventListener('keydown', function (event) {
        if (event.key === "Escape") {
            var openModals = document.querySelectorAll('.modal.modal-open');
            openModals.forEach(function (modal) {
                closeModalByElement(modal);
            });
        }
    });
});

document.addEventListener("DOMContentLoaded", function () {
    $(".accordion-toggle").on("click", function () {
        var target = $(this).data("target");
        $("#" + target).slideToggle("slow");
        $(this).toggleClass("active");
    });
});
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.optionSelector = window.eviivo.optionSelector ? window.eviivo.optionSelector : {};

window.eviivo.optionSelector = function ($) {
    var defaultOptions = {
    };

    var options;


    ///<summary>Main init method of the eviivo.optionSelector object</summary>
    ///<param name="settings">external settings</param>
    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);

    }



    //Header language selector
    var $expandableSelector = $("header .cp-expandable");
    var $headerControls = $(".cp-expandable");
    var $currencyContainer = $(".currency-inner");
    var $languageContainer = $(".language-inner");
    var $headerTooltip = $("header .cp-tooltip");


    $expandableSelector.on("click", function () {
        $(this).toggleClass("active");
        $(this).siblings(".cp-tooltip").toggle();
    });

    $headerControls.on("click", function () {
        if ($(this).hasClass("active")) {
            $(this).parent().siblings().find(".cp-expandable").removeClass("active");
            $(this).parent().siblings().find(".cp-tooltip").hide();
        }
    });

    /* Hide */
    $(document).on("click", function (e) {

        if ((!$(e.target).hasClass("cp-expandable") || !$(e.target).hasClass("active")) && $(e.target).parents("header .mod-selectors").length == 0) {
            $currencyContainer.hide();
            $languageContainer.hide();
            $expandableSelector.removeClass("active");
        }

    });

    $currencyContainer.on("click", function (evt) {
        evt.stopPropagation();
    });

    $languageContainer.on("click", function (evt) {
        evt.stopPropagation();
    });

    $(document).on("keyup",function (e) {
        if (e.keyCode == 27) {

            if (!$(e.target).hasClass(".cp-expandable.cp-expandable")) {
                $headerTooltip.hide();
                $expandableSelector.removeClass("active");

            }

        }
    });
    //Header language selector END




    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init
    };

}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.roomImages = window.eviivo.roomImages ? window.eviivo.roomImages : {};

window.eviivo.roomImages = function ($) {

    var defaultOptions = {
    };
    
    var options;
    var clickedImageSrc;
    
    ///<summary>Main init method of the eviivo.roomImages object</summary>
    ///<param name="settings">external settings</param>
    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);

        $("div.mod-results div.results-gallery-thumbs li:first-child a").addClass("active");

        // Results thumbs click functionality
        $(".results-gallery-thumbs a").on("click", thumbnailClickHandler);
    }
    
    ///<summary></summary>
    function thumbnailClickHandler() {
        var $obj = $(this);
        if (!$obj.hasClass("active")) {
            $obj.parents(".results-gallery-thumbs").find("a").removeClass("active");
            $obj.addClass("active");
            var $picture = $obj.parents("div.results-gallery").find("div.results-gallery-single picture");
            if ($picture) {
                var src = $obj.find("img").attr("srcset");
                clickedImageSrc = extractUrl(src, false);
                $picture.find("img, source").each(changeSourceSet);
            }
        }
    }
    
    ///<summary></summary>
    function extractUrl(url, extensionOnly) {
        var index = url.lastIndexOf("-");
        var str = url.substr(index);
        if (str.length > 6) {
            index = url.lastIndexOf(".");
            return extensionOnly ? url.substr(index) : url.substr(0, index);
        }
        return extensionOnly ? str : url.substr(0, index);
    }
    
    ///<summary></summary>
    function changeSourceSet(i, e) {
        var srcExtension = $(e).attr("srcset");
        srcExtension = extractUrl(srcExtension, true);
        if ($(e).attr("src")) {
            $(e).attr("src", clickedImageSrc + srcExtension);
        }
        $(e).attr("srcset", clickedImageSrc + srcExtension);
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.instantWebMenu = window.eviivo.instantWebMenu ? window.eviivo.instantWebMenu : {};

window.eviivo.instantWebMenu = function ($) {

    var defaultOptions = {
        navigation: '.menu',
        menuOuter: '.menu-toggle ul',
        menuItems: '.menu li a',
        iconRight: '.icon-arrow-right',
        iconLeft: '.icon-arrow-left',
        menuControls: '.nav-controls',
        menuCta: '.menu-toggle .cp-button',
        searchBar: '.mod-search',
        menuButton: '.cp-menuIcon',
        iconMenuContainer: '.menu-icon',
        iconMenuDefault: '≡',
        iconMenuClose: '×',
    };
    var options;
    var totalWidth;

    var $navigation;
    var $menuOuter;
    var $menuItems;
    var $iconRight;
    var $iconLeft;
    var $menuControls;
    var $menuCta;
    var $searchBar;
    // Responsive menu toggle
    var $menuButton;
    var $iconMenuContainer;
    var iconMenuDefault;
    var iconMenuClose;

    ///<summary>Main init method of the eviivo.availabilitySearch object</summary>
    ///<param name="settings">external settings</param>
    function init(settings) {

        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);

        $navigation = $(options.navigation);
        $menuOuter = $(options.menuOuter);
        $menuItems = $(options.menuItems);
        $iconRight = $(options.iconRight);
        $iconLeft = $(options.iconLeft);
        $menuControls = $(options.menuControls);
        // header book button
        $menuCta = $(options.menuCta);
        $searchBar = $(options.searchBar);
        // Responsive menu toggle
        $menuButton = $(options.menuButton);
        iconMenuContainer = options.iconMenuContainer;
        iconMenuDefault = options.iconMenuDefault;
        iconMenuClose = options.iconMenuClose;

        totalWidth = 0;

        $iconRight.on('click', clickScrollRight);
        $iconLeft.on('click', clickScrollLeft);

        menuLengthCheck();

        $menuCta.on("click", function () {
            $(this).toggleClass("active");
            $searchBar.toggleClass('open');

            if ($menuButton.parent().hasClass("active")) {
                toggleBookButtonIcon($menuButton);
            }
        });
        
        $menuButton.on("click", function () {
            toggleBookButtonIcon($(this));

            if ($menuCta.hasClass('active')) {
                closeSearch();
            }
        });


        $(window).resize(function () {
            menuLengthCheck();
        });
    }

    function closeSearch() {
        $menuCta.removeClass("active");
        $searchBar.removeClass('open');
    }
    
    function initSearchBar() {
        $menuCta.toggleClass('active');
        $searchBar.toggleClass('open');
    }

    function toggleBookButtonIcon(object) {
        $(object).parent().toggleClass("active");

        if ($menuButton.parent().hasClass('active')) {
            $(iconMenuContainer).text(iconMenuClose);
        }
        else {
            $(iconMenuContainer).text(iconMenuDefault);
        }
    }

    function menuLengthCheck() {
        var menuContainer = $('nav .menu').outerWidth(true);

        totalWidth = 0;
        $menuItems.each(function (i, e) {
            totalWidth += $(e).outerWidth(true); // adds its width to the total
        });

        if ($(window).width() > 1023) {

            $menuOuter.css('width', (totalWidth + 1)); // I give it extra 1 pixels for to accommodate different browser rendering issues.

            if (totalWidth > menuContainer) {
                menuShow();
            } else {
                menuHide();
            }
        } else {
            menuHide();
        }
    }

    function menuHide() {
        $menuOuter.removeAttr("style");
        $menuControls.hide();
    }

    function menuShow() {
        $menuControls.show();
    }

    function clickScrollRight() {
        var scrollX = $navigation.scrollLeft();
        $navigation.animate({ scrollLeft: scrollX + 200 }, 300);
    }

    function clickScrollLeft() {
        var scrollX = $navigation.scrollLeft();
        $navigation.animate({ scrollLeft: scrollX - 200 }, 300);
    }



    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        initSearchBar: initSearchBar
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.promos = window.eviivo.promos ? window.eviivo.promos : {};

window.eviivo.promos = function ($) {

    var defaultOptions = {
        resources: {
            apply: "Apply",
            unlockSpecials: "Click to unlock your special deal",
            enterPromoCode: "Enter your code or member ID"
        }
    };
    var options;
    var $mainContainer;
    var $modOverlay;
    var searchTrigger;

    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);

        $mainContainer = $(".main");
        $('div.mod-promo button.promo-button-action').on("click", applyPromoButtonHandler);

        checkForInvalidPromoCode();

        searchTrigger = options.searchTrigger;
    }

    function checkForInvalidPromoCode() {
        var failure = jQuery("#failed_code_message");
        if (failure.length > 0) {
            showPromoCodeInputPopup(failure.val());
        }
    }

    function applyPromoButtonHandler() {
        var bannerType = $(this).data("banner-type");
        if (typeof bannerType === "string") {
            switch (bannerType.toLowerCase()) {
                case options.bannerTypes.webExclusivePromoCode.toLowerCase():
                    showPromoCodeInputPopup();
                    break;
                case options.bannerTypes.webExclusiveInstantDeal.toLowerCase():
                    showInstantDealInputPopup();
                    break;
                case options.bannerTypes.webExclusivePromoCodeUnlocked.toLowerCase():
                case options.bannerTypes.webExclusivePromoCodeFail.toLowerCase():
                case options.bannerTypes.webExclusiveBannerWarning.toLowerCase():
                    removePromotionBanner();
                    break;
            }
        }
    }

    function removePromotionBanner() {
        $("#" + options.queryString.promoCode).remove();
        $("#" + options.queryString.askForPromoInstantDeal).remove();
        //remove from cookies too
        var propertyId = $("#prop-id").val();
        if (typeof (propertyId) === "string") {
            removePropertyIdFromCookie(propertyId, options.cookie.flags.instantDeal);
            removePropertyIdFromCookie(propertyId, options.cookie.flags.promotionCode);
        }

        searchTrigger();
    }

    function removePropertyIdFromCookie(propertyId, cookieName) {
        var listOfProperties = window.eviivo.webcore.cookieManager.getCookie(cookieName);
        if (listOfProperties != null && listOfProperties.length > 0) {
            var json = eviivo.utils.queryStringHelper.getAllKeys(listOfProperties, {});
            eviivo.utils.queryStringHelper.deleteKey(json, "p_" + propertyId.toLowerCase());
            //Sets the cookie to expiry after the session ended (no value by default does that) this kept the functionallity that was in place before replacing the cookie library
            window.eviivo.webcore.cookieManager.setCookie(cookieName, eviivo.utils.queryStringHelper.toString(json, false));
        }
    }

    //The overlay has that faded background over the entire page, so if we show it and not removing it we will not be able to interact with the page.
    //Same case when we already have it opened.
    //Just as a protection in case it's already opened, we remove it first and then we re-add it from the template.
    function displayPopup(popupPromoCodeTitleText, popupPromoCodeForm, popupCloseCallBack) {
        $modOverlay = $mainContainer.find("div.dialogue-outer");
        eviivo.popup.display({
            html: popupPromoCodeForm,
            headerTitle: popupPromoCodeTitleText,
            bodyClass: "dialogue-medium dialogue-height--auto",
            popupCloseCallBack: popupCloseCallBack
        });
    }

    function displayInstantDealPopup(popupPromoCodeTitleText, popupPromoCodeForm) {
        displayPopup(popupPromoCodeTitleText, popupPromoCodeForm);
        if (grecaptcha) {
            grecaptcha.render('grecaptchaId',
            {
                'sitekey': options.captcha.siteKey,
                'callback': recaptchaReceived
            });
        } else {
            console.error("Error: could not load Google Recaptcha API.");
        }
    }

    function recaptchaReceived(response) {
        if (response) {
            //force removal of promo code (in case the entered one gave error and now we want to enter instant deal only)
            $("#" + options.queryString.promoCode).remove();
            $("#" + options.queryString.askForPromoInstantDeal).val(true);
            window.eviivo.webcore.cookieManager.setCookie('captcha', response, 30);
            searchTrigger();
        } else {
            console.error("Error: recaptcha response not received.");
        }
    }

    function showInstantDealInputPopup() {
        var unlockInstantDealTitle = options.resources.unlockSpecials;
        var unlockInstantDealForm = $("<div id='grecaptchaId' class='captcha'></div>");

        displayInstantDealPopup(unlockInstantDealTitle, unlockInstantDealForm);
    }

    function removePromoCodeFromQueryString() {
        window.location.href = window.location.href.removeKeyFromQueryString(options.queryString.promoCode);
    }

    function showPromoCodeInputPopup(failureMessage) {
        var popupPromoCodeTitleText = options.resources.enterPromoCode;
        var popupPromoCodeForm = "<input type='text' class='cp-input' id='apply-promo-code-input' placeholder='' value='' /><button class='cp-button' id='apply-promo-code' type='button'>" + options.resources.apply + "</button>";

        if (typeof (failureMessage) === "string" && failureMessage !== "") {
            popupPromoCodeForm += '<div class="field-validation-error">' + failureMessage + '</div>';

            displayPopup(popupPromoCodeTitleText, popupPromoCodeForm, removePromoCodeFromQueryString);

        } else {
            displayPopup(popupPromoCodeTitleText, popupPromoCodeForm);
        }



        //focus on the input straight
        $("#apply-promo-code-input").focus();

        $("#apply-promo-code-input").bind("paste", function (e) {
            e.preventDefault();
            $("#apply-promo-code-input").val(e.originalEvent.clipboardData.getData('text').trim())
        });
    }

    function onCodeValid(code) {
        $("#" + options.queryString.promoCode).val(code);
        // add spinner to indicate that someting is happening
        searchTrigger();
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        onCodeValid: onCodeValid
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.promos = window.eviivo.promos ? window.eviivo.promos : {};
window.eviivo.promos.codeValidator = window.eviivo.promos.codeValidator ? window.eviivo.promos.codeValidator : {};

window.eviivo.promos.codeValidator = function ($) {
    var options;
    var promoCodeValidationRule = new RegExp("^[a-zA-Z0-9\-\_@\#]+$", "ig");

    function applyPromoCodeHandler(e) {
        if (e != null && (e.keyCode === 13 || e.which === 1)) {
            var $applyInput = $("#apply-promo-code-input");
            var $errorArea = $("div.field-validation-error");

            $applyInput.removeClass("invalid");
            $errorArea.remove();
            var isInvalid = false;
            var errorMessage = "";
            var code = $applyInput.val();
            if (code === "") {
                errorMessage = options.resources.promoValidationEmptyCode;
                isInvalid = true;
            } else if (!(promoCodeValidationRule.test(code))) {
                errorMessage = options.resources.promoValidationMessage;
                isInvalid = true;
            }
            if (isInvalid === true) {
                $applyInput.addClass('invalid');
                $("<div class='field-validation-error'>" + errorMessage + "</div>").insertAfter($("#apply-promo-code"));
            } else {
                if (typeof options.callback === "function") {
                    options.callback(code);
                }
                return true;
            }
        }
        return false;
    }

    function init(settings) {
        //extend internal settings with external ones
        options = $.extend({}, settings);

        $(document).on("click", "#apply-promo-code", applyPromoCodeHandler);
        $(document).on("keyup", "#apply-promo-code-input", applyPromoCodeHandler);
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.bookingSystem = window.eviivo.bookingSystem ? window.eviivo.bookingSystem : {};
window.eviivo.bookingSystem.managePageLogin = window.eviivo.bookingSystem.managePageLogin ? window.eviivo.bookingSystem.managePageLogin : {};

window.eviivo.bookingSystem.managePageLogin = function ($, ajaxHelper) {

    function init(customSettings) {

        var options = customSettings;

        $('#manageBooking')
            .on('click',
                function () {

                    eviivo.popup.display({
                        html: $("#manage-popup-login-content").html(),
                        headerTitle: options.popupHeaderTitle,
                        bodyClass: "dialogue-large dialogue-height--auto"
                    });

                    // hide header tooltip if exapanded
                    if ($(".cp-expandable").hasClass("active")) {
                        $(".cp-expandable").removeClass("active");
                        $(".cp-tooltip").hide();
                    }

                    var ajaxRequestId = "retrieveOrderCancellationPermissions";
                    var $manageLoginForm = $('#manage-page-login-form');
                    var $cancelationErrorMsg = $("#cancellationGenericMessage");

                    var ajaxCompletedFn = function (responseData) {

                        if (responseData != null && responseData.allowRedirectToManagePage === true) {
                            window.location.href = responseData.manageBookingUrl;
                        } else {
                            $cancelationErrorMsg.show();
                        }
                    };

                    var ajaxCompletedWithErrorsFn = function () {
                        $cancelationErrorMsg.show();
                    };

                    ajaxHelper.init(ajaxRequestId,
                        options.ajaxLoaderResources,
                        $(".mod-dialogueBox"),
                        ajaxCompletedFn,
                        ajaxCompletedWithErrorsFn);

                    // because popup's html is loaded on-the-fly we need to initialize jquery unobtrusive validation here
                    $.validator.unobtrusive.parse($manageLoginForm);
                    $manageLoginForm.validate().settings.submitHandler = function () {

                        $cancelationErrorMsg.hide();

                        ajaxHelper.executeAjax({
                            requestId: ajaxRequestId,
                            url: options.ajaxUrl,
                            method: "POST",
                            headers: {
                                '__RequestVerificationToken': options.requestVerificationToken
                            },
                            data: {
                                "GuestEmailAddress": $('#emailAddress', $manageLoginForm).val(),
                                "OrderOrBookingReference": $('#orderReference', $manageLoginForm).val(),
                                "ReferrerShortName": options.referrerShortName,
                                "PropertyShortName": options.propertyShortName
                            }
                        });

                        return false;
                    };

                    //manage booking pop up tip
                    $(".cp-tip")
                        .tooltip({
                            position: {
                                my: "center bottom-15",
                                at: "center top",
                                using: function (position, feedback) {
                                    $(this).css(position);
                                    $("<div>")
                                        .addClass("arrow")
                                        .addClass(feedback.vertical)
                                        .addClass(feedback.horizontal)
                                        .appendTo(this);
                                }
                            }
                        });

                    // toggle show/hide manage pop up
                    $(".mod-sliding-trigger")
                        .on("click",
                            function (elem) {

                                var $anchorElem = $(elem.target);

                                $anchorElem.parents().eq(2).toggleClass("active");

                                var buttonText = $anchorElem.text() === $anchorElem.data('need-help-text')
                                    ? $anchorElem.data('go-back-text')
                                    : $anchorElem.data('need-help-text');

                                $anchorElem.text(buttonText).toggleClass("active");
                            });
                });
    }

    return {
        init: init
    };
}(jQuery, eviivo.utils.ajaxHelper);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.announcement = window.eviivo.announcement ? window.eviivo.announcement : {};

window.eviivo.announcement = function ($) {

    var options;
    var defaultOptions = {
        openInNewTab: false
    }
    var announcementLink;
    var searchUrl = "";
    var querystringHelper;

    function init(settings) {
        options = $.extend(defaultOptions, settings);
        searchUrl = options.searchUrl;
        announcementLink = $('#promo-code-link');

        announcementLink.on('click', function () {
            window.eviivo.webcore.cookieManager.setCookie("announcement_popup", "announcement_" + options.propertyShortName + "=1", 1);
            searchUrl = setUrl();

            if (options.linkAddress != "") {
                searchUrl = options.linkAddress;
            }

            if (options.openInNewTab) {
                window.open(searchUrl);
                return;
            }

            if (options.promoCode == "") {
                window.open(searchUrl, "_self");
                return;
            }

            window.location.href = searchUrl;
        });
    }

    function setUrl() {
        querystringHelper = eviivo.utils.queryStringHelper;
        if (typeof querystringHelper === "undefined") {
            console.warn("eviivo.utils.queryStringHelper was not loaded therefore this page might not work properly");
        }

        var src = window.location.href;
        var originalQueryString = querystringHelper.getAllKeys(src);
        var queryStrings = jQuery.extend({}, originalQueryString);

        querystringHelper.addKey(queryStrings, "pce", options.promoCode);

        return searchUrl += querystringHelper.toString(queryStrings);
    }

    return {
        init: init,
    }
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.customPage = window.eviivo.customPage ? window.eviivo.customPage : {};

window.eviivo.customPage = function ($) {
    var selectors = {
        collapsibleArticles: ".mod-article.collapsible h4"
    };

    function init() {
        toggleCollapsedClassEvent();
    }


    /**
     * Toggles the 'collapsed' class on click event for collapsible articles.
     */
    function toggleCollapsedClassEvent() {
        const collapsedClassName = "collapsed";

        jQuery(selectors.collapsibleArticles).on('click', function () {
            const elementIndex = jQuery(selectors.collapsibleArticles).index(this);

            // Remove 'collapsed' class from all collapsible articles except the clicked one
            jQuery(selectors.collapsibleArticles)
                .filter(index => index != elementIndex)
                .removeClass(collapsedClassName);

            jQuery(this).toggleClass(collapsedClassName);
        });
    }

    return {
        init: init,
    }
}(jQuery);
(function ($, sr) {

    // debouncing function from John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    var debounce = function (func, threshold, execAsap) {
        var timeout;

        return function debounced() {
            var obj = this, args = arguments;
            function delayed() {
                if (!execAsap)
                    func.apply(obj, args);
                timeout = null;
            };

            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);

            timeout = setTimeout(delayed, threshold || 100);
        };
    }
    // smartresize 
    jQuery.fn[sr] = function (fn) { return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery, 'smartresize');

window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.combinedInventory = window.eviivo.combinedInventory ? window.eviivo.combinedInventory : {};

window.eviivo.combinedInventory = function ($) {
    let options,
        defaultOptions = {
            resources: {
                soldout: "Sold Out",
                select: "Select"
            }
        },
        attributes = {
            checked: "checked",
            id: "id",
            name: "name",
            disabled: "disabled"
        },
        classes = {
            checked: "ui-checkboxradio-checked",
            active: "ui-state-active"
        },
        selectors = {
            roomInventory: {
                radio: {
                    items: 'input[type="radio"].s-inventory-item',
                    groupByName: (name) => `input[type="radio"].s-inventory-item[name='${name}']`,
                },
                labelById: (id) => `label[for='${id}']`,
            },
            checked: ":checked",
        },
        elements = {
            roomInventory: {
                radio: {
                    items: $(),
                }
            },
        },
        events = {
            change: "change"
        },
        combinedInventoryManager = {
            totalRealInventoryAmount: 0,
            inventorySelections: [],
            unitTypeMap: {}
        };

    /**
     * Main initialise function.
     * @param {any} settings - combined inventory settings.
     */
    function init(settings) {
        options = $.extend(defaultOptions, settings);
        initElements();
        initCombinedInventoryManager();
        initListeners();
    }

    /**
     * Initialises elements needed for combined inventory.
     */
    function initElements() {
        elements.roomInventory.radio.items = $(selectors.roomInventory.radio.items);
    }

    /**
     * Initialises the combined inventory manager which holds information needed to manage combined inventory such as: 
     * total real inventory amount, inventory selection and unit type information (e.g. room type amount consumed).
     */
    function initCombinedInventoryManager() {
        // Build the combined inventory manager's unit type map, this holds details such as a unit type's consumed amount and real available amount. 
        elements.roomInventory.radio.items.each(function () {
            const data = $(this).data();
            if (data?.rtid && !combinedInventoryManager.unitTypeMap[data.rtid]) {
                combinedInventoryManager.unitTypeMap[data.rtid] = {
                    amountAvailable: data.aa == null ? 0 : data.aa,
                    amountConsumed: data.ac == null ? 0 : data.ac,
                    amountRealAvailable: data.ara == null ? 0 : data.ara
                };
            }
        });

        // JIRA EVDEV-35528 - If the search returned no real availability, use the max inventory count for the property which is the count of all real inventory units for the property.
        combinedInventoryManager.totalRealInventoryAmount = options.maxInventory;

        // Add each pre-selected inventory item to the inventory manager's selections.
        elements.roomInventory.radio.items.each(function () {
            const element = $(this);
            if (element.is(selectors.checked)) {
                combinedInventoryManager.inventorySelections.push({ id: element.prop(attributes.id), amountConsumed: element.data().ac });
            }
        });

        // We could already be over the total real inventory amount due to pre-selections, so enforce availability to deal with this. 
        enforceAvailabilityOnInventoryItems();
    }

    /**
     * Initialises event listeners needed for managing combined inventory.
     */
    function initListeners() {
        /**
         * Change event handler that will trigger on each room selection.
         * @param {any} event - The change event.
         */
        const handleRoomSelection = (event) => {
            const element = $(event.target);

            // Set text to 'selected' for the selection's associated label.
            setLabelTextForInputElement(element, options.resources.select);

            // Grab the selections id.
            const id = element.prop(attributes.id);

            // Add the selection to the manager so we can keep track of what is currently selected when working out the availability to display.
            combinedInventoryManager.inventorySelections.push({ id: id, amountConsumed: element.data().ac });

            // Enforce the new availability onto the inventory items, passing in the newly selected element's id
            // so that we don't enforce availability onto the inventory item that we just selected.
            enforceAvailabilityOnInventoryItems(id);
        }

        // Attach the handler to the change event for each radio button.
        elements.roomInventory.radio.items.each(function () {
            $(this).off(events.change).on(events.change, handleRoomSelection);
        });
    }

    /**
     * Function to set the text content of a specified DOM element to the provided value.
     * @param {jQuery} element - The jQuery element for the input.
     * @param {string} value - The text content.
     */
    const setLabelTextForInputElement = (element, value) => {
        element.siblings(selectors.roomInventory.labelById(element.attr(attributes.id))).text(value);
    }

    /**
     * Returns the inventory selections sorted by the amount consumed in descending order.
     * @returns {Array} Sorted array of inventory selections.
     */
    const sortSortedSelectionsByConsumed = () => {
        return combinedInventoryManager.inventorySelections.sort((a, b) => {
            if (a.amountConsumed < b.amountConsumed) {
                return 1;
            }
            if (a.amountConsumed > b.amountConsumed) {
                return -1;
            }
            return 0;
        });
    }

    /**
    * Enforces the current availability onto all inventory items, unless a 'selectedId' is provided, in which case the corresponding inventory item will be skipped.
    * @param {string} selectedId - (Optional) An id we wish to exclude from having current availability rules applied to it, used when a new selection has just been made
    * to avoid applying current availability to the item that was just selected.
    */
    const enforceAvailabilityOnInventoryItems = (selectedId = null) => {
        // Firstly, if we have a 'selectedId' we need to remove any existing selection for this selections radio group.
        if (selectedId != null) {
            const newlySelectedItem = $(`#${selectedId}`);
            const currentlySelectedInventory = $(selectors.roomInventory.radio.groupByName(newlySelectedItem.attr(attributes.name)));

            currentlySelectedInventory.each(function () {
                // Remove/Deselect this inventory selection:
                const element = $(this);
                const id = element.prop(attributes.id);

                // If the selectedId matches the current inventory item's id skip this inventory item as we don't want to remove the item we just selected.
                if (id === selectedId) {
                    return;
                }

                // 1. Remove the current selection from the inventory manager.
                combinedInventoryManager.inventorySelections = combinedInventoryManager.inventorySelections.filter(_ => _.id !== id);

                // 2. Set text to 'soldout' for the selection's associated label.
                setLabelTextForInputElement(element, options.resources.soldout);

                // 3. Uncheck the radio button if it's checked and remove any checked/active classes that may be present.
                if (element.is(selectors.checked)) {
                    element.prop(attributes.checked, false);
                    element.siblings(selectors.roomInventory
                        .labelById(id))
                        .removeClass([classes.checked, classes.active]);
                }

                // 4. Disable the input
                element.attr(attributes.disabled, attributes.disabled);
            });       
        }

        // Next, check whether the amount consumed by the current selections is valid by summing the amount consumed of all current selections and
        // comparing it to the combined inventory manager's total real inventory amount.
        let selectionsTotalAmountConsumed = combinedInventoryManager.inventorySelections.reduce((acc, item) => acc + item.amountConsumed, 0);

        // If the current selections amount consumed is greater than the total real inventory amount we need to resolve this by deselecting some
        // selections until the selection amount consumed is valid again.
        if (selectionsTotalAmountConsumed > combinedInventoryManager.totalRealInventoryAmount) {
            // Sort the current inventory selections by their amount consumed, this way we will be removing the fewest selections possible.
            const sortedSelections = sortSortedSelectionsByConsumed();

            for (i = 0; i < sortedSelections.length; i++) {
                // If the selections amount consumed is now less than or equal to the total real inventory amount break out the loop as
                // we do not need to deselect anymore inventory.
                if (selectionsTotalAmountConsumed <= combinedInventoryManager.totalRealInventoryAmount) {
                    break;
                }

                const selection = sortedSelections[i];

                // If a selectedId was provided and it matches the current selection's id skip this inventory item.
                if (selectedId != null && selection.id === selectedId) {
                    continue;
                }

                const element = $(`#${selection.id}`);

                // Remove/Deselect this inventory selection:

                // 1. Remove the current selection from the inventory manager.
                combinedInventoryManager.inventorySelections = combinedInventoryManager.inventorySelections.filter(_ => _.id !== selection.id);

                // 2. Reduce the selections amount consumed by this selection's amount consumed.
                selectionsTotalAmountConsumed -= selection.amountConsumed;

                // 3. Set text to 'soldout' for the selection's associated label.
                setLabelTextForInputElement(element, options.resources.soldout);

                // 4. Uncheck the radio button if it's checked and remove any checked/active classes that may be present.
                if (element.is(selectors.checked)) {
                    element.prop(attributes.checked, false);
                    element.siblings(selectors.roomInventory
                        .labelById(element.attr(attributes.id)))
                        .removeClass([classes.checked, classes.active]);
                }

                // 5. Disable the input
                element.attr(attributes.disabled, attributes.disabled);
            }
        }

        // Lastly, enforce availability onto any unselected inventory by checking whether any inventory item that is not selected has an amount consumed
        // greater than the remaining available inventory. If it does we need to mark it as sold out, otherwise mark it as selected. 

        // Calculate the remaining available inventory.
        const remainingAvailableInventory = combinedInventoryManager.totalRealInventoryAmount - selectionsTotalAmountConsumed;

        elements.roomInventory.radio.items.each(function () {
            const element = $(this);
            // We only care about unchecked elements here as the checked elements have been dealt with above.
            if (!element.is(selectors.checked)) {
                const amountConsumed = element.data().ac;

                const currentlySelectedInventoryForGroup = $(selectors.roomInventory.radio.groupByName(element.attr(attributes.name)))
                    .not(element)
                    .filter(selectors.checked)
                    .toArray()
                    .reduce((acc, item) => acc + ($(item).data().ac || 0), 0);

                const isSoldOut = amountConsumed > (remainingAvailableInventory + currentlySelectedInventoryForGroup);

                // Any other units displayed that have a consumed inventory of HIGHER than the remaining available inventory should be marked as Sold Out.
                setLabelTextForInputElement(element,
                    isSoldOut
                        ? options.resources.soldout
                        : options.resources.select);

                combinedInventoryManager.inventorySelections = combinedInventoryManager.inventorySelections.filter(_ => _.id !== element.attr(attributes.id));

                // Disable the input if soldout
                isSoldOut
                    ? element.attr(attributes.disabled, attributes.disabled)
                    : element.removeAttr(attributes.disabled);
            }
        });
    }

    return {
        init: init
    };
}(jQuery);
