/* Minification failed. Returning unminified contents.
(156,45-46): run-time error JS1014: Invalid character: `
(156,47-48): run-time error JS1100: Expected ',': {
(156,67-68): run-time error JS1014: Invalid character: `
(157,5-6): run-time error JS1002: Syntax error: }
(158,33-34): run-time error JS1004: Expected ';': {
(169,1-2): run-time error JS1002: Syntax error: }
(171,39-40): run-time error JS1195: Expected expression: )
(171,41-42): run-time error JS1004: Expected ';': {
(668,48-49): run-time error JS1195: Expected expression: )
(668,51-52): run-time error JS1195: Expected expression: >
(670,1-2): run-time error JS1002: Syntax error: }
(690,46-47): run-time error JS1004: Expected ';': {
(723,11-12): run-time error JS1004: Expected ';': {
(725,41-42): run-time error JS1195: Expected expression: )
(725,44-45): run-time error JS1195: Expected expression: >
(730,51-52): run-time error JS1195: Expected expression: >
(730,80-81): run-time error JS1004: Expected ';': )
(732,10-11): run-time error JS1195: Expected expression: ,
(741,28-29): run-time error JS1004: Expected ';': {
(764,31-32): run-time error JS1195: Expected expression: )
(764,34-35): run-time error JS1195: Expected expression: >
(781,26-27): run-time error JS1004: Expected ';': {
(792,23-24): run-time error JS1004: Expected ';': {
(824,31-32): run-time error JS1004: Expected ';': {
(825,42-43): run-time error JS1195: Expected expression: )
(825,45-46): run-time error JS1195: Expected expression: >
(835,34-35): run-time error JS1004: Expected ';': {
(845,29-30): run-time error JS1004: Expected ';': {
(874,31-32): run-time error JS1004: Expected ';': {
(875,42-43): run-time error JS1195: Expected expression: )
(875,45-46): run-time error JS1195: Expected expression: >
(885,34-35): run-time error JS1004: Expected ';': {
(895,29-30): run-time error JS1004: Expected ';': {
(907,26-27): run-time error JS1004: Expected ';': {
(997,14-15): run-time error JS1004: Expected ';': {
(998,48-49): run-time error JS1195: Expected expression: >
(998,50-51): run-time error JS1197: Too many errors. The file might not be a JavaScript file: {
(915,13-19): run-time error JS1018: 'return' statement outside of function: return
(174,62-68): run-time error JS1018: 'return' statement outside of function: return
 */
// forEach method (crossbrowser)
function forEach(array, fn, scope) {
    for (var i = 0; i < array.length; i++) {
        fn.call(scope, i, array[i]);
    }
};
// closest method - if find "searching" element return that element else keep searching
function closest(el, fn) {
    return el && (fn(el) ? el : closest(el.parentNode, fn));
}
// call event only once
function oneTime (el, event, fn) {
    el.addEventListener(event, function (e) {
        fn();
        e.target.removeEventListener(e.type, arguments.callee);
    });
}
// contain class
function containClass (el, className) {
    if (el && typeof el.classList !== 'undefined') {
        return el.classList.contains(className);
    }
    return false;
}
// add listener for multiple events
function addListenerMultipleEvents (element, eventNames, listener) {
    var events = eventNames.split(' ');
    for (var i = 0, iLen = events.length; i < iLen; i++) {
        element.addEventListener(events[i], listener, false);
    }
}
// is mobile
function isMobile () {
    return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
}
// is function
function isFunc (obj) {
    return !!(obj && obj.constructor && obj.call && obj.apply);
}
// filters
function isSafari () {
    return navigator.userAgent.toLowerCase().match(/version\/(\d+).+?safari/) !== null;
}
// string to bool
function stringToBool (str) {
    return (str.toLowerCase() === "true" || str.toLowerCase() === "1" || str.toLowerCase() === "!0");
}
//// detect the supported event property name
function detectTransitionEvent() {
    var t, el = document.createElement("fakeelement");

    var transitions = {
        "transition": "transitionend",
        "OTransition": "oTransitionEnd",
        "MozTransition": "transitionend",
        "WebkitTransition": "webkitTransitionEnd"
    }

    for (t in transitions) {
        if (el.style[t] !== undefined) {
            return transitions[t];
        }
    }
};
var EventTracking = EventTracking || {};

EventTracking.trackEvent = function (customEvent, eventCategory, eventAction, data) {
    //if (Settings.debug) {
    //    console.log({
    //      "event": customEvent,
    //      "gaCategory": eventCategory,
    //      "gaAction": eventAction,
    //      "gaLabel": data
    //    });
    //}

    // GTM
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        'event': customEvent,
        'gaCategory': eventCategory,
        'gaAction': eventAction,
        'gaLabel': data
    });
};

EventTracking.init = function (element) {
    // Init event tracking within the specified element
    // If no element is specified, init even tracking in the entire document
    element = $(element || document);

    element.find(".t-c").each(function () {
        var profile = $(this).closest(".item-data");
        var myData = $(this).data("td") || {};

        if (typeof myData.id === "undefined" && typeof profile.data("id") !== "undefined") {
            myData.id = profile.data("id");
        }

        if (!$.isEmptyObject(myData)) {
            $(this).data("td", myData);
        }
    });

    element.find(".t-c").click(function () { EventTracking.trackingClick(this); });
    element.find(".t-om").click(function () { EventTracking.trackOpenModal(this); });
};

EventTracking.trackingClick = function (el, actionName) {
    var myPageType, myAction, myData, listingId, eventName;

    eventName = "click";

    // get folder child listing id from button url
    profile = document.getElementById("profile");
    if (profile) listingId = profile.dataset.id;

    // tracking data
    myPageType = Settings.pageType || "UNKNOWN";
    myAction = $(el).data("ta") || actionName || "UNKNOWN CLICK";
    myData = Settings.pageData || { actionData: { id: listingId } };

    if (typeof $(el).data("td") !== "undefined") {
        myData.actionData = $(el).data("td");
    }

    if (typeof $(el).data("ev") !== "undefined") {
        eventName = $(el).data("ev");
    }

    EventTracking.trackEvent(eventName, myPageType, myAction, JSON.stringify(myData));
};

//
EventTracking.trackProfileCardShown = function (resultId, resultPosition) {
    // Make sure variables in Settings are initialized
    Settings.var = Settings.var || {};
    Settings.var.profileCardsShown = Settings.var.profileCardsShown || 0;

    // Make copy of pageData
    var pageData = jQuery.extend(true, {}, Settings.pageData);

    pageData.l = resultId;
    pageData.lo = resultPosition;
    pageData.lc = ++Settings.var.profileCardsShown;

    // Emit 'profile card shown event'
    EventTracking.trackEvent(Settings.pageType, 'ProfileCardShown', JSON.stringify(pageData));
};
//
EventTracking.trackOpenModal = function (el) {
    var myPageType, myAction, myData;
    const profile = document.getElementById("profile");
    let ad = {};
    if (profile) {
        ad = { "actionData": { "listingId": `${profile.dataset.id}` } }
    }
    if ($(el).hasClass("t-om")) {
        myPageType = Settings.pageType || "UNKNOWN";
        myAction = $(el).data("tma") || "UNKNOWN CLICK";
        myData = Settings.pageData || ad;

        if (typeof $(el).data("td") !== "undefined") {
            myData.actionData = $(el).data("td");
        }

        EventTracking.trackEvent('modalOpen', myPageType, myAction, JSON.stringify(myData));
    }
};

EventTracking.trackFilter = function () {
    const myPageType = Settings.pageType || "UNKNOWN";
    // do not send if no filters selected
    if (HotFilters.parseFiltersForTagging() === "NoFilters") return;
    EventTracking.trackEvent("click", myPageType, "SearchFilterClick", JSON.stringify({ "actionData": HotFilters.parseFiltersForTagging() }));
};

EventTracking.modalSubmit = function (el) {
    var myData = Settings.pageData || {};

    if (typeof $(el).data("td") !== "undefined") {
        myData.actionData = $(el).data("td") || {};
    }

    var myPageType = Settings.pageType || "UNKNOWN";
    var myAction = $(el).data("ta") || "UNKNOWN SUBMIT";

    myAction = myAction + "Click";

    EventTracking.trackEvent('modalSubmitClick', myPageType, myAction, JSON.stringify(myData));
};

EventTracking.modalSubmitSuccess = function (el) {
    var btn, myPageType, myAction, myData;
    btn = $("#" + el).find(".t-mss");
    myPageType = Settings.pageType || "UNKNOWN";
    myAction = $(btn).data("ta") || "UNKNOWN SUCCESSFUL SUBMIT";
    myData = Settings.pageData || {};

    myAction = myAction + "Success";

    if (typeof $(btn).data("td") !== "undefined") {
        myData.actionData = $(btn).data("td");
    }

    EventTracking.trackEvent('modalSubmitSuccess', myPageType, myAction, JSON.stringify(myData));
};

$(document).ready(function () {
    // Don't initialize event tracking if it's disabled
    if (Settings.disableTracking === true) {
        return;
    }

    EventTracking.init();

    //// Track load event if page data is available
    //if (typeof Settings.pageType !== "undefined" && typeof Settings.pageData !== "undefined") {

    //    (function trackSort() {
    //        var w = window.location.search;
    //        if (w.length > 0) {
    //            var r = /[\?&](.+?)=([\w%,\.]+)/g;
    //            var m;

    //            do {
    //                m = r.exec(w);
    //                if (m && typeof m !== 'undefined') {
    //                    if (m[1].toLowerCase() === 'sort') {
    //                        Settings.pageData['sort'] = m[2].toLowerCase();
    //                        return;
    //                    }
    //                }
    //            } while (m);
    //        }
    //    })();

    //    EventTracking.trackEvent(Settings.pageType, "Load", JSON.stringify(Settings.pageData));
    //}
});
;
/*
	jQuery autoComplete v1.0.7
    Copyright (c) 2014 Simon Steinberger / Pixabay
    GitHub: https://github.com/Pixabay/jQuery-autoComplete
	License: http://www.opensource.org/licenses/mit-license.php
*/

(function ($) {
    $.fn.autoComplete = function (options) {
        var o = $.extend({}, $.fn.autoComplete.defaults, options);

        // public methods
        if (typeof options == 'string') {
            this.each(function () {
                var that = $(this);
                if (options == 'destroy') {
                    $(window).off('resize.autocomplete', that.updateSC);
                    that.off('blur.autocomplete focus.autocomplete keydown.autocomplete keyup.autocomplete');
                    if (that.data('autocomplete'))
                        that.attr('autocomplete', that.data('autocomplete'));
                    else
                        that.removeAttr('autocomplete');
                    $(that.data('sc')).remove();
                    that.removeData('sc').removeData('autocomplete');
                }
            });
            return this;
        }

        return this.each(function () {
            var that = $(this);
            var borderWidth = 2;

            // sc = 'suggestions container'
            that.sc = $('<div class="autocomplete-suggestions ' + o.menuClass + '"></div>');
            that.data('sc', that.sc).data('autocomplete', that.attr('autocomplete'));
            that.attr('autocomplete', 'off');
            that.cache = {};
            that.last_val = '';
            that.open_class = 'autocomplete-open';

            // show autocomplete and add open class to input
            that.showSC = function () {
                that.addClass(that.open_class);
                that.sc.show();
            }

            // hide autocomplete and add open class to input
            that.hideSC = function () {
                that.removeClass(that.open_class)
                that.sc.hide();
            }

            that.updateSC = function (resize, next) {
                that.sc.css({
                    top: that.offset().top + that.outerHeight(),
                    left: that.offset().left,
                });
                that.sc[0].style[window.innerWidth <= 480 ? 'width' : 'min-width'] = that.outerWidth() + 'px';
                if (!resize) {
                    that.showSC();
                    if (!that.sc.maxHeight) that.sc.maxHeight = parseInt(that.sc.css('max-height'));
                    if (!that.sc.suggestionHeight) that.sc.suggestionHeight = $('.autocomplete-suggestion', that.sc).first().outerHeight();
                    if (that.sc.suggestionHeight)
                        if (!next) that.sc.scrollTop(0);
                        else {
                            var scrTop = that.sc.scrollTop(), selTop = next.offset().top - that.sc.offset().top;
                            if (selTop + that.sc.suggestionHeight - that.sc.maxHeight > 0)
                                that.sc.scrollTop(selTop + that.sc.suggestionHeight + scrTop - that.sc.maxHeight);
                            else if (selTop < 0)
                                that.sc.scrollTop(selTop + scrTop);
                        }
                }
            }
            $(window).on('resize.autocomplete', that.updateSC);

            that.sc.appendTo('body');

            that.sc.on('mouseleave', '.autocomplete-suggestion', function () {
                $('.autocomplete-suggestion.selected').removeClass('selected');
            });

            that.sc.on('mouseenter', '.autocomplete-suggestion', function () {
                $('.autocomplete-suggestion.selected').removeClass('selected');
                $(this).addClass('selected');
            });

            that.sc.on('mousedown click', '.autocomplete-suggestion', function (e) {
                var item = $(this), v = item.data('val');
                if (v || item.hasClass('autocomplete-suggestion')) { // else outside click
                    that.val(v);
                    o.onSelect(e, v, item);
                    that.hideSC();
                }
                return false;
            });

            that.on('blur.autocomplete', function () {
                try { over_sb = $('.autocomplete-suggestions:hover').length; } catch (e) { over_sb = 0; } // IE7 fix :hover
                if (!over_sb) {
                    that.last_val = that.val();
                    that.hideSC();
                    setTimeout(function () { that.hideSC(); }, 350); // hide suggestions on fast input
                } else if (!that.is(':focus')) setTimeout(function () { that.focus(); }, 20);
            });

            if (!o.minChars) that.on('focus.autocomplete', function () { that.last_val = '\n'; that.trigger('keyup.autocomplete'); });

            function suggest(data) {
                var val = that.val();
                that.cache[val] = data;
                if (data.length && val.length >= o.minChars) {
                    var s = '';
                    for (var i = 0; i < data.length; i++) s += o.renderItem(data[i], val);
                    that.sc.html(s);
                    that.updateSC(0);
                }
                else
                    that.hideSC();
            }

            that.on('keydown.autocomplete', function (e) {
                // down (40), up (38)
                if ((e.which == 40 || e.which == 38) && that.sc.html()) {
                    var next, sel = $('.autocomplete-suggestion.selected', that.sc);
                    if (!sel.length) {
                        next = (e.which == 40) ? $('.autocomplete-suggestion', that.sc).first() : $('.autocomplete-suggestion', that.sc).last();
                        that.val(next.addClass('selected').data('val'));
                    } else {
                        next = (e.which == 40) ? sel.next('.autocomplete-suggestion') : sel.prev('.autocomplete-suggestion');
                        if (next.length) { sel.removeClass('selected'); that.val(next.addClass('selected').data('val')); }
                        else { sel.removeClass('selected'); that.val(that.last_val); next = 0; }
                    }
                    that.updateSC(0, next);
                    return false;
                }
                // esc
                else if (e.which == 27) that.val(that.last_val).sc.hide();
                // enter or tab
                else if (e.which == 13 || e.which == 9) {
                    var sel = $('.autocomplete-suggestion.selected', that.sc);
                    if (sel.length && that.sc.is(':visible')) { o.onSelect(e, sel.data('val'), sel); setTimeout(function () { that.hideSC(); }, 20); }
                }
            });

            that.on('keyup.autocomplete', function (e) {
                if (!~$.inArray(e.which, [13, 27, 35, 36, 37, 38, 39, 40])) {
                    var val = that.val();
                    if (val.length >= o.minChars) {
                        if (val != that.last_val) {
                            that.last_val = val;
                            clearTimeout(that.timer);
                            if (o.cache) {
                                if (val in that.cache) { suggest(that.cache[val]); return; }
                                // no requests if previous suggestions were empty
                                for (var i = 1; i < val.length - o.minChars; i++) {
                                    var part = val.slice(0, val.length - i);
                                    if (part in that.cache && !that.cache[part].length) { suggest([]); return; }
                                }
                            }
                            that.timer = setTimeout(function () { o.source(val, suggest) }, o.delay);
                        }
                    } else {
                        that.last_val = val;
                        that.hideSC();
                    }
                }
            });
        });
    }

    $.fn.autoComplete.defaults = {
        source: 0,
        minChars: 3,
        delay: 150,
        cache: 1,
        menuClass: '',
        renderItem: function (item, search) {
            // escape special characters
            search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
            var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
            return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
        },
        onSelect: function (e, term, item) { }
    };
}(jQuery));

function autocompleteInit() {
    var url = '/api/suggests/';
    var inputs = ["what", "where"];

    $.each(inputs, function (i, val) {
        $('#'+val).autoComplete({
            minChars: 2,
            delay: 400,
            menuClass: val,
            source:
            function (term, response) {
                try { xhr.abort(); } catch (e) { }
                xhr = $.getJSON(url + val + '/', { term: term }, function (data) { response(data); });
                //console.log('autosuggest term: '+ term +', val: ' + val);
            },
            onSelect: function (e, term, item) {
                //alert("select it")
            }
        });
    });
};

$(function () {
    autocompleteInit();
});;
//// shortlist
var Shortlist = Shortlist || {};

Shortlist.init = function (parentElem) {
    // get short list items on init
    this.updateShortlist();
    // add/remove item to/from short list
    this.handleFavouriteClick(parentElem);
}

Shortlist.getId = function (t) {
    if (typeof t !== "undefined" && t.getAttribute("data-id") !== null) {
        return t.getAttribute("data-id");
    }

    var c = closest(t.parentElement, function (el) {
        return el.getAttribute("data-id") !== null;
    });

    var id = c.getAttribute("data-id");

    return id;
};

Shortlist.eventTracking = function () {
    var myData = Settings.pageData || {};

    if (typeof Settings.listingId !== 'undefined') {
        myData.actionData = { id: Settings.listingId };
    }

    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        'event': 'click',
        'gaCategory': Settings.pageType || "UKNOWN CATEGORY",
        'gaAction': 'FavouritesButtonClick',
        'gaLabel': JSON.stringify(myData) || '{}'
    });
};

Shortlist.handleFavouriteClick = function (elem) {
    var searchResults = elem ? document.querySelectorAll(elem + " .result-item") : document.querySelectorAll(".result-item");
    var folderResults = document.querySelectorAll("#folder-child-addresses > li");
    var addresses = document.querySelector("#folder-child-addresses");

    var results = [];

    if (searchResults.length) {
        results = searchResults;
    }

    if (folderResults.length && !addresses.classList.contains("initialized")) {
        results = folderResults;
        addresses.classList.add("initialized");
    }

    if (results.length === 0) {
        results = [document.querySelector(".favourite-btn__wrap")];
    }

    results.forEach(function (result) {
        Shortlist.favouriteBtnEventListener(result);
    });
};

Shortlist.favouriteBtnEventListener = function (result) {
    if (!result) return;
    var favouriteBtn = result.querySelector("#GO__favourite-btn");

    favouriteBtn.addEventListener("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        Shortlist.addOrRemove(this);
        Shortlist.eventTracking();
        return false;
    });
}

Shortlist.addOrRemove = function (t) {
    this.id = this.getId(t);
    var results = document.querySelector(".result-items");

    if (!t.classList.contains("added")) {
        this.addToShortlist();
    } else {
        if (results && results.classList.contains("shortlist")) {
            this.removeFromShortlistResults();
        } else {
            this.removeFromShortlist();
        }
    }

    t.classList.toggle("added");

    if (document.querySelector('.results-clone')) {
        var a = document.querySelector('.result-items > [data-id=' + this.id + '] .card__favourite');
        a.classList.toggle('added');
    }

    this.updateShortlist();
};

// add result item to shortlist
Shortlist.addToShortlist = function () {
    // has id
    if (this.id === undefined) return;

    // add to cookie
    var cookieName = "_shortList";
    var ypCookie = getCookie(cookieName);
    var newCookieContent = this.id + (ypCookie.length === 0 ? "" : "," + ypCookie);
    // save to cookie
    setCookie(cookieName, newCookieContent, 365);
    // animate clone
    this.cloneResultItem();
}

// get shortlist items
Shortlist.getShortlist = function () {
    var c = getCookie("_shortList");
    var l = [];

    if (c != "") {
        var rx = /\w\d+/gm;
        while ((m = rx.exec(c)) !== null) {
            l.push(m[0]);
        }
    }
    return l;
}

// update shortlist
Shortlist.updateShortlist = function () {
    var c = this.getShortlist().length;
    var badge = document.querySelector("#shortlist .badge");
    badge.innerHTML = c;

    if (c > 0) {
        badge.classList.remove("hidden");
    } else if (!badge.classList.contains("hidden")) {
        badge.classList.add("hidden");
    }
}

// remove result item from shortlist
Shortlist.removeFromShortlist = function () {
    var shortlist = this.getShortlist();
    var idIndex = shortlist.indexOf(this.id);

    if (idIndex != -1) shortlist.splice(idIndex, 1);

    setCookie("_shortList", shortlist.join(','), 365);
    this.updateShortlist();
}

// clone result item for animation
Shortlist.cloneResultItem = function () {
    var _this = this;

    var $el = $("[data-id='" + _this.id + "']");
    var $sl = $("#shortlist");
    var $resultClone = $el.clone();
    var cloneCss = {
        "width": $el.outerWidth() + "px",
        "top": $el.offset().top + "px",
        "left": $el.offset().left + "px",
        "position": "absolute",
        "z-index": "10002",
        "background-color": "#fff",
        "margin": "0",
        "padding": "15px 5px",
        "list-style": "none",
        "border-bottom": "1px solid #e2e2e2",
    }

    // set css to clone and append to body
    $resultClone.css(cloneCss);
    $resultClone.appendTo("body");

    // start animate when done remove it from DOM
    $.when($resultClone.animate({
        top: $sl.offset().top + "px",
        left: $sl.offset().left + "px",
        width: "25px",
        height: "2px",
        opacity: 0.2
    })).done(function () {
        $(this).remove();
        // update counter
        _this.updateShortlist();
    });
}

// remove shortlist item
Shortlist.removeFromShortlistResults = function () {
    var _this = this; 

    var $el = $("[data-id='" + _this.id + "']");
    var $cel = $(".result-info__count .count");
    var c = parseInt($cel.text());

    $.when($el.animate({
        height: 0,
        paddingTop: 0,
        paddingBottom: 0,
        opacity: 0,
        overflow: "hidden",
    })).done(function () {
        $(this).remove();
        $cel.text(--c)
        _this.removeFromShortlist(_this.id);
    });
}

document.addEventListener('DOMContentLoaded', () => {
    Shortlist.init();
});;

/**
 * Sticky.js
 * Library for sticky elements written in vanilla javascript. With this library you can easily set sticky elements on your website. It's also responsive.
 *
 * @version 1.3.0
 * @author Rafal Galus <biuro@rafalgalus.pl>
 * @website https://rgalus.github.io/sticky-js/
 * @repo https://github.com/rgalus/sticky-js
 * @license https://github.com/rgalus/sticky-js/blob/master/LICENSE
 */

class Sticky {
    /**
     * Sticky instance constructor
     * @constructor
     * @param {string} selector - Selector which we can find elements
     * @param {string} options - Global options for sticky elements (could be overwritten by data-{option}="" attributes)
     */
    constructor(selector = '', options = {}) {
        this.selector = selector;
        this.elements = [];

        this.version = '1.3.0';

        this.vp = this.getViewportSize();
        this.body = document.querySelector('body');

        this.options = {
            wrap: options.wrap || false,
            wrapWith: options.wrapWith || '<span></span>',
            marginTop: options.marginTop || 0,
            marginBottom: options.marginBottom || 0,
            stickyFor: options.stickyFor || 0,
            stickyClass: options.stickyClass || null,
            stickyContainer: options.stickyContainer || 'body',
        };

        this.updateScrollTopPosition = this.updateScrollTopPosition.bind(this);

        this.updateScrollTopPosition();
        window.addEventListener('load', this.updateScrollTopPosition);
        window.addEventListener('scroll', this.updateScrollTopPosition);

        this.run();
    }


    /**
     * Function that waits for page to be fully loaded and then renders & activates every sticky element found with specified selector
     * @function
     */
    run() {
        // wait for page to be fully loaded
        const pageLoaded = setInterval(() => {
            if (document.readyState === 'complete') {
                clearInterval(pageLoaded);

                const elements = document.querySelectorAll(this.selector);
                this.forEach(elements, (element) => this.renderElement(element));
            }
        }, 10);
    }


    /**
     * Function that assign needed variables for sticky element, that are used in future for calculations and other
     * @function
     * @param {node} element - Element to be rendered
     */
    renderElement(element) {
        // create container for variables needed in future
        element.sticky = {};

        // set default variables
        element.sticky.active = false;

        element.sticky.marginTop = parseInt(element.getAttribute('data-margin-top')) || this.options.marginTop;
        element.sticky.marginBottom = parseInt(element.getAttribute('data-margin-bottom')) || this.options.marginBottom;
        element.sticky.stickyFor = parseInt(element.getAttribute('data-sticky-for')) || this.options.stickyFor;
        element.sticky.stickyClass = element.getAttribute('data-sticky-class') || this.options.stickyClass;
        element.sticky.wrap = element.hasAttribute('data-sticky-wrap') ? true : this.options.wrap;
        // @todo attribute for stickyContainer
        // element.sticky.stickyContainer = element.getAttribute('data-sticky-container') || this.options.stickyContainer;
        element.sticky.stickyContainer = this.options.stickyContainer;

        element.sticky.container = this.getStickyContainer(element);
        element.sticky.container.rect = this.getRectangle(element.sticky.container);

        element.sticky.rect = this.getRectangle(element);

        // fix when element is image that has not yet loaded and width, height = 0
        if (element.tagName.toLowerCase() === 'img') {
            element.onload = () => element.sticky.rect = this.getRectangle(element);
        }

        if (element.sticky.wrap) {
            this.wrapElement(element);
        }

        // activate rendered element
        this.activate(element);
    }


    /**
     * Wraps element into placeholder element
     * @function
     * @param {node} element - Element to be wrapped
     */
    wrapElement(element) {
        element.insertAdjacentHTML('beforebegin', element.getAttribute('data-sticky-wrapWith') || this.options.wrapWith);
        element.previousSibling.appendChild(element);
    }


    /**
     * Function that activates element when specified conditions are met and then initalise events
     * @function
     * @param {node} element - Element to be activated
     */
    activate(element) {
        if (
            ((element.sticky.rect.top + element.sticky.rect.height) < (element.sticky.container.rect.top + element.sticky.container.rect.height))
            && (element.sticky.stickyFor < this.vp.width)
            && !element.sticky.active
        ) {
            element.sticky.active = true;
        }

        if (this.elements.indexOf(element) < 0) {
            this.elements.push(element);
        }

        if (!element.sticky.resizeEvent) {
            this.initResizeEvents(element);
            element.sticky.resizeEvent = true;
        }

        if (!element.sticky.scrollEvent) {
            this.initScrollEvents(element);
            element.sticky.scrollEvent = true;
        }

        this.setPosition(element);
    }


    /**
     * Function which is adding onResizeEvents to window listener and assigns function to element as resizeListener
     * @function
     * @param {node} element - Element for which resize events are initialised
     */
    initResizeEvents(element) {
        element.sticky.resizeListener = () => this.onResizeEvents(element);
        window.addEventListener('resize', element.sticky.resizeListener);
    }


    /**
     * Removes element listener from resize event
     * @function
     * @param {node} element - Element from which listener is deleted
     */
    destroyResizeEvents(element) {
        window.removeEventListener('resize', element.sticky.resizeListener);
    }


    /**
     * Function which is fired when user resize window. It checks if element should be activated or deactivated and then run setPosition function
     * @function
     * @param {node} element - Element for which event function is fired
     */
    onResizeEvents(element) {
        this.vp = this.getViewportSize();

        element.sticky.rect = this.getRectangle(element);
        element.sticky.container.rect = this.getRectangle(element.sticky.container);

        if (
            ((element.sticky.rect.top + element.sticky.rect.height) < (element.sticky.container.rect.top + element.sticky.container.rect.height))
            && (element.sticky.stickyFor < this.vp.width)
            && !element.sticky.active
        ) {
            element.sticky.active = true;
        } else if (
            ((element.sticky.rect.top + element.sticky.rect.height) >= (element.sticky.container.rect.top + element.sticky.container.rect.height))
            || element.sticky.stickyFor >= this.vp.width
            && element.sticky.active
        ) {
            element.sticky.active = false;
        }

        this.setPosition(element);
    }


    /**
     * Function which is adding onScrollEvents to window listener and assigns function to element as scrollListener
     * @function
     * @param {node} element - Element for which scroll events are initialised
     */
    initScrollEvents(element) {
        element.sticky.scrollListener = () => this.onScrollEvents(element);
        window.addEventListener('scroll', element.sticky.scrollListener);
    }


    /**
     * Removes element listener from scroll event
     * @function
     * @param {node} element - Element from which listener is deleted
     */
    destroyScrollEvents(element) {
        window.removeEventListener('scroll', element.sticky.scrollListener);
    }


    /**
     * Function which is fired when user scroll window. If element is active, function is invoking setPosition function
     * @function
     * @param {node} element - Element for which event function is fired
     */
    onScrollEvents(element) {
        if (element.sticky && element.sticky.active) {
            this.setPosition(element);
        }
    }


    /**
     * Main function for the library. Here are some condition calculations and css appending for sticky element when user scroll window
     * @function
     * @param {node} element - Element that will be positioned if it's active
     */
    setPosition(element) {
        const topBar = document.querySelector(".top-bar");
        this.css(element, { position: '', width: '', top: '', left: '', zIndex: '999' });
        if (topBar) {
            this.css(topBar, { marginBottom: '' });
        }

        if ((this.vp.height < element.sticky.rect.height) || !element.sticky.active) {
            return;
        }

        if (!element.sticky.rect.width) {
            element.sticky.rect = this.getRectangle(element);
        }

        if (element.sticky.wrap) {
            this.css(element.parentNode, {
                display: 'block',
                width: element.sticky.rect.width + 'px',
                height: element.sticky.rect.height + 'px',
            });
        }

        if (
            element.sticky.rect.top === 0
            && element.sticky.container === this.body
        ) {
            this.css(element, {
                position: 'fixed',
                top: element.sticky.rect.top + 'px',
                left: element.sticky.rect.left + 'px',
                width: element.sticky.rect.width + 'px',
            });
            if (topBar) {
                this.css(topBar, {
                    marginBottom: element.sticky.rect.height + 'px'
                });
            }
            if (element.sticky.stickyClass) {
                element.classList.add(element.sticky.stickyClass);
            }
        } else if (this.scrollTop > (element.sticky.rect.top - element.sticky.marginTop)) {
            this.css(element, {
                position: 'fixed',
                width: element.sticky.rect.width + 'px',
                left: element.sticky.rect.left + 'px',
            });
            if (topBar) {
                this.css(topBar, {
                    marginBottom: element.sticky.rect.height + 'px'
                });
            }
            if (
                (this.scrollTop + element.sticky.rect.height + element.sticky.marginTop)
                > (element.sticky.container.rect.top + element.sticky.container.offsetHeight - element.sticky.marginBottom)
            ) {

                if (element.sticky.stickyClass) {
                    element.classList.remove(element.sticky.stickyClass);
                }

                this.css(element, {
                    top: (element.sticky.container.rect.top + element.sticky.container.offsetHeight) - (this.scrollTop + element.sticky.rect.height + element.sticky.marginBottom) + 'px'
                }
                );
            } else {
                if (element.sticky.stickyClass) {
                    element.classList.add(element.sticky.stickyClass);
                }

                this.css(element, { top: element.sticky.marginTop + 'px' });
            }
        } else {
            if (element.sticky.stickyClass) {
                element.classList.remove(element.sticky.stickyClass);
            }

            this.css(element, { position: '', width: '', top: '', left: '' });

            if (element.sticky.wrap) {
                this.css(element.parentNode, { display: '', width: '', height: '' });
            }
        }
    }


    /**
     * Function that updates element sticky rectangle (with sticky container), then activate or deactivate element, then update position if it's active
     * @function
     */
    update() {
        this.forEach(this.elements, (element) => {
            element.sticky.rect = this.getRectangle(element);
            element.sticky.container.rect = this.getRectangle(element.sticky.container);

            this.activate(element);
            this.setPosition(element);
        });
    }


    /**
     * Destroys sticky element, remove listeners
     * @function
     */
    destroy() {
        window.removeEventListener('load', this.updateScrollTopPosition);
        window.removeEventListener('scroll', this.updateScrollTopPosition);

        this.forEach(this.elements, (element) => {
            this.destroyResizeEvents(element);
            this.destroyScrollEvents(element);
            delete element.sticky;
        });
    }


    /**
     * Function that returns container element in which sticky element is stuck (if is not specified, then it's stuck to body)
     * @function
     * @param {node} element - Element which sticky container are looked for
     * @return {node} element - Sticky container
     */
    getStickyContainer(element) {
        let container = element.parentNode;

        while (
            !container.hasAttribute('data-sticky-container')
            && !container.parentNode.querySelector(element.sticky.stickyContainer)
            && container !== this.body
        ) {
            container = container.parentNode;
        }

        return container;
    }


    /**
     * Function that returns element rectangle & position (width, height, top, left)
     * @function
     * @param {node} element - Element which position & rectangle are returned
     * @return {object}
     */
    getRectangle(element) {
        this.css(element, { position: '', width: '', top: '', left: '' });

        const width = Math.max(element.offsetWidth, element.clientWidth, element.scrollWidth);
        const height = Math.max(element.offsetHeight, element.clientHeight, element.scrollHeight);

        let top = 0;
        let left = 0;

        do {
            top += element.offsetTop || 0;
            left += element.offsetLeft || 0;
            element = element.offsetParent;
        } while (element);

        return { top, left, width, height };
    }


    /**
     * Function that returns viewport dimensions
     * @function
     * @return {object}
     */
    getViewportSize() {
        return {
            width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
            height: Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
        };
    }


    /**
     * Function that updates window scroll position
     * @function
     * @return {number}
     */
    updateScrollTopPosition() {
        this.scrollTop = (window.pageYOffset || document.scrollTop) - (document.clientTop || 0) || 0;
    }


    /**
     * Helper function for loops
     * @helper
     * @param {array}
     * @param {function} callback - Callback function (no need for explanation)
     */
    forEach(array, callback) {
        for (let i = 0, len = array.length; i < len; i++) {
            callback(array[i]);
        }
    }


    /**
     * Helper function to add/remove css properties for specified element.
     * @helper
     * @param {node} element - DOM element
     * @param {object} properties - CSS properties that will be added/removed from specified element
     */
    css(element, properties) {
        for (let property in properties) {
            if (properties.hasOwnProperty(property)) {
                element.style[property] = properties[property];
            }
        }
    }
}


/**
 * Export function that supports AMD, CommonJS and Plain Browser.
 */
((root, factory) => {
    if (typeof exports !== 'undefined') {
        module.exports = factory;
    } else if (typeof define === 'function' && define.amd) {
        define([], function () {
            return factory;
        });
    } else {
        root.Sticky = factory;
    }
})(this, Sticky);;
/**
 * @preserve
 * Sharer.js
 *
 * @description Create your own social share buttons
 * @version 0.3.8
 * @author Ellison Leao <ellisonleao@gmail.com>
 * @license GPLv3
 *
 */

(function (window, document) {
    'use strict';
    /**
     * @constructor
     */
    var Sharer = function (elem) {
        this.elem = elem;
    };

    /**
     *  @function init
     *  @description bind the events for multiple sharer elements
     *  @returns {Empty}
     */
    Sharer.init = function () {
        var elems = document.querySelectorAll('[data-sharer]'),
            i,
            l = elems.length;

        for (i = 0; i < l; i++) {
            elems[i].addEventListener('click', Sharer.add);
        }
    };

    /**
     *  @function add
     *  @description bind the share event for a single dom element
     *  @returns {Empty}
     */
    Sharer.add = function (elem) {
        var target = elem.currentTarget || elem.srcElement;
        var sharer = new Sharer(target);
        sharer.share();
    };

    // instance methods
    Sharer.prototype = {
        constructor: Sharer,
        /**
         *  @function getValue
         *  @description Helper to get the attribute of a DOM element
         *  @param {String} attr DOM element attribute
         *  @returns {String|Empty} returns the attr value or empty string
         */
        getValue: function (attr) {
            var val = this.elem.getAttribute('data-' + attr);
            // handing facebook hashtag attribute
            if (val && attr === 'hashtag') {
                if (!val.startsWith('#')) {
                    val = '#' + val;
                }
            }
            return val;
        },

        /**
         * @event share
         * @description Main share event. Will pop a window or redirect to a link
         * based on the data-sharer attribute.
         */
        share: function () {
            var sharer = this.getValue('sharer').toLowerCase(),
                sharers = {
                    facebook: {
                        shareUrl: 'https://www.facebook.com/sharer/sharer.php',
                        params: {
                            u: this.getValue('url'),
                            hashtag: this.getValue('hashtag')
                        }
                    },
                    messenger: {
                        shareUrl: 'https://www.facebook.com/dialog/send',
                        params: {                         
                            app_id: this.getValue('app_id'),
                            link: this.getValue('url'),
                            redirect_uri: this.getValue('redirect_url'),
                            display: this.getValue('display')
                        }
                    },
                    linkedin: {
                        shareUrl: 'https://www.linkedin.com/shareArticle',
                        params: {
                            url: this.getValue('url'),
                            mini: true
                        }
                    },
                    twitter: {
                        shareUrl: 'https://twitter.com/intent/tweet/',
                        params: {
                            text: this.getValue('title'),
                            url: this.getValue('url'),
                            hashtags: this.getValue('hashtags'),
                            via: this.getValue('via')
                        }
                    },
                    email: {
                        shareUrl: 'mailto:' + this.getValue('to') || '',
                        params: {
                            subject: this.getValue('subject'),
                            body: this.getValue('title') + '\n' + this.getValue('url')
                        },
                        isLink: true
                    },
                    whatsapp: {
                        shareUrl: this.getValue('web') !== null ? 'https://api.whatsapp.com/send' : 'whatsapp://send',
                        params: {
                            text: this.getValue('title') + ' ' + this.getValue('url')
                        },
                        isLink: true
                    },
                    telegram: {
                        shareUrl: 'tg://msg_url',
                        params: {
                            text: this.getValue('title'),
                            url: this.getValue('url'),
                            to: this.getValue('to')
                        },
                        isLink: true
                    },
                    viber: {
                        shareUrl: 'viber://forward',
                        params: {
                            text: this.getValue('title') + ' ' + this.getValue('url')
                        },
                        isLink: true
                    },
                    line: {
                        shareUrl:
                            'http://line.me/R/msg/text/?' +
                            encodeURIComponent(this.getValue('title') + ' ' + this.getValue('url')),
                        isLink: true
                    },
                    pinterest: {
                        shareUrl: 'https://www.pinterest.com/pin/create/button/',
                        params: {
                            url: this.getValue('url'),
                            media: this.getValue('image'),
                            description: this.getValue('description')
                        }
                    },
                    tumblr: {
                        shareUrl: 'http://tumblr.com/widgets/share/tool',
                        params: {
                            canonicalUrl: this.getValue('url'),
                            content: this.getValue('url'),
                            posttype: 'link',
                            title: this.getValue('title'),
                            caption: this.getValue('caption'),
                            tags: this.getValue('tags')
                        }
                    },
                    hackernews: {
                        shareUrl: 'https://news.ycombinator.com/submitlink',
                        params: {
                            u: this.getValue('url'),
                            t: this.getValue('title')
                        }
                    },
                    reddit: {
                        shareUrl: 'https://www.reddit.com/submit',
                        params: { url: this.getValue('url') }
                    },
                    vk: {
                        shareUrl: 'http://vk.com/share.php',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title'),
                            description: this.getValue('caption'),
                            image: this.getValue('image')
                        }
                    },
                    xing: {
                        shareUrl: 'https://www.xing.com/app/user',
                        params: {
                            op: 'share',
                            url: this.getValue('url'),
                            title: this.getValue('title')
                        }
                    },
                    buffer: {
                        shareUrl: 'https://buffer.com/add',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title'),
                            via: this.getValue('via'),
                            picture: this.getValue('picture')
                        }
                    },
                    instapaper: {
                        shareUrl: 'http://www.instapaper.com/edit',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title'),
                            description: this.getValue('description')
                        }
                    },
                    pocket: {
                        shareUrl: 'https://getpocket.com/save',
                        params: {
                            url: this.getValue('url')
                        }
                    },
                    digg: {
                        shareUrl: 'http://www.digg.com/submit',
                        params: {
                            url: this.getValue('url')
                        }
                    },
                    stumbleupon: {	// Usage deprecated, leaving for backwards compatibility.
                        shareUrl: 'http://www.stumbleupon.com/submit',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title')
                        }
                    },
                    mix: {
                        shareUrl: 'https://mix.com/add',
                        params: {
                            url: this.getValue('url')
                        }
                    },
                    flipboard: {
                        shareUrl: 'https://share.flipboard.com/bookmarklet/popout',
                        params: {
                            v: 2,
                            title: this.getValue('title'),
                            url: this.getValue('url'),
                            t: Date.now()
                        }
                    },
                    weibo: {
                        shareUrl: 'http://service.weibo.com/share/share.php',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title'),
                            pic: this.getValue('image'),
                            appkey: this.getValue('appkey'),
                            ralateUid: this.getValue('ralateuid'),
                            language: 'zh_cn'
                        }
                    },
                    renren: {
                        shareUrl: 'http://share.renren.com/share/buttonshare',
                        params: {
                            link: this.getValue('url')
                        }
                    },
                    myspace: {
                        shareUrl: 'https://myspace.com/post',
                        params: {
                            u: this.getValue('url'),
                            t: this.getValue('title'),
                            c: this.getValue('description')
                        }
                    },
                    blogger: {
                        shareUrl: 'https://www.blogger.com/blog-this.g',
                        params: {
                            u: this.getValue('url'),
                            n: this.getValue('title'),
                            t: this.getValue('description')
                        }
                    },
                    baidu: {
                        shareUrl: 'http://cang.baidu.com/do/add',
                        params: {
                            it: this.getValue('title'),
                            iu: this.getValue('url')
                        }
                    },
                    douban: {
                        shareUrl: 'https://www.douban.com/share/service',
                        params: {
                            name: this.getValue('title'),
                            href: this.getValue('url'),
                            image: this.getValue('image')
                        }
                    },
                    okru: {
                        shareUrl: 'https://connect.ok.ru/dk',
                        params: {
                            'st.cmd': 'WidgetSharePreview',
                            'st.shareUrl': this.getValue('url'),
                            title: this.getValue('title')
                        }
                    },
                    mailru: {
                        shareUrl: 'http://connect.mail.ru/share',
                        params: {
                            share_url: this.getValue('url'),
                            linkname: this.getValue('title'),
                            linknote: this.getValue('description'),
                            type: 'page'
                        }
                    },
                    evernote: {
                        shareUrl: 'http://www.evernote.com/clip.action',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title')
                        }
                    },
                    skype: {
                        shareUrl: 'https://web.skype.com/share',
                        params: {
                            url: this.getValue('url'),
                            title: this.getValue('title')
                        }
                    }
                },
                s = sharers[sharer];

            // custom popups sizes
            if (s) {
                s.width = this.getValue('width');
                s.height = this.getValue('height');
            }
            return s !== undefined ? this.urlSharer(s) : false;
        },
        /**
         * @event urlSharer
         * @param {Object} sharer
         */
        urlSharer: function (sharer) {
            var p = sharer.params || {},
                keys = Object.keys(p),
                i,
                str = keys.length > 0 ? '?' : '';
            for (i = 0; i < keys.length; i++) {
                if (str !== '?') {
                    str += '&';
                }
                if (p[keys[i]]) {
                    str += keys[i] + '=' + encodeURIComponent(p[keys[i]]);
                }
            }
            sharer.shareUrl += str;

            if (!sharer.isLink) {
                var popWidth = sharer.width || 600,
                    popHeight = sharer.height || 480,
                    left = window.innerWidth / 2 - popWidth / 2 + window.screenX,
                    top = window.innerHeight / 2 - popHeight / 2 + window.screenY,
                    popParams =
                        'scrollbars=no, width=' +
                        popWidth +
                        ', height=' +
                        popHeight +
                        ', top=' +
                        top +
                        ', left=' +
                        left,
                    newWindow = window.open(sharer.shareUrl, '', popParams);

                if (window.focus) {
                    newWindow.focus();
                }
            } else {
                //window.location.href = sharer.shareUrl;
                var win = window.open(sharer.shareUrl, '_blank');
                win.focus();
            }
        }
    };

    // adding sharer events on domcontentload
    if (document.readyState === 'complete' || document.readyState !== 'loading') {
        Sharer.init();
    } else {
        document.addEventListener('DOMContentLoaded', Sharer.init);
    }

    // turbolinks 3 compatibility
    window.addEventListener('page:load', Sharer.init);

    // turbolinks 5 compatibility
    window.addEventListener('turbolinks:load', Sharer.init);

    // exporting sharer for external usage
    window.Sharer = Sharer;
})(window, document);;
var Main = {};

Main.isMobile = () => {
    let check = false;
    (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || window.opera);
    return check;
}

// handle language menu
Main.handleLangMenu = (opt) => {
    if (!opt.link) return;

    opt.link.addEventListener("click", function (e) {
        e.preventDefault();
        e.stopPropagation();

        if (opt.list.classList.contains("hidden")) {
            opt.list.classList.remove("hidden");
            opt.icon.classList.add("rotate-180");
        } else {
            opt.list.classList.add("hidden");
            opt.icon.classList.remove("rotate-180");
        }
    });
}
Main.closeLangMenu = (opt, elem) => {
    elem.addEventListener("click", function () {

        if (!opt.list.classList.contains("hidden")) {
            opt.list.classList.add("hidden");
            opt.icon.classList.remove("rotate-180");
        }
    });
}
Main.initLangMenu = () => {
    const menu = document.querySelectorAll("#language-switch");
    forEach(menu, function (_, item) { 
        const link = item.querySelector("a");
        const icon = link.querySelector("svg");
        const list = item.querySelector("ul");

        const options = {
            menu: item,
            link,
            icon,
            list
        };

        Main.handleLangMenu(options);
        Main.closeLangMenu(options, document);
    })
}

// handle accordion
Main.accordion = (id, leaveItOpen = false) => {
    if (id == undefined) return;
    const accordion = document.getElementById(id);
    if (accordion == null) return;
    const ITEM = "accordion-item";

    const items = accordion.querySelectorAll(`.${ITEM}`);
    [...items].map((item) => {
        const header = item.querySelector(`.${ITEM}__header`);
        const body = item.querySelector(`.${ITEM}__body`);
        const arrow = item.querySelector(`.${ITEM}__arrow`);
        if (header == null || body == null || arrow == null) return;

        header.addEventListener("click", (e) => {
            if (leaveItOpen) {
                // close open one
                const openItem = accordion.querySelector(".open");
                if (openItem == null) return;
                openItem.classList.toggle("open");
                const openArrow = openItem.querySelector(`.${ITEM}__arrow`);
                const openBody = openItem.querySelector(`.${ITEM}__body`);
                openArrow.classList.toggle("text-blue-600");
                openArrow.classList.toggle("rotate-180");
                openBody.classList.toggle("hidden");
            }

            // open choosen one
            item.classList.toggle("open");
            arrow.classList.toggle("rotate-180");
            arrow.classList.toggle("text-gray-100");
            arrow.classList.toggle("text-blue-600");
            body.classList.toggle("hidden");
        })
    })

}

// handle cateogries on mobile devices
Main.handleCategories = (id) => {
    const categoriesBtn = document.getElementById("blog-categories__btn");
    const categories = document.getElementById(id);
    if (!categories || !categoriesBtn) return
    // open categories on click
    categoriesBtn.addEventListener("click", () => {
        categories.classList.toggle("hidden");
        categories.classList.toggle("blog-cateogries--active");

        categoriesBtn.classList.toggle("blog-categories--close");
        if (categoriesBtn.innerText == "x") {
            categoriesBtn.innerText = categoriesBtn.getAttribute("btn-label");
        } else {
            categoriesBtn.setAttribute("btn-label", categoriesBtn.innerText);
            categoriesBtn.innerText = "x";
        }
    }); 
}

// set cookie
function setCookie(cname, cvalue, exdays) {
    let d = new Date();
    let expires = "";

    if (exdays) {
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        expires = ";expires=" + d.toUTCString();
    }

    document.cookie = `${cname}=${cvalue}${expires};path=/`;
}
// get cookie
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
//// horizontal list
function initHorizontalList(element) {
    element = element || document;
    var list, isDown, speed, down, up, startX, scrollLeft;
    list = element.querySelectorAll('.horizontal-list');
    isDown = false;
    speed = 1.5;

    function addListeners(list) {
        var scroll = list.querySelector('.horizontal-list__items');

        list.addEventListener('mousedown', function (e) {
            down = e.pageX;
            isDown = true;
            list.classList.add('active');
            startX = e.pageX - scroll.offsetLeft;
            scrollLeft = scroll.scrollLeft;
        });
        list.addEventListener('mouseleave', function () {
            isDown = false;
            list.classList.remove('active');
        });
        list.addEventListener('mouseup', function (e) {
            up = e.pageX;
            isDown = false;
            list.classList.remove('active');
            if (down != up) {
                list.classList.add("no-actions-allow");
            } else {
                list.classList.remove("no-actions-allow");
            }
        });
        list.addEventListener('mousemove', function (e) {
            if (!isDown) {
                return;
            }
            e.preventDefault();
            var x = e.pageX - scroll.offsetLeft;
            var walk = (x - startX) * speed;
            scroll.scrollLeft = scrollLeft - walk;
        });
    }

    function hideScrollbar(item) {
        var horizontalItem = item.querySelector("[class*='blog-horizontal__item']");
        if (!horizontalItem) return;
        item.style.height = horizontalItem.getBoundingClientRect().height + "px";
        item.style.overflow = "hidden";
    }

    forEach(list, function (_, item) {
        hideScrollbar(item);
        addListeners(item);
    });
}
// ad
function getAdItem(item) {
    var ads = ['iframe', 'canvas', 'img'];
    for (var key in ads) {
        var i = item.querySelector(ads[key]);
        if (i !== null) return i;
    }
    return false;
}
//// maresponsive ads
function makeAdsResponsive(classBox) {
    window.addEventListener('resize', () => resizeCanvas(classBox));
    resizeCanvas(classBox);

    function resizeCanvas(classBox) {
        const iframeWraps = [...document.querySelectorAll(".iframeWrap")].filter(c => !c.classList.contains(classBox));
        const mobile = isMobile();

        iframeWraps.map(item => {
            // skip it if ad is on mobile and we don't want to fit it
            if (mobile && !item.classList.contains('iframeWrap--mobile'))  return;

            const ad = getAdItem(item);
            const w = item.offsetWidth;
            const h = ad ? ad.offsetHeight : 0;
            const defaultWidth = ad ? ad.offsetWidth : 0;

            if (h === 0) {
                item.parentElement.style.height = 0;
                item.style.margin = 0;
            }

            if (defaultWidth > 0 && defaultWidth !== w) {
                const ratio = w / defaultWidth;  
                ad.style.transform = "scale(" + ratio + ")";
                ad.style.transformOrigin = "left top 0";
                item.style.height = (h * ratio) + "px";
                item.style.overflow = 'hidden';
            }
        });
    }
}
//// hide empty banner box
function hideEmptyAdBox() {
    var b = document.querySelectorAll('.banner-box');

    forEach(b, function (_, box) {
        var img = box.querySelector('img');
        var iframe = box.querySelector('iframe');
        var div = box.querySelector('.card');

        if ((img && img.height <= 1 || iframe && iframe.height == 0) && div === null) {
            box.classList.add('hidden');
        }
    });
}
// set dropdown box position and dimensions
function setDropDownPosition(btn, dropdown) {
    var rect = btn.getBoundingClientRect();
    var h = document.getElementById('header');
    var isFixed = (getComputedStyle(h).position == 'fixed');
    var w = window.innerWidth;
    var d = dropdown.offsetWidth;
    var scrollTop = Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop);

    btn.offset = {
        top: rect.top + (isFixed ? 0 : scrollTop),
        left: rect.left + (isFixed ? 0 : document.documentElement.scrollLeft)
    };

    dropdown.style.top = btn.offset.top + btn.offsetHeight + 'px';
    dropdown.style.left = (w - btn.offset.left < d ? w - d : btn.offset.left) + 'px';

    if (isFixed) dropdown.style.position = 'fixed';
}
//// init recent searches
function initRecentSearches() {
    const recentSearch = document.getElementById('recent-searches');
    if (!recentSearch) return;

    function setPositionRecentSearch(what, recentSearch) {
        setDropDownPosition(what, recentSearch);
        recentSearch.style[window.innerWidth <= 480 ? 'width' : 'min-width'] = what.offsetWidth + 'px';
    }

    // open rs box
    function openRecentSearch() {
        recentSearch.classList.add(classes.openRS);
        what.classList.add(classes.openWhat);
    }

    // close rs box
    function closeRecentSearch() {
        recentSearch.classList.remove(classes.openRS);
        what.classList.remove(classes.openWhat);
    }

    const what = document.getElementById('what');
    if (!what) return;

    const autoClomplete = recentSearch.querySelectorAll('.autocomplete-suggestion');
    var classes = {
        openRecentSearch: 'show',
        selectRecentSearch: 'selected',
        openWhat: 'autocomplete-open'
    };

    // open rs on click
    what.addEventListener('click', function () {
        setPositionRecentSearch(what, recentSearch);
        openRecentSearch();
    });

    // open/close depends on what field length 
    what.addEventListener('keyup', function () {
        var whatTermLength = what.value.length;
        if (whatTermLength >= 2) closeRecentSearch();
        if (whatTermLength == 0) openRecentSearch();
    });

    // close when click outside of rs
    addListenerMultipleEvents(document, 'click touchend', function (e) {
        var c = closest(e.target, function (el) {
            if (el.id === 'what' || el.id === 'recent-searches' ||
                (typeof el.classList !== 'undefined' && el.classList.contains('autocomplete-suggestion'))
            ) {
                return true
            }
        });

        if (c) return;
        closeRecentSearch();
    });

    // add event listeners on each "recent search" item
    forEach(autoClomplete, function (_, item) {
        item.addEventListener('mouseenter', (e) => e.target.classList.add(classes.selectRS));
        item.addEventListener('mouseleave', (e) => e.target.classList.remove(c.selectRS));
        addListenerMultipleEvents(item, 'click touchend', (e) => {
            what.value = e.target.innerHTML;
            closeRecentSearch();
        });
    });

    // re-set rs box position and dimensions on window resize
    window.addEventListener('resize', setPositionRecentSearch(what, recentSearch));
}
//// hover poi
function hoverPoi() {
    $('.is-poi').hover(
        function () {
            $('.gg-poi.gg-poi-' + $(this).data('index')).addClass('gg-poi--hover');
        }, function () {
            $('.gg-poi.gg-poi-' + $(this).data('index')).removeClass('gg-poi--hover');
        });
}

function adsLoaded(selector, callback, time) {
    var i = 0;
    var checker = window.setInterval(function () {
        var ad = document.querySelector(selector);
        if (ad !== null && getAdItem(ad) !== false) {
            clearInterval(checker);
            callback();
        }
        if (i > 3 || ad === null) {
            clearInterval(checker);
        }
        i++;
    }, time);
}

function clickTopCall(e) {  
    e.preventDefault();
    var btn, phone, impression, label
    btn = e.target.tagName !== "A" ? e.target.parentNode : e.target;
    phoneFormatted = btn.getAttribute("data-phone-formatted");
    phone = btn.getAttribute("data-phone");
    impression = btn.getAttribute("data-impression");
    labelValue = phoneFormatted || phone;
    label = btn.querySelector("span");

    if (labelValue) {
        if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
            // call
            window.location.href = "tel:" + phone;
        } else {
            if (label.getAttribute("data-lbl") == null) {
                label.setAttribute("data-lbl", label.innerText)
            }

            if (containClass(btn, "active")) {
                btn.classList.remove("active");
                label.innerText = label.getAttribute("data-lbl");
            } else {
                btn.classList.add("active");
                label.innerText = labelValue;
            }
        }

        // log impression
        impression && $.get(impression);
    }
}

Main.handleOpenShareBox = function () {
    var shareButtons, klass;
    klass = "btn--share-it__open";
    shareButtons = document.querySelectorAll(".share-it");

    forEach(shareButtons, function (index, item) {
        var link = item.querySelector("a.btn");
        var box = item.querySelector(".share-it__box");

        if (link) {
            link.addEventListener("click", function (e) {
                e.preventDefault();

                var s = item.getBoundingClientRect().right;
                var l = document.querySelector(".result-item") || document.querySelector(".profile__introduction");
                var x = l.getBoundingClientRect().right;

                if ((x - s) < 130) {
                    box.style["right"] = "0";
                    box.style["left"] = "auto";
                } else {
                    box.style["right"] = "auto";
                    box.style["left"] = "0";
                }

                if (link.classList.contains(klass)) {
                    link.classList.remove(klass);
                } else {
                    link.classList.add(klass);
                }
            });
        }
    });
};

function initPebbleConsent() {
    window._PebbleConsent = false;
    var cookieObj = {};
    var keys = [];
    var cookie = getCookie("CookieScriptConsent");
    if (cookie.length) {
        cookieObj = JSON.parse(cookie);
        keys = Object.keys(cookieObj);
    }

    if (keys.length && keys.indexOf("categories") !== -1 && (Array && !Array.isArray(cookieObj.categories))) {
        if (JSON.parse(cookieObj.categories).indexOf("targeting") !== -1) {
            window._PebbleConsent = true;
        }
    }
}

Main.initFolderMap = function () {
    const mapHolder = document.getElementById("folder-map-holder");
    if (!mapHolder) return;

    const status = mapHolder && mapHolder.getAttribute("data-modal-status");

    if (status === "false") {
        // TO DO: display folder childs addresses

        FolderMapHolder.init();
        let activeAddress = document.querySelector("#folder-info > [itemprop=address]").innerText;

        [...document.querySelectorAll("#folder-child-addresses > li")].map(item => {
            if (item.querySelector("a").innerText == activeAddress) {
                item.classList.add("bg-blue-300");
            }
        })
        mapHolder.setAttribute("data-modal-status", true);
    }
};

// search bar handling
Main.expandSearchBar = function (elId) {
    const searchForm = document.getElementById(elId);
    if (!searchForm) return;
    const what = searchForm.querySelector("#what");
    const tmp = searchForm.querySelector(".reduced-search-form");

    if (window.innerWidth <= 767) {
        addListenerMultipleEvents(searchForm, "click touch", (e) => {
            e.stopPropagation();

            what.classList.add("mb-4");
            const where = searchForm.querySelector("#where").parentElement;
            const search = searchForm.querySelector("#search");
            where.classList.remove("hidden");
            search.classList.remove("hidden");
            if (tmp) tmp.classList.add("hidden");
        });
    }
};
Main.reduceSearchBar = function (elId) {
    addListenerMultipleEvents(document, "click touch", () => {
        const searchForm = document.getElementById(elId);
        if (!searchForm) return;
        searchForm.querySelector("#what").classList.remove("mb-4");
        searchForm.querySelector("#where").parentElement.classList.add("hidden");
        searchForm.querySelector("#search").classList.add("hidden");
        const tmp = searchForm.querySelector(".reduced-search-form");
        if (tmp) tmp.classList.remove("hidden");
    });
};

// hide CYB link
Main.hideCYBLink = function () {
    const claimedListingId = localStorage.getItem("claimedListing");
    const claimedListignEl = document.querySelector(`[data-id='${claimedListingId}']`);
    if (!claimedListignEl) return;
    const links = claimedListignEl.querySelectorAll("[data-ta='ClaimYourListing']");
    if (links.length > 0)
        [...links].map(l => l.style.display = "none");
    
};

Main.initStickyBox = function (boxId) {
    const box = document.getElementById(boxId);
    if (!box) return;

    let clone = null;
    let stuck = false;
    let stickPoint = getDistance();

    function getDistance() {
        // top distance
        return box.offsetTop;
    }

    window.addEventListener("scroll", function (e) {
        const distance = getDistance() - window.pageYOffset;
        const offset = window.pageYOffset;
        //readout.innerHTML = stickPoint + '   ' + distance + '   ' + offset + '   ' + stuck;
        const copyId = `${boxId}-copy`;
        const copyEl = document.getElementById(`${boxId}-copy`);
        let copies = document.querySelectorAll("[id$=-copy]");

        if ((distance <= 0) && !stuck) {
            if (window.innerWidth <= 767) { 
                // je element uz nakopirovany? pokud ne udelej kopii
                if (!copyEl) {
                    clone = box.cloneNode(true);
                    clone.classList.add("hidden");
                    clone.id = copyId;

                    if (boxId == "search-form") {
                        var reducedForm = clone.querySelector(".reduced-search-form");
                        if (!reducedForm) return;
                        reducedForm.classList.add("p-4");
                        console.log("add clone");
                        document.body.appendChild(clone);
                        Main.expandSearchBar(copyId);
                        Main.reduceSearchBar(copyId);
                    } else if (boxId == "header-box") {
                        console.log("expand")
                    }
                    else {
                        document.body.appendChild(clone);
                    }
                } else {
                    copyEl.style.width = '100%';
                    copyEl.style.position = 'fixed';
                    copyEl.style.zIndex = '999';
                    copyEl.style.top = '0';

                    // css TOP if there are multiple elements
                    [...copies].map((c, i) => {
                        if (i > 0) {
                            let heightPrev = copies[i - 1].offsetHeight;
                            let top = c.style.top.replace("px", "");
                            top = parseInt(top);
                            c.style.top = top + heightPrev + "px";
                        }
                    });

                    copyEl.classList.remove("hidden");

                    if (copyId === "search-form-copy") {
                        copyEl.style.margin = "0";
                        copyEl.style.backgroundColor = "#fff";
                        copyEl.style.padding = "1rem";
                        copyEl.style.borderBottom = "1px solid rgb(203, 203, 203)";
                    }

                    stuck = true;
                }
            }
        } else if (stuck && (offset <= stickPoint)) {
            copyEl.style.position = 'absolute';
            copyEl.style.top = "-100%";
            stuck = false;
        }
    });
};

function syncLocationButton() {
    var locationInput = document.querySelectorAll(".hidden-location");
    var locationButton = document.getElementById("my-location");
    var where = document.getElementById("where");

    if (locationInput.length == 0 || !locationButton || !where) return;

    [...locationInput].map(l => { 
        if (l.value !== "") {
            locationButton.classList.add("active");
            where.value = "";
            where.setAttribute("placeholder", "Rondom mij");
            // Switch location search mode to where search when user starts typing
            where.addEventListener("keypress", () => {
                // Check the current mode to avoid pointless sync
                if (l.value !== "") {
                    l.value = "";
                    syncLocationButton();
                }
            });
        } else {
            where.setAttribute("placeholder", "Jouw stad of gemeente");
            locationButton.classList.remove("active");
        }
    })
}

function toggleLocationSearchMode(locationSearch) {
    // Current search mode is determined by the value of #location input
    // - no value - where search
    // - some value - location search
    const locationButton = document.getElementById("my-location");
    const location = document.querySelectorAll(".hidden-location");

    if (((locationButton && locationButton.classList.contains("active"))
        && locationSearch == undefined) || locationSearch == false) {
        document.getElementById("location").value = "";
        syncLocationButton();
    } else {
        navigator.geolocation.getCurrentPosition(function (position) {
            [...location].map(l => {
                l.value = position.coords.latitude + "," + position.coords.longitude;
            })
            syncLocationButton();
        });
    }
}

document.addEventListener('DOMContentLoaded', () => {
    Main.initLangMenu();

    initPebbleConsent();

    // poi hover 
    hoverPoi();

    // recent searches
    initRecentSearches();

    // Lightbox settings
    lightbox.option({ 'disableScrolling': true });
    
    // hide empty ads
    hideEmptyAdBox(); 

    Main.expandSearchBar('search-form');
    Main.reduceSearchBar('search-form');

    // Clicking on location button switches search modes to location search and back
    //console.log(document.getElementById("my-location"));
    //document.getElementById("my-location").addEventListener("click", () => {
    //    console.log("click click");
    //    toggleLocationSearchMode();
    //});

    if (Main.isMobile()) {
        toggleLocationSearchMode();
        syncLocationButton();

        // horizontal list
        initHorizontalList();
    }

    //Main.initStickyBox("listing-info");
    
    /*Main.initStickyBox("search-form");*/
    //if (document.getElementById("back-button")) {
    //    Main.initStickyBox("back-button");
    //}

    var sticky = new Sticky('[data-sticky]');

    Main.accordion("qna");
    Main.hideCYBLink();
    Main.handleCategories("blog-categories")
});

window.addEventListener("load", function () {
    adsLoaded("ins", function () { makeAdsResponsive("TOP-banner"); }, 1000);
})

window.addEventListener('CookieScriptAcceptAll', function () {
    window._PebbleConsent = true;
});

window.addEventListener('CookieScriptAccept', function () {
    window._PebbleConsent = false;

    var state = CookieScript.instance.currentState();
    if (typeof state !== "undefined") {
        if (state.categories.indexOf("targeting") !== -1) {
            window._PebbleConsent = true;
        }
    }
});;
