window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.webcore = window.eviivo.webcore ? window.eviivo.webcore : {};
window.eviivo.webcore.formatting = window.eviivo.webcore.formatting ? window.eviivo.webcore.formatting : {};

window.eviivo.webcore.formatting.datetime = function () {
    var namespace = "eviivo.webcore.formatting.datetime";

    function evDisplayLongTime(date, culture) {
        // hh:MM:ss
        return formatTime(date, culture, "long");
    }
    function evDisplayShortTime(date, culture) {
        // hh:MM
        return formatTime(date, culture, "short");
    }
    function evDisplayLongDate(date, culture) {
        // ddd dd-mmm-yy
        return formatDate(date, culture, "long");
    }
    function evDisplayMediumDate(date, culture) {
        // dd-mmm-yy
        return formatDate(date, culture, "medium");
    }
    function evDisplayShortDate(date, culture) {
        // dd-mmm-yy (should be dd-mm-yy)
        return formatDate(date, culture, "short");
    }
    function evDisplayLongDateTime(date, culture) {
        return formatDate(date, culture, "long") + " " + formatTime(date, culture, "short");
    }
    function evDisplayExtraLongDateTime(date, culture) {
        return formatDate(date, culture, "long") + " " + formatTime(date, culture, "long");
    }
    function evDisplayLongTimeDate(date, culture) {
        return formatTime(date, culture, "short") + " " + formatDate(date, culture, "long");
    }
    function evDisplayMediumDateTime(date, culture) {
        return formatDate(date, culture, "medium") + " " + formatTime(date, culture, "short");
    }
    function evDisplayMediumTimeDate(date, culture) {
        return formatTime(date, culture, "short") + " " + formatDate(date, culture, "medium");
    }
    function evDisplayShortDateTime(date, culture) {
        return formatDate(date, culture, "short") + " " + formatTime(date, culture, "short");
    }
    function evDisplayShortTimeDate(date, culture) {
        return formatTime(date, culture, "short") + " " + formatDate(date, culture, "short");
    }

    function evStandardIso8601Date(date) {
        // yyyymmdd
        return formatDate(date, "iso8601", "short");
    }
    function evStandardIso8601DateTimeUtc(date) {
        // yyyymmddThhmmss
        return formatDate(date, "iso8601", "short") + "T" + formatTime(date, "iso8601", "short");
    }
    function evStandardIso8601DateExtended(date) {
        // yyyy-mm-dd
        return formatDate(date, "iso8601", "long");
    }

    function evStandardIso8601DateTimeUtcExtended(date) {
        // yyyy-mm-ddThh:mm:ss
        return formatDate(date, "iso8601", "long") + "T" + formatTime(date, "iso8601", "long");
    }

    function evStandard24HourTime(date) {
        return formatTime(date, "iso8601", "short");
    }

    // public method to - assess current culture passed into function and calculate calendar first day offset
    function evStandardFirstDayCalendarOffset(culture) {
        return getFirstDayCalendarOffset(culture.toLowerCase());
    }

    // public method to - assess current culture passed into function and calculate calendar first day offset
    function evGetDateDisplayFormat(culture, type) {
        return getDateDisplayFormat(culture.toLowerCase(), type);
    }

    // private method to - assess current culture passed into function and calculate calendar first day offset
    function getFirstDayCalendarOffset(culture) {
        var regionals = window.eviivo.webcore.formatting.regionals[culture];
        if (regionals == null) {
            regionals = window.eviivo.webcore.formatting.regionals["default"];
        }
        return regionals.firstDayCalendarOffset;
    }

    // private method to - assess current culture passed into function and calculate calendar first day offset
    function getDateDisplayFormat(culture, type) {
        var regionals = window.eviivo.webcore.formatting.regionals[culture];
        if (regionals == null) {
            regionals = window.eviivo.webcore.formatting.regionals["default"];
        }
        if (type === "long") {
            return regionals.jQDateFormat.long;
        } else if (type === "short") {
            return regionals.jQDateFormat.short;
        } else {
            return regionals.jQDateFormat.medium;
        }
    }

    //NOTE: replace and indexOf are case sensitive
    function formatDate(date, culture, formatType) {
        if (date == null) {
            return null;
        }

        if (culture == null || culture == "") {
            throw (namespace + ": please specify the 'culture' code parameter");
        }

        culture = culture.toLowerCase();

        if (date instanceof Date) {
            var regionals = window.eviivo.webcore.formatting.regionals[culture];
            if (regionals == null) {
                regionals = window.eviivo.webcore.formatting.regionals["default"];
            }

            var dateResult = regionals.dateFormat[formatType].slice(0);
            var day = date.getDate();
            var weekDay = date.getDay();

            var regExNonPaddedDay1 = new RegExp("([\\w\\d ]+[ \\.\\-/,])(d{1})([ \\.\\-/,]+)([\\w\\d \\.\\-/,]+)");
            var regExNonPaddedDay2 = new RegExp("[^yYdDmM \\.\\-/,](d{1})([ \\.\\-/,]+)([yYdDmM \\.\\-/,]+)");
            if (regExNonPaddedDay1.test(dateResult)) {
                dateResult = dateResult.replace(regExNonPaddedDay1, "$1" + day + "$3$4");
            } else if (regExNonPaddedDay2.test(dateResult)) {
                dateResult = dateResult.replace(regExNonPaddedDay2, day + "$2$3");
            }

            if (regionals.dayNames != null) {
                dateResult = dateResult.replace("dddd", regionals.dayNames.long[weekDay]);
                dateResult = dateResult.replace("ddd", regionals.dayNames.medium[weekDay]);
                dateResult = dateResult.replace("DD", regionals.dayNames.short[weekDay]);
            }
            dateResult = dateResult.replace("dd", padZero(day));

            var month = date.getMonth();
            var regExNonPaddedMonth1 = new RegExp("([\\w\\d ]+[ \\.\\-/,])(M{1})([ \\.\\-/,]+)([\\w\\d \\.\\-/,]+)");
            var regExNonPaddedMonth2 = new RegExp("[^yYdDmM \\.\\-/,](M{1})([ \\.\\-/,]+)([yYdDmM \\.\\-/,]+)");
            if (regExNonPaddedMonth1.test(dateResult)) {
                dateResult = dateResult.replace(regExNonPaddedMonth1, "$1" + month + "$3$4");
            } else if (regExNonPaddedMonth2.test(dateResult)) {
                dateResult = dateResult.replace(regExNonPaddedMonth2, month + "$2$3");
            }

            if (regionals.monthNames != null) {
                dateResult = dateResult.replace("MMMM", regionals.monthNames.long[month]);
                dateResult = dateResult.replace("MMM", regionals.monthNames.medium[month]);
            }
            dateResult = dateResult.replace("MM", padZero(month + 1));

            dateResult = dateResult.replace("yyyy", date.getFullYear());
            dateResult = dateResult.replace("yy", date.getFullYear().toString().substring(2));
            return dateResult;
        } else {
            return date.toLocaleString();
        }
    }

    //NOTE: replace and indexOf are case sensitive
    function formatTime(date, culture, formatType) {
        if (date == null) {
            return null;
        }

        if (culture == null || culture == "") {
            throw (namespace + ": please specify the 'culture' code parameter");
        }

        culture = culture.toLowerCase();

        if (date instanceof Date) {
            var regionals = window.eviivo.webcore.formatting.regionals[culture];
            if (regionals == null) {
                regionals = window.eviivo.webcore.formatting.regionals["default"];
            }

            var timeResult = regionals.clockFormat[formatType].slice(0);

            var cFormat = regionals.clockFormat.mode;
            if (cFormat == null) {
                cFormat = 24;
            }

            if (timeResult.indexOf("tt") < 0 && timeResult.indexOf("t") > -1) {
                timeResult = timeResult.replace("t", cFormat == 24 ? "hh:mm" : "h:mm tt");
            }

            if (timeResult.indexOf("tt") < 0 && timeResult.indexOf("T") > -1) {
                timeResult = timeResult.replace("T", cFormat == 24 ? "hh:mm:ss" : "h:mm:ss tt");
            }

            var hours = date.getHours();
            if (cFormat == 12) {
                var ampm = hours >= 12 ? "PM" : "AM";
                timeResult = timeResult.replace("tt", ampm);
                hours = hours % 12;
                hours = hours ? hours : 12; // the hour '0' should be '12'
            }
            timeResult = timeResult.replace("hh:", padZero(hours) + ":");
            timeResult = timeResult.replace("h:", hours + ":");
            timeResult = timeResult.replace(":mm", ":" + padZero(date.getMinutes()));
            timeResult = timeResult.replace(":ss", ":" + padZero(date.getSeconds()));

            return timeResult;
        } else {
            return date.toLocaleString();
        }
    }

    function padZero(n) { return n < 10 ? '0' + n : n; }

    return {
        evDisplayLongTime: evDisplayLongTime,
        evDisplayShortTime: evDisplayShortTime,
        evDisplayLongDate: evDisplayLongDate,
        evDisplayMediumDate: evDisplayMediumDate,
        evDisplayShortDate: evDisplayShortDate,
        evDisplayLongDateTime: evDisplayLongDateTime,
        evDisplayExtraLongDateTime: evDisplayExtraLongDateTime,
        evDisplayMediumDateTime: evDisplayMediumDateTime,
        evDisplayShortDateTime: evDisplayShortDateTime,
        evDisplayLongTimeDate: evDisplayLongTimeDate,
        evDisplayMediumTimeDate: evDisplayMediumTimeDate,
        evDisplayShortTimeDate: evDisplayShortTimeDate,
        evStandard24HourTime: evStandard24HourTime,
        evStandardIso8601Date: evStandardIso8601Date,
        evStandardIso8601DateTimeUtc: evStandardIso8601DateTimeUtc,
        evStandardIso8601DateExtended: evStandardIso8601DateExtended,
        evStandardIso8601DateTimeUtcExtended: evStandardIso8601DateTimeUtcExtended,
        evStandardFirstDayCalendarOffset: evStandardFirstDayCalendarOffset,
        evGetDateDisplayFormat: evGetDateDisplayFormat
    };
}();

Date.prototype.evGetDateDisplayFormat = function (culture, type) {
    return eviivo.webcore.formatting.datetime.evGetDateDisplayFormat(culture, type);
}

Date.prototype.evStandardFirstDayCalendarOffset = function (culture) {
    return eviivo.webcore.formatting.datetime.evStandardFirstDayCalendarOffset(culture);
}

Date.prototype.evDisplayLongTime = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayLongTime(this, culture);
}

Date.prototype.evDisplayShortTime = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayShortTime(this, culture);
}

Date.prototype.evDisplayLongDate = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayLongDate(this, culture);
}

Date.prototype.evDisplayMediumDate = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayMediumDate(this, culture);
}

Date.prototype.evDisplayShortDate = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayShortDate(this, culture);
}

Date.prototype.evDisplayLongDateTime = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayLongDateTime(this, culture);
}

Date.prototype.evDisplayExtraLongDateTime = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayExtraLongDateTime(this, culture);
}

Date.prototype.evDisplayMediumDateTime = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayMediumDateTime(this, culture);
}

Date.prototype.evDisplayShortDateTime = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayShortDateTime(this, culture);
}

Date.prototype.evDisplayLongTimeDate = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayLongTimeDate(this, culture);
}

Date.prototype.evDisplayMediumTimeDate = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayMediumTimeDate(this, culture);
}

Date.prototype.evDisplayShortTimeDate = function (culture) {
    return eviivo.webcore.formatting.datetime.evDisplayShortTimeDate(this, culture);
}

Date.prototype.evStandardIso8601Date = function () {
    return eviivo.webcore.formatting.datetime.evStandardIso8601Date(this);
}
Date.prototype.evStandardIso8601DateTimeUtc = function () {
    return eviivo.webcore.formatting.datetime.evStandardIso8601DateTimeUtc(this);
}
Date.prototype.evStandardIso8601DateExtended = function () {
    return eviivo.webcore.formatting.datetime.evStandardIso8601DateExtended(this);
}
Date.prototype.evStandardIso8601DateTimeUtcExtended = function () {
    return eviivo.webcore.formatting.datetime.evStandardIso8601DateTimeUtcExtended(this);
}

Date.prototype.evStandard24HourTime = function () {
    return eviivo.webcore.formatting.datetime.evStandard24HourTime(this);
}

window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.webcore.formatting = window.eviivo.webcore.formatting ? window.eviivo.webcore.formatting : {};
window.eviivo.webcore.formatting.regionals = window.eviivo.webcore.formatting.regionals ? window.eviivo.webcore.formatting.regionals : {};

window.eviivo.webcore.formatting.regionals["iso8601"] = {
    monthNames: null,
    dayNames: null,
    dateFormat: {
        long: "yyyy-MM-dd",
        medium: null,
        short: "yyyyMMdd"
    },
    jQDateFormat: {
        long: "yy-mm-dd",
        medium: null,
        short: "yymmdd"
    },
    clockFormat: {
        mode: 24,
        long: "hh:mm:ss",
        short: "hhmmss"
    },
    firstDayCalendarOffset: 1
};

window.eviivo.webcore.formatting.regionals["default"] = {
    monthNames: {
        long: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        medium: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        short: null
    },
    dayNames: {
        long: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        medium: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
    },
    dateFormat: {
        long: "ddd dd MMM yyyy",
        medium: "dd MMM yyyy",
        short: "dd-MM-yy"
    },
    jQDateFormat: {
        long: "D dd M yy",
        medium: "d M yy",
        short: "dd-M-y"
    },
    clockFormat: {
        mode: 24,
        long: "T",
        short: "t"
    },
    firstDayCalendarOffset: 1
};

window.eviivo.webcore.formatting.regionals["en-gb"] = {
    monthNames: {
        long: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        medium: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        short: null
    },
    dayNames: {
        long: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        medium: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
    },
    dateFormat: {
        long: "ddd dd MMM yyyy",
        medium: "dd MMM yyyy",
        short: "dd-MM-yy"
    },
    jQDateFormat: {
        long: "D dd M yy",
        medium: "d M yy",
        short: "dd-M-y"
    },
    clockFormat: {
        mode: 24,
        long: "T",
        short: "t"
    },
    firstDayCalendarOffset: 1
};

window.eviivo.webcore.formatting.regionals["en-us"] = {
    monthNames: {
        long: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        medium: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        short: null
    },
    dayNames: {
        long: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        medium: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
    },
    dateFormat: {
        long: "ddd MMM d, yyyy",
        medium: "MMM d, yyyy",
        short: "M/d/yy"
    },
    jQDateFormat: {
        long: "D M d, yy",
        medium: "M d, yy",
        short: "m/d/y"
    },
    clockFormat: {
        mode: 12,
        long: "T",
        short: "t"
    },
    firstDayCalendarOffset: 0
};

window.eviivo.webcore.formatting.regionals["fr-fr"] = {
    monthNames: {
        long: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
        medium: ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'],
        short: null
    },
    dayNames: {
        long: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
        medium: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
        short: ['di', 'lu', 'ma', 'me', 'je', 've', 'sa']
    },
    dateFormat: {
        long: "ddd dd MMM yyyy",
        medium: "dd MMM yyyy",
        short: "dd-MM-yy"
    },
    jQDateFormat: {
        long: "D dd M yy",
        medium: "d M yy",
        short: "dd-M-y"
    },
    clockFormat: {
        mode: 24,
        long: "T",
        short: "t"
    },
    firstDayCalendarOffset: 1
};

window.eviivo.webcore.formatting.regionals["it-it"] = {
    monthNames: {
        long: ['gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'],
        medium: ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'],
        short: null
    },
    dayNames: {
        long: ['domenica', 'lunedì', 'martedì', 'mercoledì', 'giovedì', 'venerdì', 'sabato'],
        medium: ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'],
        short: ['do', 'lu', 'ma', 'me', 'gi', 've', 'sa']
    },
    dateFormat: {
        long: "ddd dd MMM yyyy",
        medium: "dd MMM yyyy",
        short: "dd-MM-yy"
    },
    jQDateFormat: {
        long: "D dd M yy",
        medium: "d M yy",
        short: "dd-M-y"
    },
    clockFormat: {
        mode: 24,
        long: "T",
        short: "t"
    },
    firstDayCalendarOffset: 1
};

window.eviivo.webcore.formatting.regionals["de-de"] = {
    monthNames: {
        long: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
        medium: ['Jan', 'Feb', 'Mrz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
        short: null
    },
    dayNames: {
        long: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
        medium: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
        short: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa']
    },
    dateFormat: {
        long: "ddd dd MMM yyyy",
        medium: "dd MMM yyyy",
        short: "dd-MM-yy"
    },
    jQDateFormat: {
        long: "D dd M yy",
        medium: "d M yy",
        short: "dd-M-y"
    },
    clockFormat: {
        mode: 24,
        long: "T",
        short: "t"
    },
    firstDayCalendarOffset: 1
};

window.eviivo.webcore.formatting.regionals["pt-pt"] = {
    monthNames: {
        long: ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'],
        medium: ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
        short: null
    },
    dayNames: {
        long: ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'],
        medium: ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'],
        short: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S']
    },
    dateFormat: {
        long: "ddd dd MMM yyyy",
        medium: "dd MMM yyyy",
        short: "dd-MM-yy"
    },
    jQDateFormat: {
        long: "D dd M yy",
        medium: "d M yy",
        short: "dd-M-y"
    },
    clockFormat: {
        mode: 24,
        long: "T",
        short: "t"
    },
    firstDayCalendarOffset: 1
};

window.eviivo.webcore.formatting.regionals["pt-br"] = {
    monthNames: {
        long: ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'],
        medium: ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
        short: null
    },
    dayNames: {
        long: ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'],
        medium: ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'],
        short: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S']
    },
    dateFormat: {
        long: "ddd dd MMM yyyy",
        medium: "dd MMM yyyy",
        short: "dd-MM-yy"
    },
    jQDateFormat: {
        long: "D dd M yy",
        medium: "d M yy",
        short: "dd-M-y"
    },
    clockFormat: {
        mode: 24,
        long: "T",
        short: "t"
    },
    firstDayCalendarOffset: 1
};

window.eviivo.webcore.formatting.regionals["es-es"] = {
    monthNames: {
        long: ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'],
        medium: ['ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sep.', 'oct.', 'nov.', 'dic.'],
        short: null
    },
    dayNames: {
        long: ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
        medium: ['do.', 'lu.', 'ma.', 'mi.', 'ju.', 'vi.', 'sá.'],
        short: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S']
    },
    dateFormat: {
        long: "ddd dd MMM yyyy",
        medium: "dd MMM yyyy",
        short: "dd-MM-yy"
    },
    jQDateFormat: {
        long: "D dd M yy",
        medium: "d M yy",
        short: "dd-M-y"
    },
    clockFormat: {
        mode: 24,
        long: "T",
        short: "t"
    },
    firstDayCalendarOffset: 1
};
function setDatepickerFormat(cultureCode) {
    var dtFormatStyle = eviivo.webcore.formatting.datetime.evGetDateDisplayFormat(cultureCode, "medium");
    jQuery.datepicker.setDefaults({ dateFormat: dtFormatStyle, altFormat: dtFormatStyle });
}
/*! nouislider - 8.5.1 - 2016-04-24 16:00:29 */

(function (factory) {

    if (typeof define === 'function' && define.amd) {

        // AMD. Register as an anonymous module.
        define([], factory);

    } else if (typeof exports === 'object') {

        // Node/CommonJS
        module.exports = factory();

    } else {

        // Browser globals
        window.noUiSlider = factory();
    }

}(function () {

    'use strict';


    // Removes duplicates from an array.
    function unique(array) {
        return array.filter(function (a) {
            return !this[a] ? this[a] = true : false;
        }, {});
    }

    // Round a value to the closest 'to'.
    function closest(value, to) {
        return Math.round(value / to) * to;
    }

    // Current position of an element relative to the document.
    function offset(elem) {

        var rect = elem.getBoundingClientRect(),
            doc = elem.ownerDocument,
            docElem = doc.documentElement,
            pageOffset = getPageOffset();

        // getBoundingClientRect contains left scroll in Chrome on Android.
        // I haven't found a feature detection that proves this. Worst case
        // scenario on mis-match: the 'tap' feature on horizontal sliders breaks.
        if (/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)) {
            pageOffset.x = 0;
        }

        return {
            top: rect.top + pageOffset.y - docElem.clientTop,
            left: rect.left + pageOffset.x - docElem.clientLeft
        };
    }

    // Checks whether a value is numerical.
    function isNumeric(a) {
        return typeof a === 'number' && !isNaN(a) && isFinite(a);
    }

    // Sets a class and removes it after [duration] ms.
    function addClassFor(element, className, duration) {
        addClass(element, className);
        setTimeout(function () {
            removeClass(element, className);
        }, duration);
    }

    // Limits a value to 0 - 100
    function limit(a) {
        return Math.max(Math.min(a, 100), 0);
    }

    // Wraps a variable as an array, if it isn't one yet.
    function asArray(a) {
        return Array.isArray(a) ? a : [a];
    }

    // Counts decimals
    function countDecimals(numStr) {
        var pieces = numStr.split(".");
        return pieces.length > 1 ? pieces[1].length : 0;
    }

    // http://youmightnotneedjquery.com/#add_class
    function addClass(el, className) {
        if (el.classList) {
            el.classList.add(className);
        } else {
            el.className += ' ' + className;
        }
    }

    // http://youmightnotneedjquery.com/#remove_class
    function removeClass(el, className) {
        if (el.classList) {
            el.classList.remove(className);
        } else {
            el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
        }
    }

    // https://plainjs.com/javascript/attributes/adding-removing-and-testing-for-classes-9/
    function hasClass(el, className) {
        return el.classList ? el.classList.contains(className) : new RegExp('\\b' + className + '\\b').test(el.className);
    }

    // https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes
    function getPageOffset() {

        var supportPageOffset = window.pageXOffset !== undefined,
            isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"),
            x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft,
            y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;

        return {
            x: x,
            y: y
        };
    }

    // we provide a function to compute constants instead
    // of accessing window.* as soon as the module needs it
    // so that we do not compute anything if not needed
    function getActions() {

        // Determine the events to bind. IE11 implements pointerEvents without
        // a prefix, which breaks compatibility with the IE10 implementation.
        return window.navigator.pointerEnabled ? {
            start: 'pointerdown',
            move: 'pointermove',
            end: 'pointerup'
        } : window.navigator.msPointerEnabled ? {
            start: 'MSPointerDown',
            move: 'MSPointerMove',
            end: 'MSPointerUp'
        } : {
            start: 'mousedown touchstart',
            move: 'mousemove touchmove',
            end: 'mouseup touchend'
        };
    }


    // Value calculation

    // Determine the size of a sub-range in relation to a full range.
    function subRangeRatio(pa, pb) {
        return (100 / (pb - pa));
    }

    // (percentage) How many percent is this value of this range?
    function fromPercentage(range, value) {
        return (value * 100) / (range[1] - range[0]);
    }

    // (percentage) Where is this value on this range?
    function toPercentage(range, value) {
        return fromPercentage(range, range[0] < 0 ?
            value + Math.abs(range[0]) :
            value - range[0]);
    }

    // (value) How much is this percentage on this range?
    function isPercentage(range, value) {
        return ((value * (range[1] - range[0])) / 100) + range[0];
    }


    // Range conversion

    function getJ(value, arr) {

        var j = 1;

        while (value >= arr[j]) {
            j += 1;
        }

        return j;
    }

    // (percentage) Input a value, find where, on a scale of 0-100, it applies.
    function toStepping(xVal, xPct, value) {

        if (value >= xVal.slice(-1)[0]) {
            return 100;
        }

        var j = getJ(value, xVal), va, vb, pa, pb;

        va = xVal[j - 1];
        vb = xVal[j];
        pa = xPct[j - 1];
        pb = xPct[j];

        return pa + (toPercentage([va, vb], value) / subRangeRatio(pa, pb));
    }

    // (value) Input a percentage, find where it is on the specified range.
    function fromStepping(xVal, xPct, value) {

        // There is no range group that fits 100
        if (value >= 100) {
            return xVal.slice(-1)[0];
        }

        var j = getJ(value, xPct), va, vb, pa, pb;

        va = xVal[j - 1];
        vb = xVal[j];
        pa = xPct[j - 1];
        pb = xPct[j];

        return isPercentage([va, vb], (value - pa) * subRangeRatio(pa, pb));
    }

    // (percentage) Get the step that applies at a certain value.
    function getStep(xPct, xSteps, snap, value) {

        if (value === 100) {
            return value;
        }

        var j = getJ(value, xPct), a, b;

        // If 'snap' is set, steps are used as fixed points on the slider.
        if (snap) {

            a = xPct[j - 1];
            b = xPct[j];

            // Find the closest position, a or b.
            if ((value - a) > ((b - a) / 2)) {
                return b;
            }

            return a;
        }

        if (!xSteps[j - 1]) {
            return value;
        }

        return xPct[j - 1] + closest(
            value - xPct[j - 1],
            xSteps[j - 1]
        );
    }


    // Entry parsing

    function handleEntryPoint(index, value, that) {

        var percentage;

        // Wrap numerical input in an array.
        if (typeof value === "number") {
            value = [value];
        }

        // Reject any invalid input, by testing whether value is an array.
        if (Object.prototype.toString.call(value) !== '[object Array]') {
            throw new Error("noUiSlider: 'range' contains invalid value.");
        }

        // Covert min/max syntax to 0 and 100.
        if (index === 'min') {
            percentage = 0;
        } else if (index === 'max') {
            percentage = 100;
        } else {
            percentage = parseFloat(index);
        }

        // Check for correct input.
        if (!isNumeric(percentage) || !isNumeric(value[0])) {
            throw new Error("noUiSlider: 'range' value isn't numeric.");
        }

        // Store values.
        that.xPct.push(percentage);
        that.xVal.push(value[0]);

        // NaN will evaluate to false too, but to keep
        // logging clear, set step explicitly. Make sure
        // not to override the 'step' setting with false.
        if (!percentage) {
            if (!isNaN(value[1])) {
                that.xSteps[0] = value[1];
            }
        } else {
            that.xSteps.push(isNaN(value[1]) ? false : value[1]);
        }
    }

    function handleStepPoint(i, n, that) {

        // Ignore 'false' stepping.
        if (!n) {
            return true;
        }

        // Factor to range ratio
        that.xSteps[i] = fromPercentage([
            that.xVal[i]
            , that.xVal[i + 1]
        ], n) / subRangeRatio(
            that.xPct[i],
            that.xPct[i + 1]);
    }


    // Interface

    // The interface to Spectrum handles all direction-based
    // conversions, so the above values are unaware.

    function Spectrum(entry, snap, direction, singleStep) {

        this.xPct = [];
        this.xVal = [];
        this.xSteps = [singleStep || false];
        this.xNumSteps = [false];

        this.snap = snap;
        this.direction = direction;

        var index, ordered = [ /* [0, 'min'], [1, '50%'], [2, 'max'] */];

        // Map the object keys to an array.
        for (index in entry) {
            if (entry.hasOwnProperty(index)) {
                ordered.push([entry[index], index]);
            }
        }

        // Sort all entries by value (numeric sort).
        if (ordered.length && typeof ordered[0][0] === "object") {
            ordered.sort(function (a, b) { return a[0][0] - b[0][0]; });
        } else {
            ordered.sort(function (a, b) { return a[0] - b[0]; });
        }


        // Convert all entries to subranges.
        for (index = 0; index < ordered.length; index++) {
            handleEntryPoint(ordered[index][1], ordered[index][0], this);
        }

        // Store the actual step values.
        // xSteps is sorted in the same order as xPct and xVal.
        this.xNumSteps = this.xSteps.slice(0);

        // Convert all numeric steps to the percentage of the subrange they represent.
        for (index = 0; index < this.xNumSteps.length; index++) {
            handleStepPoint(index, this.xNumSteps[index], this);
        }
    }

    Spectrum.prototype.getMargin = function (value) {
        return this.xPct.length === 2 ? fromPercentage(this.xVal, value) : false;
    };

    Spectrum.prototype.toStepping = function (value) {

        value = toStepping(this.xVal, this.xPct, value);

        // Invert the value if this is a right-to-left slider.
        if (this.direction) {
            value = 100 - value;
        }

        return value;
    };

    Spectrum.prototype.fromStepping = function (value) {

        // Invert the value if this is a right-to-left slider.
        if (this.direction) {
            value = 100 - value;
        }

        return fromStepping(this.xVal, this.xPct, value);
    };

    Spectrum.prototype.getStep = function (value) {

        // Find the proper step for rtl sliders by search in inverse direction.
        // Fixes issue #262.
        if (this.direction) {
            value = 100 - value;
        }

        value = getStep(this.xPct, this.xSteps, this.snap, value);

        if (this.direction) {
            value = 100 - value;
        }

        return value;
    };

    Spectrum.prototype.getApplicableStep = function (value) {

        // If the value is 100%, return the negative step twice.
        var j = getJ(value, this.xPct), offset = value === 100 ? 2 : 1;
        return [this.xNumSteps[j - 2], this.xVal[j - offset], this.xNumSteps[j - offset]];
    };

    // Outside testing
    Spectrum.prototype.convert = function (value) {
        return this.getStep(this.toStepping(value));
    };

    /*	Every input option is tested and parsed. This'll prevent
        endless validation in internal methods. These tests are
        structured with an item for every option available. An
        option can be marked as required by setting the 'r' flag.
        The testing function is provided with three arguments:
            - The provided value for the option;
            - A reference to the options object;
            - The name for the option;
    
        The testing function returns false when an error is detected,
        or true when everything is OK. It can also modify the option
        object, to make sure all values can be correctly looped elsewhere. */

    var defaultFormatter = {
        'to': function (value) {
            return value !== undefined && value.toFixed(2);
        }, 'from': Number
    };

    function testStep(parsed, entry) {

        if (!isNumeric(entry)) {
            throw new Error("noUiSlider: 'step' is not numeric.");
        }

        // The step option can still be used to set stepping
        // for linear sliders. Overwritten if set in 'range'.
        parsed.singleStep = entry;
    }

    function testRange(parsed, entry) {

        // Filter incorrect input.
        if (typeof entry !== 'object' || Array.isArray(entry)) {
            throw new Error("noUiSlider: 'range' is not an object.");
        }

        // Catch missing start or end.
        if (entry.min === undefined || entry.max === undefined) {
            throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");
        }

        // Catch equal start or end.
        if (entry.min === entry.max) {
            throw new Error("noUiSlider: 'range' 'min' and 'max' cannot be equal.");
        }

        parsed.spectrum = new Spectrum(entry, parsed.snap, parsed.dir, parsed.singleStep);
    }

    function testStart(parsed, entry) {

        entry = asArray(entry);

        // Validate input. Values aren't tested, as the public .val method
        // will always provide a valid location.
        if (!Array.isArray(entry) || !entry.length || entry.length > 2) {
            throw new Error("noUiSlider: 'start' option is incorrect.");
        }

        // Store the number of handles.
        parsed.handles = entry.length;

        // When the slider is initialized, the .val method will
        // be called with the start options.
        parsed.start = entry;
    }

    function testSnap(parsed, entry) {

        // Enforce 100% stepping within subranges.
        parsed.snap = entry;

        if (typeof entry !== 'boolean') {
            throw new Error("noUiSlider: 'snap' option must be a boolean.");
        }
    }

    function testAnimate(parsed, entry) {

        // Enforce 100% stepping within subranges.
        parsed.animate = entry;

        if (typeof entry !== 'boolean') {
            throw new Error("noUiSlider: 'animate' option must be a boolean.");
        }
    }

    function testAnimationDuration(parsed, entry) {

        parsed.animationDuration = entry;

        if (typeof entry !== 'number') {
            throw new Error("noUiSlider: 'animationDuration' option must be a number.");
        }
    }

    function testConnect(parsed, entry) {

        if (entry === 'lower' && parsed.handles === 1) {
            parsed.connect = 1;
        } else if (entry === 'upper' && parsed.handles === 1) {
            parsed.connect = 2;
        } else if (entry === true && parsed.handles === 2) {
            parsed.connect = 3;
        } else if (entry === false) {
            parsed.connect = 0;
        } else {
            throw new Error("noUiSlider: 'connect' option doesn't match handle count.");
        }
    }

    function testOrientation(parsed, entry) {

        // Set orientation to an a numerical value for easy
        // array selection.
        switch (entry) {
        case 'horizontal':
            parsed.ort = 0;
            break;
        case 'vertical':
            parsed.ort = 1;
            break;
        default:
            throw new Error("noUiSlider: 'orientation' option is invalid.");
        }
    }

    function testMargin(parsed, entry) {

        if (!isNumeric(entry)) {
            throw new Error("noUiSlider: 'margin' option must be numeric.");
        }

        // Issue #582
        if (entry === 0) {
            return;
        }

        parsed.margin = parsed.spectrum.getMargin(entry);

        if (!parsed.margin) {
            throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.");
        }
    }

    function testLimit(parsed, entry) {

        if (!isNumeric(entry)) {
            throw new Error("noUiSlider: 'limit' option must be numeric.");
        }

        parsed.limit = parsed.spectrum.getMargin(entry);

        if (!parsed.limit) {
            throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.");
        }
    }

    function testDirection(parsed, entry) {

        // Set direction as a numerical value for easy parsing.
        // Invert connection for RTL sliders, so that the proper
        // handles get the connect/background classes.
        switch (entry) {
        case 'ltr':
            parsed.dir = 0;
            break;
        case 'rtl':
            parsed.dir = 1;
            parsed.connect = [0, 2, 1, 3][parsed.connect];
            break;
        default:
            throw new Error("noUiSlider: 'direction' option was not recognized.");
        }
    }

    function testBehaviour(parsed, entry) {

        // Make sure the input is a string.
        if (typeof entry !== 'string') {
            throw new Error("noUiSlider: 'behaviour' must be a string containing options.");
        }

        // Check if the string contains any keywords.
        // None are required.
        var tap = entry.indexOf('tap') >= 0,
            drag = entry.indexOf('drag') >= 0,
            fixed = entry.indexOf('fixed') >= 0,
            snap = entry.indexOf('snap') >= 0,
            hover = entry.indexOf('hover') >= 0;

        // Fix #472
        if (drag && !parsed.connect) {
            throw new Error("noUiSlider: 'drag' behaviour must be used with 'connect': true.");
        }

        parsed.events = {
            tap: tap || snap,
            drag: drag,
            fixed: fixed,
            snap: snap,
            hover: hover
        };
    }

    function testTooltips(parsed, entry) {

        var i;

        if (entry === false) {
            return;
        } else if (entry === true) {

            parsed.tooltips = [];

            for (i = 0; i < parsed.handles; i++) {
                parsed.tooltips.push(true);
            }

        } else {

            parsed.tooltips = asArray(entry);

            if (parsed.tooltips.length !== parsed.handles) {
                throw new Error("noUiSlider: must pass a formatter for all handles.");
            }

            parsed.tooltips.forEach(function (formatter) {
                if (typeof formatter !== 'boolean' && (typeof formatter !== 'object' || typeof formatter.to !== 'function')) {
                    throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'.");
                }
            });
        }
    }

    function testFormat(parsed, entry) {

        parsed.format = entry;

        // Any object with a to and from method is supported.
        if (typeof entry.to === 'function' && typeof entry.from === 'function') {
            return true;
        }

        throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.");
    }

    function testCssPrefix(parsed, entry) {

        if (entry !== undefined && typeof entry !== 'string' && entry !== false) {
            throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`.");
        }

        parsed.cssPrefix = entry;
    }

    function testCssClasses(parsed, entry) {

        if (entry !== undefined && typeof entry !== 'object') {
            throw new Error("noUiSlider: 'cssClasses' must be an object.");
        }

        if (typeof parsed.cssPrefix === 'string') {
            parsed.cssClasses = {};

            for (var key in entry) {
                if (!entry.hasOwnProperty(key)) { continue; }

                parsed.cssClasses[key] = parsed.cssPrefix + entry[key];
            }
        } else {
            parsed.cssClasses = entry;
        }
    }

    // Test all developer settings and parse to assumption-safe values.
    function testOptions(options) {

        // To prove a fix for #537, freeze options here.
        // If the object is modified, an error will be thrown.
        // Object.freeze(options);

        var parsed = {
                margin: 0,
                limit: 0,
                animate: true,
                animationDuration: 300,
                format: defaultFormatter
            }, tests;

        // Tests are executed in the order they are presented here.
        tests = {
            'step': { r: false, t: testStep },
            'start': { r: true, t: testStart },
            'connect': { r: true, t: testConnect },
            'direction': { r: true, t: testDirection },
            'snap': { r: false, t: testSnap },
            'animate': { r: false, t: testAnimate },
            'animationDuration': { r: false, t: testAnimationDuration },
            'range': { r: true, t: testRange },
            'orientation': { r: false, t: testOrientation },
            'margin': { r: false, t: testMargin },
            'limit': { r: false, t: testLimit },
            'behaviour': { r: true, t: testBehaviour },
            'format': { r: false, t: testFormat },
            'tooltips': { r: false, t: testTooltips },
            'cssPrefix': { r: false, t: testCssPrefix },
            'cssClasses': { r: false, t: testCssClasses }
        };

        var defaults = {
            'connect': false,
            'direction': 'ltr',
            'behaviour': 'tap',
            'orientation': 'horizontal',
            'cssPrefix': 'noUi-',
            'cssClasses': {
                target: 'target',
                base: 'base',
                origin: 'origin',
                handle: 'handle',
                handleLower: 'handle-lower',
                handleUpper: 'handle-upper',
                horizontal: 'horizontal',
                vertical: 'vertical',
                background: 'background',
                connect: 'connect',
                ltr: 'ltr',
                rtl: 'rtl',
                draggable: 'draggable',
                drag: 'state-drag',
                tap: 'state-tap',
                active: 'active',
                stacking: 'stacking',
                tooltip: 'tooltip',
                pips: 'pips',
                pipsHorizontal: 'pips-horizontal',
                pipsVertical: 'pips-vertical',
                marker: 'marker',
                markerHorizontal: 'marker-horizontal',
                markerVertical: 'marker-vertical',
                markerNormal: 'marker-normal',
                markerLarge: 'marker-large',
                markerSub: 'marker-sub',
                value: 'value',
                valueHorizontal: 'value-horizontal',
                valueVertical: 'value-vertical',
                valueNormal: 'value-normal',
                valueLarge: 'value-large',
                valueSub: 'value-sub'
            }
        };

        // Run all options through a testing mechanism to ensure correct
        // input. It should be noted that options might get modified to
        // be handled properly. E.g. wrapping integers in arrays.
        Object.keys(tests).forEach(function (name) {

            // If the option isn't set, but it is required, throw an error.
            if (options[name] === undefined && defaults[name] === undefined) {

                if (tests[name].r) {
                    throw new Error("noUiSlider: '" + name + "' is required.");
                }

                return true;
            }

            tests[name].t(parsed, options[name] === undefined ? defaults[name] : options[name]);
        });

        // Forward pips options
        parsed.pips = options.pips;

        // Pre-define the styles.
        parsed.style = parsed.ort ? 'top' : 'left';

        return parsed;
    }


    function closure(target, options, originalOptions) {
        var
            actions = getActions(),
            // All variables local to 'closure' are prefixed with 'scope_'
            scope_Target = target,
            scope_Locations = [-1, -1],
            scope_Base,
            scope_Handles,
            scope_Spectrum = options.spectrum,
            scope_Values = [],
            scope_Events = {},
            scope_Self;


        // Delimit proposed values for handle positions.
        function getPositions(a, b, delimit) {

            // Add movement to current position.
            var c = a + b[0], d = a + b[1];

            // Only alter the other position on drag,
            // not on standard sliding.
            if (delimit) {
                if (c < 0) {
                    d += Math.abs(c);
                }
                if (d > 100) {
                    c -= (d - 100);
                }

                // Limit values to 0 and 100.
                return [limit(c), limit(d)];
            }

            return [c, d];
        }

        // Provide a clean event with standardized offset values.
        function fixEvent(e, pageOffset) {

            // Prevent scrolling and panning on touch events, while
            // attempting to slide. The tap event also depends on this.
            e.preventDefault();

            // Filter the event to register the type, which can be
            // touch, mouse or pointer. Offset changes need to be
            // made on an event specific basis.
            var touch = e.type.indexOf('touch') === 0,
                mouse = e.type.indexOf('mouse') === 0,
                pointer = e.type.indexOf('pointer') === 0,
                x, y, event = e;

            // IE10 implemented pointer events with a prefix;
            if (e.type.indexOf('MSPointer') === 0) {
                pointer = true;
            }

            if (touch) {
                // noUiSlider supports one movement at a time,
                // so we can select the first 'changedTouch'.
                x = e.changedTouches[0].pageX;
                y = e.changedTouches[0].pageY;
            }

            pageOffset = pageOffset || getPageOffset();

            if (mouse || pointer) {
                x = e.clientX + pageOffset.x;
                y = e.clientY + pageOffset.y;
            }

            event.pageOffset = pageOffset;
            event.points = [x, y];
            event.cursor = mouse || pointer; // Fix #435

            return event;
        }

        // Append a handle to the base.
        function addHandle(direction, index) {

            var origin = document.createElement('div'),
                handle = document.createElement('div'),
                classModifier = [options.cssClasses.handleLower, options.cssClasses.handleUpper];

            if (direction) {
                classModifier.reverse();
            }

            addClass(handle, options.cssClasses.handle);
            addClass(handle, classModifier[index]);

            addClass(origin, options.cssClasses.origin);
            origin.appendChild(handle);

            return origin;
        }

        // Add the proper connection classes.
        function addConnection(connect, target, handles) {

            // Apply the required connection classes to the elements
            // that need them. Some classes are made up for several
            // segments listed in the class list, to allow easy
            // renaming and provide a minor compression benefit.
            switch (connect) {
            case 1: addClass(target, options.cssClasses.connect);
                addClass(handles[0], options.cssClasses.background);
                break;
            case 3: addClass(handles[1], options.cssClasses.background);
            /* falls through */
            case 2: addClass(handles[0], options.cssClasses.connect);
            /* falls through */
            case 0: addClass(target, options.cssClasses.background);
                break;
            }
        }

        // Add handles to the slider base.
        function addHandles(nrHandles, direction, base) {

            var index, handles = [];

            // Append handles.
            for (index = 0; index < nrHandles; index += 1) {

                // Keep a list of all added handles.
                handles.push(base.appendChild(addHandle(direction, index)));
            }

            return handles;
        }

        // Initialize a single slider.
        function addSlider(direction, orientation, target) {

            // Apply classes and data to the target.
            addClass(target, options.cssClasses.target);

            if (direction === 0) {
                addClass(target, options.cssClasses.ltr);
            } else {
                addClass(target, options.cssClasses.rtl);
            }

            if (orientation === 0) {
                addClass(target, options.cssClasses.horizontal);
            } else {
                addClass(target, options.cssClasses.vertical);
            }

            var div = document.createElement('div');
            addClass(div, options.cssClasses.base);
            target.appendChild(div);
            return div;
        }


        function addTooltip(handle, index) {

            if (!options.tooltips[index]) {
                return false;
            }

            var element = document.createElement('div');
            element.className = options.cssClasses.tooltip;
            return handle.firstChild.appendChild(element);
        }

        // The tooltips option is a shorthand for using the 'update' event.
        function tooltips() {

            if (options.dir) {
                options.tooltips.reverse();
            }

            // Tooltips are added with options.tooltips in original order.
            var tips = scope_Handles.map(addTooltip);

            if (options.dir) {
                tips.reverse();
                options.tooltips.reverse();
            }

            bindEvent('update', function (f, o, r) {
                if (tips[o]) {
                    tips[o].innerHTML = options.tooltips[o] === true ? f[o] : options.tooltips[o].to(r[o]);
                }
            });
        }


        function getGroup(mode, values, stepped) {

            // Use the range.
            if (mode === 'range' || mode === 'steps') {
                return scope_Spectrum.xVal;
            }

            if (mode === 'count') {

                // Divide 0 - 100 in 'count' parts.
                var spread = (100 / (values - 1)), v, i = 0;
                values = [];

                // List these parts and have them handled as 'positions'.
                while ((v = i++ * spread) <= 100) {
                    values.push(v);
                }

                mode = 'positions';
            }

            if (mode === 'positions') {

                // Map all percentages to on-range values.
                return values.map(function (value) {
                    return scope_Spectrum.fromStepping(stepped ? scope_Spectrum.getStep(value) : value);
                });
            }

            if (mode === 'values') {

                // If the value must be stepped, it needs to be converted to a percentage first.
                if (stepped) {

                    return values.map(function (value) {

                        // Convert to percentage, apply step, return to value.
                        return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)));
                    });

                }

                // Otherwise, we can simply use the values.
                return values;
            }
        }

        function generateSpread(density, mode, group) {

            function safeIncrement(value, increment) {
                // Avoid floating point variance by dropping the smallest decimal places.
                return (value + increment).toFixed(7) / 1;
            }

            var originalSpectrumDirection = scope_Spectrum.direction,
                indexes = {},
                firstInRange = scope_Spectrum.xVal[0],
                lastInRange = scope_Spectrum.xVal[scope_Spectrum.xVal.length - 1],
                ignoreFirst = false,
                ignoreLast = false,
                prevPct = 0;

            // This function loops the spectrum in an ltr linear fashion,
            // while the toStepping method is direction aware. Trick it into
            // believing it is ltr.
            scope_Spectrum.direction = 0;

            // Create a copy of the group, sort it and filter away all duplicates.
            group = unique(group.slice().sort(function (a, b) { return a - b; }));

            // Make sure the range starts with the first element.
            if (group[0] !== firstInRange) {
                group.unshift(firstInRange);
                ignoreFirst = true;
            }

            // Likewise for the last one.
            if (group[group.length - 1] !== lastInRange) {
                group.push(lastInRange);
                ignoreLast = true;
            }

            group.forEach(function (current, index) {

                // Get the current step and the lower + upper positions.
                var step, i, q,
                    low = current,
                    high = group[index + 1],
                    newPct, pctDifference, pctPos, type,
                    steps, realSteps, stepsize;

                // When using 'steps' mode, use the provided steps.
                // Otherwise, we'll step on to the next subrange.
                if (mode === 'steps') {
                    step = scope_Spectrum.xNumSteps[index];
                }

                // Default to a 'full' step.
                if (!step) {
                    step = high - low;
                }

                // Low can be 0, so test for false. If high is undefined,
                // we are at the last subrange. Index 0 is already handled.
                if (low === false || high === undefined) {
                    return;
                }

                // Find all steps in the subrange.
                for (i = low; i <= high; i = safeIncrement(i, step)) {

                    // Get the percentage value for the current step,
                    // calculate the size for the subrange.
                    newPct = scope_Spectrum.toStepping(i);
                    pctDifference = newPct - prevPct;

                    steps = pctDifference / density;
                    realSteps = Math.round(steps);

                    // This ratio represents the ammount of percentage-space a point indicates.
                    // For a density 1 the points/percentage = 1. For density 2, that percentage needs to be re-devided.
                    // Round the percentage offset to an even number, then divide by two
                    // to spread the offset on both sides of the range.
                    stepsize = pctDifference / realSteps;

                    // Divide all points evenly, adding the correct number to this subrange.
                    // Run up to <= so that 100% gets a point, event if ignoreLast is set.
                    for (q = 1; q <= realSteps; q += 1) {

                        // The ratio between the rounded value and the actual size might be ~1% off.
                        // Correct the percentage offset by the number of points
                        // per subrange. density = 1 will result in 100 points on the
                        // full range, 2 for 50, 4 for 25, etc.
                        pctPos = prevPct + (q * stepsize);
                        indexes[pctPos.toFixed(5)] = ['x', 0];
                    }

                    // Determine the point type.
                    type = (group.indexOf(i) > -1) ? 1 : (mode === 'steps' ? 2 : 0);

                    // Enforce the 'ignoreFirst' option by overwriting the type for 0.
                    if (!index && ignoreFirst) {
                        type = 0;
                    }

                    if (!(i === high && ignoreLast)) {
                        // Mark the 'type' of this point. 0 = plain, 1 = real value, 2 = step value.
                        indexes[newPct.toFixed(5)] = [i, type];
                    }

                    // Update the percentage count.
                    prevPct = newPct;
                }
            });

            // Reset the spectrum.
            scope_Spectrum.direction = originalSpectrumDirection;

            return indexes;
        }

        function addMarking(spread, filterFunc, formatter) {

            var element = document.createElement('div'),
                out = '',
                valueSizeClasses = [
                    options.cssClasses.valueNormal,
                    options.cssClasses.valueLarge,
                    options.cssClasses.valueSub
                ],
                markerSizeClasses = [
                    options.cssClasses.markerNormal,
                    options.cssClasses.markerLarge,
                    options.cssClasses.markerSub
                ],
                valueOrientationClasses = [
                    options.cssClasses.valueHorizontal,
                    options.cssClasses.valueVertical
                ],
                markerOrientationClasses = [
                    options.cssClasses.markerHorizontal,
                    options.cssClasses.markerVertical
                ];

            addClass(element, options.cssClasses.pips);
            addClass(element, options.ort === 0 ? options.cssClasses.pipsHorizontal : options.cssClasses.pipsVertical);

            function getClasses(type, source) {
                var a = source === options.cssClasses.value,
                    orientationClasses = a ? valueOrientationClasses : markerOrientationClasses,
                    sizeClasses = a ? valueSizeClasses : markerSizeClasses;

                return source + ' ' + orientationClasses[options.ort] + ' ' + sizeClasses[type];
            }

            function getTags(offset, source, values) {
                return 'class="' + getClasses(values[1], source) + '" style="' + options.style + ': ' + offset + '%"';
            }

            function addSpread(offset, values) {

                if (scope_Spectrum.direction) {
                    offset = 100 - offset;
                }

                // Apply the filter function, if it is set.
                values[1] = (values[1] && filterFunc) ? filterFunc(values[0], values[1]) : values[1];

                // Add a marker for every point
                out += '<div ' + getTags(offset, options.cssClasses.marker, values) + '></div>';

                // Values are only appended for points marked '1' or '2'.
                if (values[1]) {
                    out += '<div ' + getTags(offset, options.cssClasses.value, values) + '>' + formatter.to(values[0]) + '</div>';
                }
            }

            // Append all points.
            Object.keys(spread).forEach(function (a) {
                addSpread(a, spread[a]);
            });

            element.innerHTML = out;

            return element;
        }

        function pips(grid) {

            var mode = grid.mode,
                density = grid.density || 1,
                filter = grid.filter || false,
                values = grid.values || false,
                stepped = grid.stepped || false,
                group = getGroup(mode, values, stepped),
                spread = generateSpread(density, mode, group),
                format = grid.format || {
                    to: Math.round
                };

            return scope_Target.appendChild(addMarking(
                spread,
                filter,
                format
            ));
        }


        // Shorthand for base dimensions.
        function baseSize() {
            var rect = scope_Base.getBoundingClientRect(), alt = 'offset' + ['Width', 'Height'][options.ort];
            return options.ort === 0 ? (rect.width || scope_Base[alt]) : (rect.height || scope_Base[alt]);
        }

        // External event handling
        function fireEvent(event, handleNumber, tap) {

            var i;

            // During initialization, do not fire events.
            for (i = 0; i < options.handles; i++) {
                if (scope_Locations[i] === -1) {
                    return;
                }
            }

            if (handleNumber !== undefined && options.handles !== 1) {
                handleNumber = Math.abs(handleNumber - options.dir);
            }

            Object.keys(scope_Events).forEach(function (targetEvent) {

                var eventType = targetEvent.split('.')[0];

                if (event === eventType) {
                    scope_Events[targetEvent].forEach(function (callback) {

                        callback.call(
                            // Use the slider public API as the scope ('this')
                            scope_Self,
                            // Return values as array, so arg_1[arg_2] is always valid.
                            asArray(valueGet()),
                            // Handle index, 0 or 1
                            handleNumber,
                            // Unformatted slider values
                            asArray(inSliderOrder(Array.prototype.slice.call(scope_Values))),
                            // Event is fired by tap, true or false
                            tap || false,
                            // Left offset of the handle, in relation to the slider
                            scope_Locations
                        );
                    });
                }
            });
        }

        // Returns the input array, respecting the slider direction configuration.
        function inSliderOrder(values) {

            // If only one handle is used, return a single value.
            if (values.length === 1) {
                return values[0];
            }

            if (options.dir) {
                return values.reverse();
            }

            return values;
        }


        // Handler for attaching events trough a proxy.
        function attach(events, element, callback, data) {

            // This function can be used to 'filter' events to the slider.
            // element is a node, not a nodeList

            var method = function (e) {

                if (scope_Target.hasAttribute('disabled')) {
                    return false;
                }

                // Stop if an active 'tap' transition is taking place.
                if (hasClass(scope_Target, options.cssClasses.tap)) {
                    return false;
                }

                e = fixEvent(e, data.pageOffset);

                // Ignore right or middle clicks on start #454
                if (events === actions.start && e.buttons !== undefined && e.buttons > 1) {
                    return false;
                }

                // Ignore right or middle clicks on start #454
                if (data.hover && e.buttons) {
                    return false;
                }

                e.calcPoint = e.points[options.ort];

                // Call the event handler with the event [ and additional data ].
                callback(e, data);

            }, methods = [];

            // Bind a closure on the target for every event type.
            events.split(' ').forEach(function (eventName) {
                element.addEventListener(eventName, method, false);
                methods.push([eventName, method]);
            });

            return methods;
        }

        // Handle movement on document for handle and range drag.
        function move(event, data) {

            // Fix #498
            // Check value of .buttons in 'start' to work around a bug in IE10 mobile (data.buttonsProperty).
            // https://connect.microsoft.com/IE/feedback/details/927005/mobile-ie10-windows-phone-buttons-property-of-pointermove-event-always-zero
            // IE9 has .buttons and .which zero on mousemove.
            // Firefox breaks the spec MDN defines.
            if (navigator.appVersion.indexOf("MSIE 9") === -1 && event.buttons === 0 && data.buttonsProperty !== 0) {
                return end(event, data);
            }

            var handles = data.handles || scope_Handles, positions, state = false,
                proposal = ((event.calcPoint - data.start) * 100) / data.baseSize,
                handleNumber = handles[0] === scope_Handles[0] ? 0 : 1, i;

            // Calculate relative positions for the handles.
            positions = getPositions(proposal, data.positions, handles.length > 1);

            state = setHandle(handles[0], positions[handleNumber], handles.length === 1);

            if (handles.length > 1) {

                state = setHandle(handles[1], positions[handleNumber ? 0 : 1], false) || state;

                if (state) {
                    // fire for both handles
                    for (i = 0; i < data.handles.length; i++) {
                        fireEvent('slide', i);
                    }
                }
            } else if (state) {
                // Fire for a single handle
                fireEvent('slide', handleNumber);
            }
        }

        // Unbind move events on document, call callbacks.
        function end(event, data) {

            // The handle is no longer active, so remove the class.
            var active = scope_Base.querySelector('.' + options.cssClasses.active),
                handleNumber = data.handles[0] === scope_Handles[0] ? 0 : 1;

            if (active !== null) {
                removeClass(active, options.cssClasses.active);
            }

            // Remove cursor styles and text-selection events bound to the body.
            if (event.cursor) {
                document.body.style.cursor = '';
                document.body.removeEventListener('selectstart', document.body.noUiListener);
            }

            var d = document.documentElement;

            // Unbind the move and end events, which are added on 'start'.
            d.noUiListeners.forEach(function (c) {
                d.removeEventListener(c[0], c[1]);
            });

            // Remove dragging class.
            removeClass(scope_Target, options.cssClasses.drag);

            // Fire the change and set events.
            fireEvent('set', handleNumber);
            fireEvent('change', handleNumber);

            // If this is a standard handle movement, fire the end event.
            if (data.handleNumber !== undefined) {
                fireEvent('end', data.handleNumber);
            }
        }

        // Fire 'end' when a mouse or pen leaves the document.
        function documentLeave(event, data) {
            if (event.type === "mouseout" && event.target.nodeName === "HTML" && event.relatedTarget === null) {
                end(event, data);
            }
        }

        // Bind move events on document.
        function start(event, data) {

            var d = document.documentElement;

            // Mark the handle as 'active' so it can be styled.
            if (data.handles.length === 1) {
                // Support 'disabled' handles
                if (data.handles[0].hasAttribute('disabled')) {
                    return false;
                }

                addClass(data.handles[0].children[0], options.cssClasses.active);
            }

            // Fix #551, where a handle gets selected instead of dragged.
            event.preventDefault();

            // A drag should never propagate up to the 'tap' event.
            event.stopPropagation();

            // Attach the move and end events.
            var moveEvent = attach(actions.move, d, move, {
                    start: event.calcPoint,
                    baseSize: baseSize(),
                    pageOffset: event.pageOffset,
                    handles: data.handles,
                    handleNumber: data.handleNumber,
                    buttonsProperty: event.buttons,
                    positions: [
                        scope_Locations[0],
                        scope_Locations[scope_Handles.length - 1]
                    ]
                }), endEvent = attach(actions.end, d, end, {
                        handles: data.handles,
                        handleNumber: data.handleNumber
                    });

            var outEvent = attach("mouseout", d, documentLeave, {
                handles: data.handles,
                handleNumber: data.handleNumber
            });

            d.noUiListeners = moveEvent.concat(endEvent, outEvent);

            // Text selection isn't an issue on touch devices,
            // so adding cursor styles can be skipped.
            if (event.cursor) {

                // Prevent the 'I' cursor and extend the range-drag cursor.
                document.body.style.cursor = getComputedStyle(event.target).cursor;

                // Mark the target with a dragging state.
                if (scope_Handles.length > 1) {
                    addClass(scope_Target, options.cssClasses.drag);
                }

                var f = function () {
                    return false;
                };

                document.body.noUiListener = f;

                // Prevent text selection when dragging the handles.
                document.body.addEventListener('selectstart', f, false);
            }

            if (data.handleNumber !== undefined) {
                fireEvent('start', data.handleNumber);
            }
        }

        // Move closest handle to tapped location.
        function tap(event) {

            var location = event.calcPoint, total = 0, handleNumber, to;

            // The tap event shouldn't propagate up and cause 'edge' to run.
            event.stopPropagation();

            // Add up the handle offsets.
            scope_Handles.forEach(function (a) {
                total += offset(a)[options.style];
            });

            // Find the handle closest to the tapped position.
            handleNumber = (location < total / 2 || scope_Handles.length === 1) ? 0 : 1;

            // Check if handler is not disablet if yes set number to the next handler
            if (scope_Handles[handleNumber].hasAttribute('disabled')) {
                handleNumber = handleNumber ? 0 : 1;
            }

            location -= offset(scope_Base)[options.style];

            // Calculate the new position.
            to = (location * 100) / baseSize();

            if (!options.events.snap) {
                // Flag the slider as it is now in a transitional state.
                // Transition takes a configurable amount of ms (default 300). Re-enable the slider after that.
                addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
            }

            // Support 'disabled' handles
            if (scope_Handles[handleNumber].hasAttribute('disabled')) {
                return false;
            }

            // Find the closest handle and calculate the tapped point.
            // The set handle to the new position.
            setHandle(scope_Handles[handleNumber], to);

            fireEvent('slide', handleNumber, true);
            fireEvent('set', handleNumber, true);
            fireEvent('change', handleNumber, true);

            if (options.events.snap) {
                start(event, { handles: [scope_Handles[handleNumber]] });
            }
        }

        // Fires a 'hover' event for a hovered mouse/pen position.
        function hover(event) {

            var location = event.calcPoint - offset(scope_Base)[options.style],
                to = scope_Spectrum.getStep((location * 100) / baseSize()),
                value = scope_Spectrum.fromStepping(to);

            Object.keys(scope_Events).forEach(function (targetEvent) {
                if ('hover' === targetEvent.split('.')[0]) {
                    scope_Events[targetEvent].forEach(function (callback) {
                        callback.call(scope_Self, value);
                    });
                }
            });
        }

        // Attach events to several slider parts.
        function events(behaviour) {

            // Attach the standard drag event to the handles.
            if (!behaviour.fixed) {

                scope_Handles.forEach(function (handle, index) {

                    // These events are only bound to the visual handle
                    // element, not the 'real' origin element.
                    attach(actions.start, handle.children[0], start, {
                        handles: [handle],
                        handleNumber: index
                    });
                });
            }

            // Attach the tap event to the slider base.
            if (behaviour.tap) {

                attach(actions.start, scope_Base, tap, {
                    handles: scope_Handles
                });
            }

            // Fire hover events
            if (behaviour.hover) {
                attach(actions.move, scope_Base, hover, { hover: true });
            }

            // Make the range draggable.
            if (behaviour.drag) {

                var drag = [scope_Base.querySelector('.' + options.cssClasses.connect)];
                addClass(drag[0], options.cssClasses.draggable);

                // When the range is fixed, the entire range can
                // be dragged by the handles. The handle in the first
                // origin will propagate the start event upward,
                // but it needs to be bound manually on the other.
                if (behaviour.fixed) {
                    drag.push(scope_Handles[(drag[0] === scope_Handles[0] ? 1 : 0)].children[0]);
                }

                drag.forEach(function (element) {
                    attach(actions.start, element, start, {
                        handles: scope_Handles
                    });
                });
            }
        }


        // Test suggested values and apply margin, step.
        function setHandle(handle, to, noLimitOption) {

            var trigger = handle !== scope_Handles[0] ? 1 : 0,
                lowerMargin = scope_Locations[0] + options.margin,
                upperMargin = scope_Locations[1] - options.margin,
                lowerLimit = scope_Locations[0] + options.limit,
                upperLimit = scope_Locations[1] - options.limit;

            // For sliders with multiple handles,
            // limit movement to the other handle.
            // Apply the margin option by adding it to the handle positions.
            if (scope_Handles.length > 1) {
                to = trigger ? Math.max(to, lowerMargin) : Math.min(to, upperMargin);
            }

            // The limit option has the opposite effect, limiting handles to a
            // maximum distance from another. Limit must be > 0, as otherwise
            // handles would be unmoveable. 'noLimitOption' is set to 'false'
            // for the .val() method, except for pass 4/4.
            if (noLimitOption !== false && options.limit && scope_Handles.length > 1) {
                to = trigger ? Math.min(to, lowerLimit) : Math.max(to, upperLimit);
            }

            // Handle the step option.
            to = scope_Spectrum.getStep(to);

            // Limit percentage to the 0 - 100 range
            to = limit(to);

            // Return false if handle can't move
            if (to === scope_Locations[trigger]) {
                return false;
            }

            // Set the handle to the new position.
            // Use requestAnimationFrame for efficient painting.
            // No significant effect in Chrome, Edge sees dramatic
            // performace improvements.
            if (window.requestAnimationFrame) {
                window.requestAnimationFrame(function () {
                    handle.style[options.style] = to + '%';
                });
            } else {
                handle.style[options.style] = to + '%';
            }

            // Force proper handle stacking
            if (!handle.previousSibling) {
                removeClass(handle, options.cssClasses.stacking);
                if (to > 50) {
                    addClass(handle, options.cssClasses.stacking);
                }
            }

            // Update locations.
            scope_Locations[trigger] = to;

            // Convert the value to the slider stepping/range.
            scope_Values[trigger] = scope_Spectrum.fromStepping(to);

            fireEvent('update', trigger);

            return true;
        }

        // Loop values from value method and apply them.
        function setValues(count, values) {

            var i, trigger, to;

            // With the limit option, we'll need another limiting pass.
            if (options.limit) {
                count += 1;
            }

            // If there are multiple handles to be set run the setting
            // mechanism twice for the first handle, to make sure it
            // can be bounced of the second one properly.
            for (i = 0; i < count; i += 1) {

                trigger = i % 2;

                // Get the current argument from the array.
                to = values[trigger];

                // Setting with null indicates an 'ignore'.
                // Inputting 'false' is invalid.
                if (to !== null && to !== false) {

                    // If a formatted number was passed, attemt to decode it.
                    if (typeof to === 'number') {
                        to = String(to);
                    }

                    to = options.format.from(to);

                    // Request an update for all links if the value was invalid.
                    // Do so too if setting the handle fails.
                    if (to === false || isNaN(to) || setHandle(scope_Handles[trigger], scope_Spectrum.toStepping(to), i === (3 - options.dir)) === false) {
                        fireEvent('update', trigger);
                    }
                }
            }
        }

        // Set the slider value.
        function valueSet(input, fireSetEvent) {

            var count, values = asArray(input), i;

            // Event fires by default
            fireSetEvent = (fireSetEvent === undefined ? true : !!fireSetEvent);

            // The RTL settings is implemented by reversing the front-end,
            // internal mechanisms are the same.
            if (options.dir && options.handles > 1) {
                values.reverse();
            }

            // Animation is optional.
            // Make sure the initial values where set before using animated placement.
            if (options.animate && scope_Locations[0] !== -1) {
                addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
            }

            // Determine how often to set the handles.
            count = scope_Handles.length > 1 ? 3 : 1;

            if (values.length === 1) {
                count = 1;
            }

            setValues(count, values);

            // Fire the 'set' event for both handles.
            for (i = 0; i < scope_Handles.length; i++) {

                // Fire the event only for handles that received a new value, as per #579
                if (values[i] !== null && fireSetEvent) {
                    fireEvent('set', i);
                }
            }
        }

        // Get the slider value.
        function valueGet() {

            var i, retour = [];

            // Get the value from all handles.
            for (i = 0; i < options.handles; i += 1) {
                retour[i] = options.format.to(scope_Values[i]);
            }

            return inSliderOrder(retour);
        }

        // Removes classes from the root and empties it.
        function destroy() {

            for (var key in options.cssClasses) {
                if (!options.cssClasses.hasOwnProperty(key)) { continue; }
                removeClass(scope_Target, options.cssClasses[key]);
            }

            while (scope_Target.firstChild) {
                scope_Target.removeChild(scope_Target.firstChild);
            }

            delete scope_Target.noUiSlider;
        }

        // Get the current step size for the slider.
        function getCurrentStep() {

            // Check all locations, map them to their stepping point.
            // Get the step point, then find it in the input list.
            var retour = scope_Locations.map(function (location, index) {

                var step = scope_Spectrum.getApplicableStep(location),

                    // As per #391, the comparison for the decrement step can have some rounding issues.
                    // Round the value to the precision used in the step.
                    stepDecimals = countDecimals(String(step[2])),

                    // Get the current numeric value
                    value = scope_Values[index],

                    // To move the slider 'one step up', the current step value needs to be added.
                    // Use null if we are at the maximum slider value.
                    increment = location === 100 ? null : step[2],

                    // Going 'one step down' might put the slider in a different sub-range, so we
                    // need to switch between the current or the previous step.
                    prev = Number((value - step[2]).toFixed(stepDecimals)),

                    // If the value fits the step, return the current step value. Otherwise, use the
                    // previous step. Return null if the slider is at its minimum value.
                    decrement = location === 0 ? null : (prev >= step[1]) ? step[2] : (step[0] || false);

                return [decrement, increment];
            });

            // Return values in the proper order.
            return inSliderOrder(retour);
        }

        // Attach an event to this slider, possibly including a namespace
        function bindEvent(namespacedEvent, callback) {
            scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || [];
            scope_Events[namespacedEvent].push(callback);

            // If the event bound is 'update,' fire it immediately for all handles.
            if (namespacedEvent.split('.')[0] === 'update') {
                scope_Handles.forEach(function (a, index) {
                    fireEvent('update', index);
                });
            }
        }

        // Undo attachment of event
        function removeEvent(namespacedEvent) {

            var event = namespacedEvent && namespacedEvent.split('.')[0],
                namespace = event && namespacedEvent.substring(event.length);

            Object.keys(scope_Events).forEach(function (bind) {

                var tEvent = bind.split('.')[0],
                    tNamespace = bind.substring(tEvent.length);

                if ((!event || event === tEvent) && (!namespace || namespace === tNamespace)) {
                    delete scope_Events[bind];
                }
            });
        }

        // Updateable: margin, limit, step, range, animate, snap
        function updateOptions(optionsToUpdate, fireSetEvent) {

            // Spectrum is created using the range, snap, direction and step options.
            // 'snap' and 'step' can be updated, 'direction' cannot, due to event binding.
            // If 'snap' and 'step' are not passed, they should remain unchanged.
            var v = valueGet(), newOptions = testOptions({
                                    start: [0, 0],
                                    margin: optionsToUpdate.margin,
                                    limit: optionsToUpdate.limit,
                                    step: optionsToUpdate.step === undefined ? options.singleStep : optionsToUpdate.step,
                                    range: optionsToUpdate.range,
                                    animate: optionsToUpdate.animate,
                                    snap: optionsToUpdate.snap === undefined ? options.snap : optionsToUpdate.snap
                                });

            ['margin', 'limit', 'range', 'animate'].forEach(function (name) {

                // Only change options that we're actually passed to update.
                if (optionsToUpdate[name] !== undefined) {
                    options[name] = optionsToUpdate[name];
                }
            });

            // Save current spectrum direction as testOptions in testRange call
            // doesn't rely on current direction
            newOptions.spectrum.direction = scope_Spectrum.direction;
            scope_Spectrum = newOptions.spectrum;

            // Invalidate the current positioning so valueSet forces an update.
            scope_Locations = [-1, -1];
            valueSet(optionsToUpdate.start || v, fireSetEvent);
        }


        // Throw an error if the slider was already initialized.
        if (scope_Target.noUiSlider) {
            throw new Error('Slider was already initialized.');
        }

        // Create the base element, initialise HTML and set classes.
        // Add handles and links.
        scope_Base = addSlider(options.dir, options.ort, scope_Target);
        scope_Handles = addHandles(options.handles, options.dir, scope_Base);

        // Set the connect classes.
        addConnection(options.connect, scope_Target, scope_Handles);

        if (options.pips) {
            pips(options.pips);
        }

        if (options.tooltips) {
            tooltips();
        }

        scope_Self = {
            destroy: destroy,
            steps: getCurrentStep,
            on: bindEvent,
            off: removeEvent,
            get: valueGet,
            set: valueSet,
            updateOptions: updateOptions,
            options: originalOptions, // Issue #600
            target: scope_Target, // Issue #597
            pips: pips // Issue #594
        };

        // Attach user events.
        events(options.events);

        return scope_Self;

    }


    // Run the standard initializer
    function initialize(target, originalOptions) {

        if (!target.nodeName) {
            throw new Error('noUiSlider.create requires a single element.');
        }

        // Test the options and create the slider environment;
        var options = testOptions(originalOptions, target),
            slider = closure(target, options, originalOptions);

        // Use the public value method to set the start values.
        slider.set(options.start);

        target.noUiSlider = slider;
        return slider;
    }

    // Use an object instead of a function for future expansibility;
    return {
        create: initialize
    };

}));
/*! 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 */
window.matchMedia||(window.matchMedia=function(){"use strict";var a=window.styleMedia||window.media;if(!a){var b=document.createElement("style"),c=document.getElementsByTagName("script")[0],d=null;b.type="text/css",b.id="matchmediajs-test",c.parentNode.insertBefore(b,c),d="getComputedStyle"in window&&window.getComputedStyle(b,null)||b.currentStyle,a={matchMedium:function(a){var c="@media "+a+"{ #matchmediajs-test { width: 1px; } }";return b.styleSheet?b.styleSheet.cssText=c:b.textContent=c,"1px"===d.width}}}return function(b){return{matches:a.matchMedium(b||"all"),media:b||"all"}}}()),function(a,b){"use strict";function c(a){var b,c,d,f,g,h=a||{};b=h.elements||e.getAllElements();for(var i=0,j=b.length;j>i;i++)if(c=b[i],d=c.parentNode,f=void 0,g=void 0,c[e.ns]||(c[e.ns]={}),h.reevaluate||!c[e.ns].evaluated){if("PICTURE"===d.nodeName.toUpperCase()){if(e.removeVideoShim(d),f=e.getMatch(c,d),f===!1)continue}else f=void 0;("PICTURE"===d.nodeName.toUpperCase()||c.srcset&&!e.srcsetSupported||!e.sizesSupported&&c.srcset&&c.srcset.indexOf("w")>-1)&&e.dodgeSrcset(c),f?(g=e.processSourceSet(f),e.applyBestCandidate(g,c)):(g=e.processSourceSet(c),(void 0===c.srcset||c[e.ns].srcset)&&e.applyBestCandidate(g,c)),c[e.ns].evaluated=!0}}function d(){c();var d=setInterval(function(){return c(),/^loaded|^i|^c/.test(b.readyState)?void clearInterval(d):void 0},250);if(a.addEventListener){var e;a.addEventListener("resize",function(){a._picturefillWorking||(a._picturefillWorking=!0,a.clearTimeout(e),e=a.setTimeout(function(){c({reevaluate:!0}),a._picturefillWorking=!1},60))},!1)}}if(a.HTMLPictureElement)return void(a.picturefill=function(){});b.createElement("picture");var e={};e.ns="picturefill",e.srcsetSupported="srcset"in b.createElement("img"),e.sizesSupported=a.HTMLImageElement.sizes,e.trim=function(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")},e.endsWith=function(a,b){return a.endsWith?a.endsWith(b):-1!==a.indexOf(b,a.length-b.length)},e.matchesMedia=function(b){return a.matchMedia&&a.matchMedia(b).matches},e.getDpr=function(){return a.devicePixelRatio||1},e.getWidthFromLength=function(a){return a=a&&(parseFloat(a)>0||a.indexOf("calc(")>-1)?a:"100vw",a=a.replace("vw","%"),e.lengthEl||(e.lengthEl=b.createElement("div"),b.documentElement.insertBefore(e.lengthEl,b.documentElement.firstChild)),e.lengthEl.style.cssText="position: absolute; left: 0; width: "+a+";",e.lengthEl.offsetWidth<=0&&(e.lengthEl.style.cssText="width: 100%;"),e.lengthEl.offsetWidth},e.types={},e.types["image/jpeg"]=!0,e.types["image/gif"]=!0,e.types["image/png"]=!0,e.types["image/svg+xml"]=b.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1"),e.types["image/webp"]=function(){var b=new a.Image,d="image/webp";b.onerror=function(){e.types[d]=!1,c()},b.onload=function(){e.types[d]=1===b.width,c()},b.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="},e.verifyTypeSupport=function(a){var b=a.getAttribute("type");return null===b||""===b?!0:"function"==typeof e.types[b]?(e.types[b](),"pending"):e.types[b]},e.parseSize=function(a){var b=/(\([^)]+\))?\s*(.+)/g.exec(a);return{media:b&&b[1],length:b&&b[2]}},e.findWidthFromSourceSize=function(a){for(var b,c=e.trim(a).split(/\s*,\s*/),d=0,f=c.length;f>d;d++){var g=c[d],h=e.parseSize(g),i=h.length,j=h.media;if(i&&(!j||e.matchesMedia(j))){b=i;break}}return e.getWidthFromLength(b)},e.parseSrcset=function(a){for(var b=[];""!==a;){a=a.replace(/^\s+/g,"");var c,d=a.search(/\s/g),e=null;if(-1!==d){c=a.slice(0,d);var f=c[c.length-1];if((","===f||""===c)&&(c=c.replace(/,+$/,""),e=""),a=a.slice(d+1),null===e){var g=a.indexOf(",");-1!==g?(e=a.slice(0,g),a=a.slice(g+1)):(e=a,a="")}}else c=a,a="";(c||e)&&b.push({url:c,descriptor:e})}return b},e.parseDescriptor=function(a,b){var c,d=b||"100vw",f=a&&a.replace(/(^\s+|\s+$)/g,""),g=e.findWidthFromSourceSize(d);if(f)for(var h=f.split(" "),i=h.length+1;i>=0;i--)if(void 0!==h[i]){var j=h[i],k=j&&j.slice(j.length-1);if("h"!==k&&"w"!==k||e.sizesSupported){if("x"===k){var l=j&&parseFloat(j,10);c=l&&!isNaN(l)?l:1}}else c=parseFloat(parseInt(j,10)/g)}return c||1},e.getCandidatesFromSourceSet=function(a,b){for(var c=e.parseSrcset(a),d=[],f=0,g=c.length;g>f;f++){var h=c[f];d.push({url:h.url,resolution:e.parseDescriptor(h.descriptor,b)})}return d},e.dodgeSrcset=function(a){a.srcset&&(a[e.ns].srcset=a.srcset,a.removeAttribute("srcset"))},e.processSourceSet=function(a){var b=a.getAttribute("srcset"),c=a.getAttribute("sizes"),d=[];return"IMG"===a.nodeName.toUpperCase()&&a[e.ns]&&a[e.ns].srcset&&(b=a[e.ns].srcset),b&&(d=e.getCandidatesFromSourceSet(b,c)),d},e.applyBestCandidate=function(a,b){var c,d,f;a.sort(e.ascendingSort),d=a.length,f=a[d-1];for(var g=0;d>g;g++)if(c=a[g],c.resolution>=e.getDpr()){f=c;break}f&&!e.endsWith(b.src,f.url)&&(b.src=f.url,b.currentSrc=b.src)},e.ascendingSort=function(a,b){return a.resolution-b.resolution},e.removeVideoShim=function(a){var b=a.getElementsByTagName("video");if(b.length){for(var c=b[0],d=c.getElementsByTagName("source");d.length;)a.insertBefore(d[0],c);c.parentNode.removeChild(c)}},e.getAllElements=function(){for(var a=[],c=b.getElementsByTagName("img"),d=0,f=c.length;f>d;d++){var g=c[d];("PICTURE"===g.parentNode.nodeName.toUpperCase()||null!==g.getAttribute("srcset")||g[e.ns]&&null!==g[e.ns].srcset)&&a.push(g)}return a},e.getMatch=function(a,b){for(var c,d=b.childNodes,f=0,g=d.length;g>f;f++){var h=d[f];if(1===h.nodeType){if(h===a)return c;if("SOURCE"===h.nodeName.toUpperCase()){null!==h.getAttribute("src")&&void 0!==typeof console&&console.warn("The `src` attribute is invalid on `picture` `source` element; instead, use `srcset`.");var i=h.getAttribute("media");if(h.getAttribute("srcset")&&(!i||e.matchesMedia(i))){var j=e.verifyTypeSupport(h);if(j===!0){c=h;break}if("pending"===j)return!1}}}}return c},d(),c._=e,"object"==typeof module&&"object"==typeof module.exports?module.exports=c:"function"==typeof define&&define.amd?define(function(){return c}):"object"==typeof a&&(a.picturefill=c)}(this,this.document);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchResults = window.eviivo.searchResults ? window.eviivo.searchResults : {};

window.eviivo.searchResults = function ($) {
    var defaultOptions = {};
    var options;
    var $searchForm;
    var $mapPopupLnk;
    var $pageNoTextBox;
    var $mapMarkerToken;
    var $mapCanvasId;
    var $locationTextboxId;
    var $quickView;
    var $shortList;
    var $modTile;
    var $priceNotAvailable;
    
    ///<summary>Main init method of the eviivo.searchResults object</summary>
    ///<param name="settings">external settings</param>

    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);

        $searchForm = $("#eviivo-partner-search-form");
        $pageNoTextBox = $("#pageindex");
        $mapMarkerToken = 'mapMarker';
        $mapCanvasId = 'map-canvas';
        $locationTextboxId = 'eviivo-search-destination';
        $quickView = $(".mod-quickView");

        $mapPopupLnk = $(".cp-link").find('a');
        $shortList = $(".cp-button-sl");
        $modTile = $(".mod-tile");
        $priceNotAvailable = $("a.cp-linkCustom");
        
        $shortList.on("click", function() {
            $(this).toggleClass("selected");
        });

        //Todo: this needs to be moved into separate code block
        $priceNotAvailable.on("click", function(e) {
            e.preventDefault();
            e.stopPropagation();
            $("#eviivo-search-start-date").focus();
        });
        
        $mapPopupLnk.on("click", function () {
            window.eviivo.searchSystem.mapView.loadMapScript({ openCallback: switchQuickView , shortName: $(this).data("shortname")});
        });
        
        $(".mod-search-results a").on("click", function () {
            $("#eviivo-search-destination").focus();
        });

        //TODO: clean this out
        //$modTile.hover(
        //  function () {
        //      window.eviivo.searchSystem.mapView.highlightMarker($(this).data("shortname"));
        //  }, function () {
        //      //window.eviivo.searchSystem.mapView.removeHighlightMarker($(this).data("shortname"));
        //  }
        //);
        
    }
    
    function switchQuickView(shortName) {
        if ($quickView.is(":visible")) {
            $quickView.css("visibility", "hidden");
        }
        window.eviivo.searchSystem.mapView.showLocationPopup(shortName);
    }
    //Accordion            
    $(".accordion-toggle").on("click", function () {
        var target = $(this).data("target");
        $("#" + target).slideToggle("slow");
        $(this).toggleClass("active");
    });

    return {
        init: init
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchSystem = window.eviivo.searchSystem ? window.eviivo.searchSystem : {};
window.eviivo.searchSystem.search = window.eviivo.searchSystem.search ? window.eviivo.searchSystem.search : {};

window.eviivo.searchSystem.search = function (jQuery) {
    var AJAX_REQUEST_ID = "search";

    var defaultOptions = {
        pageActionFormWrappers: null,
        ajaxUrl: null,
        browserBaseUrl: null,
        pushRequestToHistory: false,
        refreshDataCallback: null,
        contentPlaceholder: null,
        quickViewInitializerData: null, //Contains the object to initialize the quickview object
        isTopRooms: null,
        isCluster: null,
        resources: {
            results: "results",
            intext: "in",
            propertiesFound : ""
        }
    };
    var options;
    var viewType;
    var targetUrl;
    var targetTitle;
    var $contentPlaceholder;

    // <summary>Main init method of the eviivo.searchSystem.search object</summary>
    // <param name="customSettings">external custom settings</param>
    function init(customSettings) {
        //extend internal settings with external ones
        options = jQuery.extend(defaultOptions, customSettings);

        $contentPlaceholder = jQuery(options.contentPlaceHolder);

        eviivo.utils.ajaxHelper.init(AJAX_REQUEST_ID, options.ajaxLoaderResources, jQuery(".content"), ajaxCallComplete, function () { });
    }

    function validateSearch() {
        var dateValidationResult = eviivo.searchPlugin.dateRangeInput.validate();
        //returns the validation result for each value
        return dateValidationResult;
    };

    function getSerializedData() {
        var serializedData = "";
        serializedData = eviivo.searchPlugin.dateRangeInput.getStartAndEndDateQueryString();

        // in case availability calendar is present the sort wrapper is added to another wrapper that is already part of pageActionFormWrappers this will cause values to be added twice
        // so to avoid it we need to remove div.mod-sort from pageActionFormWrappers array
        var isAvailabilityCalendarPresent = jQuery("#availabilityBtn").length > 0
        var sortElementsWrapper = "div.mod-sort";
        var _pageActionFormWrappers = isAvailabilityCalendarPresent ?
            jQuery.grep(options.pageActionFormWrappers, function (value) {
                return value != sortElementsWrapper;
            }) :
            options.pageActionFormWrappers;

        jQuery.each(_pageActionFormWrappers, function (k, v) {
            //Due to different cultures we need to get the dates in a non standard way, therefore we need to exclude it from the serialize
            var wrapper = jQuery(v).find("input:not(#eviivo-search-start-date,#eviivo-search-end-date), textarea, select").filter(function (index, element) {
                return $(element).val() != "";
            });
            if (wrapper.length > 0) {
                serializedData += (serializedData != "" ? "&" : "") + wrapper.serialize();
            }
        });
        return serializedData;
    }

    function submitAction(e, validate, defaultToFirstPage) {
        if (options.pageActionFormWrappers == null && options.pageActionFormWrappers.length == 0) {
            console.log("No page action forms have been specified.");
            return true;
        }

        if (options.ajaxUrl == null) {
            console.log("No ajax call URL has been specified.");
            return true;
        }


        //If its supposed to perform a validation calls the method to validate. if it fails returns true as the default action (as opposed to trigger the search)
        if (validate && !validateSearch()) {
            return true;
        }

        //this action should force the user to go back to the first page of results
        if (defaultToFirstPage) {
            jQuery("#pageindex").val(1);
        }

        if (options.pushRequestToHistory) {
            targetTitle = jQuery(this).attr("title");
        }

        var serializedData = getSerializedData();
        
        if (serializedData != "") {

            var escapedSerializedData = encodeUrlParameter(serializedData);
            //amend the ajaxUrl with the query string params
            var url = options.ajaxUrl + "?" + escapedSerializedData;
            //if the browser base url is the same as the targetUrl 
            targetUrl = (options.browserBaseUrl ? options.browserBaseUrl : window.location.href.split("?")[0]) + "?" + escapedSerializedData;
            
            //set the location changed to false once submitted.
            window.eviivo.searchPlugin.autoComplete.setLocationChangeFlag('false');
            
            viewType = eviivo.searchSystem.views.getViewType();

            eviivo.smoothScrolling.scrollTilesTop('.mod-search-filters-outer', function () {
                //execute the ajax call (get method by default and json return type by default)
                eviivo.utils.ajaxHelper.executeAjax({
                    requestId: AJAX_REQUEST_ID,
                    url: url,
                    contentType: (viewType == 3 ? "json" : "html"),
                    dataType: (viewType == 3 ? "json" : "html")
                });
            });

        }
        return true;
    }

    function startSpinner() {
        $spinnerContainer.prepend("<div class='cp--loading'><span class='circle'></span><span class='cp--loading-text'>" + options.resources.loadingUpdateResults + "</span></div>");

        timer1 = setTimeout(function () {
            $spinnerContainer.find(".cp--loading").html("<span class='circle'></span><span class='cp--loading-text'>" + options.resources.loadingSlowSystemWarning + "</span>");
        }, 5000);

        timer2 = setTimeout(function () {
            $spinnerContainer.find(".cp--loading").html("<span class='circle'></span><span class='cp--loading-text'>" + "<span>" + options.resources.loadingUpdateResults + "</span>&nbsp;<span>" + options.resources.loadingRefreshingIssueWarning + "&nbsp;<a href='javascript:;' id='delayedRefreshPage'> " + options.resources.refreshPageText + "</a></span>");
        }, 20000);
    }

    // <summary></summary>
    function encodeUrlParameter(str) {
        var spaceExp = new RegExp("\\%20", "g");
        var commaExp = new RegExp("\\%2C", "g");
        var forwardSlashExp = new RegExp("\\%2F", "g");
        
        str = str.replace(commaExp, "--");        
        str = str.replace(spaceExp, "-");
        str = str.replace(forwardSlashExp, "-");
        return str;
    }

    function decodeUrlParameter(str) {
        var doubleHyphenExp = new RegExp("\--", "g");
        var hyphenExp = new RegExp("\-", "g");

        str = str.replace(doubleHyphenExp, ",");
        str = str.replace(hyphenExp, " ");
        return str;
    }

    function ajaxCallFailed(status, error) {
        clearTimeout(timer1);
        clearTimeout(timer2);

        $spinnerContainer.find(".cp--loading").html("<span class='circle'></span><span class='cp--loading-text'><span>" + options.resources.ajaxFailText + "&nbsp;<a href='javascript:;' id='delayedRefreshPage'>" + options.resources.refreshPageText + "</a></span></span>");
    }

    function ajaxCallComplete(responseData) {

        //replace radius in target URl after Ajax completed
        targetUrl = targetUrl.replace(/(radius=)[^\&]+/, '$1' + eviivo.searchSystem.filters.updateRadiusSlider(responseData));

        if (options.pushRequestToHistory) {
            if (window.history.pushState) {
                window.history.pushState({ url: "" + targetUrl + "" }, targetTitle, targetUrl);  
            }
        }


        viewType = eviivo.searchSystem.views.getViewType();

        jQuery(options.contentPlaceHolder).html("");
        jQuery(".mod-map-view-wrap").addClass("hidden");
        //Removes any existing SEO text that comes from the destination pages (this happens when the user lands on the destination page and then stars a search)
        jQuery(".cp-intro").remove();
        //Removes the existing breadcrumbs after a search.
        var $breadCrumbList = $("ol.breadcrumb");
        $breadCrumbList.find("li").each(function (index, object) {
            if (index > 0) {
                $(this).remove();
            }
        });
        
        eviivo.searchSystem.filters.updateFilterStatistics();
        
        switch (viewType) {
            //map view
            case 3:
                //update map markers only
                eviivo.searchSystem.largeMapView.loadMapScript(responseData.results);
                var destination = $("#destination").val();
                var numberOfResults = 0;
                if (responseData.results.length) {
                    numberOfResults = responseData.results.length;
                }

                eviivo.searchSystem.search.filterTranslations = responseData.filteredTranslations;

                //Adds the number of results to the breadcrumb list 
                jQuery("#results-holder").prepend("<h1 class=\"mod-search-results-count\">" + numberOfResults + " " + (!options.isTopRooms ? options.resources.propertiesFound : options.isCluster ? options.resources.propertiesFound : options.resources.results + " " + capitalizeFirstLetter(decodeUrlParameter(destination))) + "</h1>");
                
               
                eviivo.searchSystem.largeMapView.refreshMapOnResize();
                if (window.eviivo && eviivo.searchSystem && eviivo.searchSystem.inventoryCalendar) {
                    eviivo.searchSystem.inventoryCalendar.hideCalendarButton();
                }
                break;
                //list view
            case 1:
                //grid view
            case 2:
            default:
                //push entire pre-rendered HTML in the placeholder
                $contentPlaceholder.html(responseData);
                eviivo.searchSystem.paging.initializePageSizeDropDown();
                //eviivo.searchSystem.filters.updateFilterStatistics();
                eviivo.quickView.init(options.quickViewInitializerData);
                if (window.eviivo && eviivo.searchSystem && eviivo.searchSystem.inventoryCalendar) {
                    eviivo.searchSystem.inventoryCalendar.showCalendarButton();
                }
                picturefill();
                break;
        }
        eviivo.searchSystem.sorting.handlePriceSortState();
        eviivo.smoothScrolling.scrollToFilterButton();
        eviivo.searchSystem.views.initializeAccordion();

        $(".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);
                }
            },
            content: function () {
                return $(this).prop('title');
            }
        });

        if ($.trim($("#inventoryCalendarContainer").html()).length) {
            eviivo.searchSystem.inventoryCalendar.showInventoryCalendar();
        }
    }

    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        submitAction: submitAction,
        getSerializedData: getSerializedData
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchSystem = window.eviivo.searchSystem ? window.eviivo.searchSystem : {};
window.eviivo.searchSystem.filters = window.eviivo.searchSystem.filters ? window.eviivo.searchSystem.filters : {};

window.eviivo.searchSystem.filters = function (jQuery) {
    var defaultOptions = {
        submitHandler: null,
        mainContainer: null,
        defaultPriceMinValue: 20,
        defaultPriceMaxValue: 800,
        defaultRadiusValue: 15,
        userSettingsCookieName: null,
        radiusUnitCookieField: null
    };
    var options;

    //price filter variables
    var searchPriceRangeSlider,
        searchPriceLowVal,
        searchPriceHighVal,
        snapValueLower,
        snapValueUpper,
        clearAll,
        mainContainer,
        searchRadiusSlider,
        searchRadiusValue,
        $radiusUnitField,
        $searchRadiusUnitLabel,
        searchRadiusLabel,
        filterByPriceButton,
        defaultPriceMinValue,
        defaultPriceMaxValue,
        priceSliderSettings,
        showOnlyAvailableProperty,
        isPriceFilterSearch;

    var isSearchRadiusEnable = $("#searchRadius").length > 0;
    var isSearchPriceEnable = $("#searchPriceRange").length > 0;
    var isAccomodationTypeEnable = $("#property-type-show-more").length > 0;


    function init(customSettings) {
        //extend internal settings with external ones
        options = jQuery.extend(defaultOptions, customSettings);

        mainContainer = jQuery(options.mainContainer);


        var $slideAside = $(".filters-actions a");
        var $aside = $(".search .aside");
        var $showFilters = $(".show-filters a");

        $showFilters.on("click", function () {
            $aside.toggleClass("active");
            $(window).scrollTop($(".mod-filters-inner").offset().top);
        });

        jQuery(document).on("keydown", _escapeKeySortSelectorHandler);

        $slideAside.on("click", function () {
            if ($aside.hasClass("active")) {
                $aside.removeClass("active");
            }
        });

        _setup();
    }

    ///<summary></summary>
    function _setup() {

        if (isSearchPriceEnable) {
            _setupPriceFilter();
        }
        if (isSearchRadiusEnable) {
            _setupRadiusFilter();
        }

        clearAll = jQuery("#reset-all");
        clearAll.on("click", _clearAllHandler);

        mainContainer.find("input:not(#pricelow, #pricehigh)").on("click", _submitAction);

        toggleFilterStates();

        if (isAccomodationTypeEnable) {
            togglePropertyTypeList();
        }
    }

    ///<summary></summary>
    function _setupRadiusFilter() {
        //radius dropdown initialize
        var $radiusSelect = jQuery("#eviivo-select-radius-unit");
        $radiusSelect.selectmenu();
        $radiusSelect.on("selectmenuselect", _selectChangeHandler);
        $radiusUnitField = jQuery("#radiusunit");
        $searchRadiusUnitLabel = jQuery("#selected-radiusunit");
        jQuery(window).scroll(function () {
            var selectDropdown = jQuery("#eviivo-select-radius-unit-button").attr("aria-expanded");

            if (selectDropdown === "true") {
                $radiusSelect.selectmenu("close");
            }
        });

        setupNoUiSliderForRadiusFilter();

    }

    function setupNoUiSliderForRadiusFilter() {
        searchRadiusSlider = document.getElementById("searchRadius");
        searchRadiusValue = document.getElementById("radius");
        searchRadiusLabel = document.getElementById("selected-radius");

        var initialRadiusValue = searchRadiusValue.value.length === 0 ? options.defaultRadiusValue : searchRadiusValue.value;

        noUiSlider.create(searchRadiusSlider, {
            start: initialRadiusValue,              //  Slider starts at
            connect: "lower",       //  Slider bar fill in colour
            step: 1,                //  Number of steps
            behaviour: "tap",       //  A handle snaps to a clicked location. A smooth transition is used
            range: {                //  Range number 5 to 50
                'min': 1,
                'max': 40
            },
            pips: {
                mode: "values",
                values: [1, 5, 10, 15, 20, 30, 40],    //  range numbers displyed on the bar
                density: 20
            },
            format: {
                to: function (value) {
                    return Math.round(value);
                },
                from: function (value) {
                    return value;
                }
            }
        });

        searchRadiusSlider.noUiSlider.on("change", function (values, handle) {
            _submitAction(null);
        });

        searchRadiusSlider.noUiSlider.on("update", function (values, handle) {
            var value = values[handle];
            if (!handle) {
                searchRadiusValue.value = value;
                searchRadiusLabel.innerHTML = value;
            }
        });
    }

    //close filters on esc
    function _escapeKeySortSelectorHandler(e) {
        var $aside = $(".search .aside");
        if (e.which == 27 && $aside.hasClass("active")) {
            $aside.removeClass("active");
        }
    }

    ///<summary></summary>
    function _setupPriceFilter() {
        searchPriceRangeSlider = document.getElementById("searchPriceRange"),
            searchPriceLowVal = document.getElementById("searchPriceLowVal"),
            searchPriceHighVal = document.getElementById("searchPriceHighVal"),
            snapValueLower = document.getElementById("pricelow"),
            snapValueUpper = document.getElementById("pricehigh");
        //showOnlyAvailableProperty = document.getElementById("showavail");
        filterByPriceButton = jQuery(".slider-value-button");


        isPriceFilterSearch = false;

        var dynamicMinValue = document.getElementById("defaultLowerPrice");
        var dynamicMaxValue = document.getElementById("defaultHigherPrice");
        defaultPriceMinValue = !dynamicMinValue || dynamicMinValue.value.length === 0
            ? options.defaultPriceMinValue
            : Number(dynamicMinValue.value);

        defaultPriceMaxValue = !dynamicMaxValue || dynamicMaxValue.value.length === 0
            ? options.defaultPriceMaxValue
            : Math.round(Number(dynamicMaxValue.value));

        if (defaultPriceMinValue === defaultPriceMaxValue) {
            defaultPriceMaxValue++;
        }
        jQuery("#pricelow, #pricehigh").numeric({
            allowPlus: true,
            maxDigits: 8
        });


        var initialLowerValue = !snapValueLower || snapValueLower.value.length === 0
            ? defaultPriceMinValue
            : snapValueLower.value;

        var initialHigherValue = !snapValueUpper || snapValueUpper.value.length === 0
            ? defaultPriceMaxValue
            : Math.round(snapValueUpper.value);

        priceSliderSettings = {
            start: [initialLowerValue, initialHigherValue], // Handle start position
            step: 10, // Slider moves in increments of '10'
            margin: 20, // Handles must be more than '20' apart
            connect: true, // Display a colored bar between the handles
            behaviour: "tap-drag", // Move handle on tap, bar is draggable
            range: {
                // Slider can select '0' to '100'
                'min': defaultPriceMinValue,
                'max': defaultPriceMaxValue
            },
            format: {
                to: function (value) {
                    return Math.round(value);
                },
                from: function (value) {
                    return value;
                }
            }
        };


        noUiSlider.create(searchPriceRangeSlider, priceSliderSettings);

        filterByPriceButton.on("click", function () {
            _submitAction(null);
        });


        BindSliderEvents(initialLowerValue, initialHigherValue);
        snapValueUpper.addEventListener("change", _priceInputValueChangedHandler);
        snapValueLower.addEventListener("change", _priceInputValueChangedHandler);

    }

    function BindSliderEvents(initialLowerValue, initialHigherValue) {
        searchPriceRangeSlider.noUiSlider.on("update", function (values, handle) {
            _priceSliderUpdateValueHandler(snapValueLower, snapValueUpper, values[handle], handle);
            _priceSliderUpdateHandler(searchPriceLowVal, searchPriceHighVal, parseFloat(values[handle]), handle);
        });

        searchPriceRangeSlider.noUiSlider.on("change", function (values, handle) {
            showOnlyAvailableProperties();
            isPriceFilterSearch = true;
            _submitAction(null);
        });

        searchPriceLowVal.innerHTML = initialLowerValue;
        searchPriceHighVal.innerHTML = initialHigherValue;
    }

    ///<summary></summary>
    function _priceInputValueChangedHandler() {
        if (defaultPriceMinValue !== snapValueLower.value && defaultPriceMaxValue !== snapValueUpper.value) {
            showOnlyAvailableProperties();
        }
        searchPriceRangeSlider.noUiSlider.set([snapValueLower.value, snapValueUpper.value]);
    }

    function showOnlyAvailableProperties() {
        //jQuery(showOnlyAvailableProperty).attr("checked", "checked");
    }

    ///<summary></summary>
    function _priceSliderUpdateHandler(lowerObjValue, upperObjValue, value, handle) {
        if (!handle) {
            lowerObjValue.innerHTML = value;
        }
        else {
            upperObjValue.innerHTML = value;
        }
    }

    ///<summary></summary>
    function _priceSliderUpdateValueHandler(lowerObj, upperObj, value, handle) {
        if (!handle) {
            lowerObj.value = value;
        }
        else {
            upperObj.value = value;
        }
    }

    ///<summary></summary>
    function _clearAllHandler(e) {
        mainContainer.find("input").prop("checked", false);

        if (searchPriceRangeSlider) {
            searchPriceRangeSlider.noUiSlider.set([options.defaultPriceMinValue, options.defaultPriceMaxValue]);
        }

        if (searchRadiusSlider) {
            searchRadiusSlider.noUiSlider.set(options.defaultRadiusValue);
        }

        _submitAction(e);
    }

    ///<summary>Sort order select change handler</summary>
    function _selectChangeHandler(e, ui) {
        $radiusUnitField.val(ui.item.value);
        $searchRadiusUnitLabel.html($radiusUnitField.val());

        var currentCookieSession = window.eviivo.webcore.cookieManager.getCookie(options.userSettingsCookieName);
        var values = eviivo.utils.queryStringHelper.getAllKeys(currentCookieSession);
        values[options.radiusUnitCookieField] = $radiusUnitField.val();
        window.eviivo.webcore.cookieManager.setCookie(options.userSettingsCookieName, eviivo.utils.queryStringHelper.toString(values, false), 30);

        _submitAction(e);
    }

    ///<summary></summary>
    function _submitAction(e) {
        if (typeof (options.submitHandler) == "function") {
            //doesnt trigger validation, defaults to the first page
            options.submitHandler(e, false, true);
            return;
        }
        console.log("filters: action handler is missing");
    }

    function handlePriceFilterState() {
        var priceFilterOverlay = $("#price-filter-overlay");
        if (!priceFilterOverlay.length) {
            return;
        }
        if (eviivo.utils.queryStringHelper.isSearchMode()) {
            jQuery("#pricelow").removeAttr("disabled");
            jQuery("#pricehigh").removeAttr("disabled");
            //jQuery("#showavail").removeAttr("disabled");
            priceFilterOverlay.removeClass("overlay")
                .addClass("visualy-hidden");

        } else {
            jQuery("#pricelow").attr("disabled", "disabled");
            jQuery("#pricehigh").attr("disabled", "disabled");
            //jQuery("#showavail").attr("disabled", "disabled");
            priceFilterOverlay.removeClass("visualy-hidden")
                .addClass("overlay");

        }
    }

    function rebuildPriceSlider(defaultLowerBound, defaultHigherBound) {
        searchPriceRangeSlider = searchPriceRangeSlider || document.getElementById("searchPriceRange");
        // Get the new values from the button.
        var val = searchPriceRangeSlider.noUiSlider.get();

        searchPriceRangeSlider.noUiSlider.destroy();

        // Create a slider with the new options.
        priceSliderSettings.range.min = Number(defaultLowerBound);
        priceSliderSettings.range.max = Number(defaultHigherBound);
        priceSliderSettings.start = val;

        noUiSlider.create(searchPriceRangeSlider, priceSliderSettings);

        BindSliderEvents(val[0], val[1]);
    }

    function handlePriceFilterRange(filterData) {
        var defaultLowerPrice = Number(filterData.DefaultLowerPrice),
            defaultHigherPrice = Number(filterData.DefaultHigherPrice),
            selectedLowerPrice = Number(filterData.SelectedLowerPrice),
            selectedHigherPrice = Number(filterData.SelectedHigherPrice);
        searchPriceRangeSlider = searchPriceRangeSlider || document.getElementById("searchPriceRange");

        //handle default values 
        if (!isPriceFilterSearch && defaultLowerPrice != null && defaultHigherPrice != null
            && (defaultLowerPrice != priceSliderSettings.range.min || defaultHigherPrice != priceSliderSettings.range.max)) {
            if (defaultPriceMinValue === defaultPriceMaxValue) {
                defaultPriceMaxValue++;
            }
            rebuildPriceSlider(defaultLowerPrice, defaultHigherPrice);
        }

        //handle user Selected values
        var currentSelectedValues = searchPriceRangeSlider.noUiSlider.get();
        if (!isPriceFilterSearch && selectedLowerPrice != null && selectedHigherPrice != null
            && (selectedLowerPrice != currentSelectedValues[0] || selectedHigherPrice != currentSelectedValues[1])) {
            searchPriceRangeSlider.noUiSlider.set([selectedLowerPrice, selectedHigherPrice]);
        }


        isPriceFilterSearch = false;
    }

    function handleFilterItem($filterItems, code, itemCount, type) {
        var $checkbox = $filterItems.find("input[name=" + type + "][value =" + code + "]");
        if (itemCount == null || itemCount == 0) {
            $checkbox.attr("disabled", true);
        } else {
            $checkbox.removeAttr("disabled");
        }
        var count = itemCount || 0;
        $checkbox.siblings("label").find(".label-value-count").text("(" + count + ")");
        return count;
    }

    ///<summary>Main init method of the eviivo.searchSystem.filters object</summary>
    ///<param name="customSettings">external settings</param>
    var handleFilterStatistic = function (filter, type) {
        //for the review score we also need to count all the records and fill in the "All" option
        var countAllRecords = false;
        var totalCount = 0;
        if (type == "reviewscore") {
            countAllRecords = true;
        }
        var $filterItems = jQuery("#" + type + "-filter-placeholder");
        if (filter.length > 0) {
            $.each(filter, function (index, item) {
                var count = handleFilterItem($filterItems, item.Code, item.Count, type);
                if (countAllRecords) {
                    totalCount += count;
                }
            });
        }
        if (countAllRecords) {
            handleFilterItem($filterItems, "all", totalCount, "reviewscore");
        }

    };

    function updateSearchRadius(radius) {
        var sliderradius = document.getElementById("searchRadius");

        sliderradius.noUiSlider.set(radius);

    }

    function updateFilterStatistics() {

        //var filterDataHiddenField = jQuery("#serializedFilters").val();
        //var filterData = filterResponseData || filterDataHiddenField != undefined ? JSON.parse(filterDataHiddenField) : null;

        //Handle Price Filter Visibility
        //if (filterData != null) {
        //    //Handle Price Filter range and values
        //    //handlePriceFilterRange(filterData);

        //    //Handle Star rating filter 
        //    if (filterData.StarRatingFilter != null) {
        //        handleFilterStatistic(filterData.StarRatingFilter, "starrating");
        //    }

        //    //Handle ReviewFilter rating filter 
        //    if (filterData.ReviewFilter != null) {
        //        handleFilterStatistic(filterData.ReviewFilter, "reviewscore");
        //    }

        //    //Handle Facilities filter  
        //    if (filterData.FacilitiesFilter != null) {
        //        handleFilterStatistic(filterData.FacilitiesFilter, "facility");
        //    }




        //}
        //Handle Price Filter Visibility
        handlePriceFilterState();
    }

    function updateRadiusSlider(filterResponseData) {

        if (!isSearchRadiusEnable) {
            return 0;
        }

        var filterDataHiddenField = jQuery('<div>' + filterResponseData + '</div>').find("#serializedFilters").val();
        var filterData;

        if (filterDataHiddenField != undefined) {
            filterData = JSON.parse(filterDataHiddenField);

            if (filterData.SelectedRadius) {
                updateSearchRadius(filterData.SelectedRadius);
                return filterData.SelectedRadius;
            }

        } else {
            // used by map view
            updateSearchRadius(filterResponseData.radius);
            return filterResponseData.radius;
        }

        return 0;
    }

    ///<summary>Toggles active states for filters</summary>
    function toggleFilterStates() {
        $filterTitle = jQuery(".eviivo-search-column-parent a");
        $filterTitle.on("click", function () {
            jQuery(this).toggleClass("active");
            jQuery(this).siblings("ul").toggleClass("hidden");
        });
    }

    ///<summary>Toggles property type filters list</summary>
    function togglePropertyTypeList() {
        $propertyTypeShowMore = jQuery("#property-type-show-more");
        $propertyTypeListItems = jQuery(".hidden-property-type");
        $propertyTypeShowMore.on("click", function () {
            $propertyTypeListItems.show();
            $propertyTypeShowMore.hide();
        });
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        handlePriceFilterState: handlePriceFilterState,
        updateFilterStatistics: updateFilterStatistics,
        updateRadiusSlider: updateRadiusSlider
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchSystem = window.eviivo.searchSystem ? window.eviivo.searchSystem : {};
window.eviivo.searchSystem.sorting = window.eviivo.searchSystem.sorting ? window.eviivo.searchSystem.sorting : {};

window.eviivo.searchSystem.sorting = function (jQuery) {
    var defaultOptions = {
        submitHandler: null
    };
    var options;
    var sortSelector;
    var sortKey;
    var sortOrder;

    ///<summary>Main init method of the eviivo.searchSystem.sorting object</summary>
    ///<param name="settings">external settings</param>
    function init(customSettings) {
        //extend internal settings with external ones
        options = jQuery.extend(defaultOptions, customSettings);

        _setup();
    }

    function _setup() {
        sortKey = jQuery("#sortkey");
        sortOrder = jQuery("#sortorder");
        sortSelector = jQuery("#eviivo-search-sort");

        // workaround for us to able to use a placeholder text if there's no actual item selected
        $.widget('app.selectmenu', $.ui.selectmenu, {
            _drawButton: function () {
                this._super();

                var selected = this.element
                        .find('[selected]')
                        .length,
                    placeholder = this.element.data('placeholder');

                if (!selected && placeholder) {
                    this.buttonItem.text(placeholder);
                }
            }
        });
        
        //select element. Make text visible
        sortSelector.selectmenu(
            { width: 'auto' }
        );
        sortSelector.on("selectmenuselect", _selectChangeHandler);

        jQuery(document).on('keydown', _escapeKeySortSelectorHandler);
    }
    
    //close filters on esc
    function _escapeKeySortSelectorHandler(e) {
        var toggleCheckBox = jQuery("#toggleCheckBox");
        if (e.which == 27 && toggleCheckBox.hasClass("active")) {
            toggleCheckBox.removeClass("active");
            jQuery(".mod-filterOuter").hide();
        }
    }

    ///<summary>Sort order select change handler</summary>
    function _selectChangeHandler(e, ui) {
        var splitedSort = ui.item.value.split("-");
        sortKey.val(splitedSort[0]);
        sortOrder.val(splitedSort[1]);
        submitAction(e);
    }
    
    ///<summary></summary>
    function submitAction(e) {
        if (typeof (options.submitHandler) == "function") {
            //doesnt trigger validation, defaults to the first page
            options.submitHandler(e,false,true);
            return;
        }
        console.log("sorting: action handler is missing");
    }
    function handlePriceSortState() {


        sortSelector.selectmenu('refresh');

        // work-around to show placeholder after refresh because refresh itself, for some reason, doesn't call the 
        // above _drawButton (this will be deleted when price sort is not disabled)
        var selected = sortSelector.find('[selected]').length,
            placeholderText = sortSelector.data('placeholder');

        if (!selected && placeholderText && sortKey.val() === 'random') {
            sortSelector.parent().find('.ui-selectmenu-text').text(placeholderText);
        }
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        handlePriceSortState: handlePriceSortState
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchSystem = window.eviivo.searchSystem ? window.eviivo.searchSystem : {};
window.eviivo.searchSystem.paging = window.eviivo.searchSystem.paging ? window.eviivo.searchSystem.paging : {};

window.eviivo.searchSystem.paging = function (jQuery) {
    var defaultOptions = {
        mainContainer: ".mod-paginate",
        submitHandler: null,
        userSettingsCookieName: null,
        pageSizeCookieField: null
    };
    var options;
    var targetUrl;
    var targetTitle;
    var $pageSize;

    ///<summary>Main init method of the eviivo.searchSystem.paging object</summary>
    ///<param name="settings">external settings</param>
    function init(customSettings) {
        //extend internal settings with external ones
        options = jQuery.extend(defaultOptions, customSettings);
        initializePageSizeDropDown();
        _setup();
    }

    ///We need to expose a method to initialize the dropdown after an ajax request, as this cannot be attached to a jquery on event
    function initializePageSizeDropDown() {
        jQuery("#numberOfRecords-selector").selectmenu().on("selectmenuselect", _selectChangeHandler);
    }

    function _setup() {
        jQuery(document).on("click", options.mainContainer + " li a", navigateToPage);
    }

    ///<summary></summary>
    function navigateToPage(e) {
        e.preventDefault();

        targetUrl = jQuery(this).attr("href");
        targetTitle = jQuery(this).attr("title");
        var buttonPageNumber = jQuery(this).data('page');
        jQuery(options.mainContainer).find('#pageindex').val(buttonPageNumber);
        submitAction(e,false);
    }

    ///<summary></summary>
    function htmlLoadComplete(data) {
        if (window.history.pushState) {
            window.history.pushState({ url: "" + targetUrl + "" }, targetTitle, targetUrl);
        }

        var html = jQuery(data).find(options.contentPlaceHolder).html();
        $contentPlaceHolder.html(html).fadeTo("slow", 1);
    }

    ///<summary>Sort order select change handler</summary>
    function _selectChangeHandler(e, ui) {
        $pageSize = jQuery('#pagesize');
        $pageSize.val(ui.item.value);
        
        var currentCookieSession = window.eviivo.webcore.cookieManager.getCookie(options.userSettingsCookieName);
        var values = eviivo.utils.queryStringHelper.getAllKeys(currentCookieSession);
        values[options.pageSizeCookieField] = $pageSize.val();
        window.eviivo.webcore.cookieManager.setCookie(options.userSettingsCookieName, eviivo.utils.queryStringHelper.toString(values, false), 30);

        submitAction(e,true);
    }

    ///<summary></summary>
    function submitAction(e,defaultToFirstPage) {
        if (typeof (options.submitHandler) == "function") {
            options.submitHandler(e,false, defaultToFirstPage);
            return;
        }
        console.log("paging: action handler is missing");
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        initializePageSizeDropDown: initializePageSizeDropDown
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.tileGallery = window.eviivo.tileGallery ? window.eviivo.tileGallery : {};

window.eviivo.tileGallery = function ($) {

    var defaultOptions = {
        imgData: ".mod-tile-image img",
        nextButton: ".tile-image-next",
        previousButton: ".tile-image-prev"
    };

    var options;
    var imgData;
    var counter;
    var maxImages;

    function getImage(obj) {
        imgData = $(obj).siblings("img").data("items");
        $(obj).siblings("img").attr("src", imgData[counter].src);
    }

    function nextImageClick() {
        //due to ajax calls it needs to confirm the image data was initialized before performing any action
        initializeImageData();
        counter = (counter + 1) % imgData.length; // increment counter
        getImage($(this));
    }

    function previousImageClick() {
        //due to ajax calls it needs to confirm the image data was initialized before performing any action
        initializeImageData();
        counter = (counter + maxImages - 1) % imgData.length; // increment your counter
        getImage($(this));
    }

    function initializeImageData()
    {
        if (imgData == undefined) {
            imgData = $(options.imgData).data("items");
            counter = 0;
            maxImages = typeof imgData == "undefined" ? 0 : imgData.length;
        }
    }

    ///<summary>Main init method of the eviivo.tileGallery object</summary>
    ///<param name="settings">external settings</param>
    function init(settings) {
        //extend internal settings with external ones
        options = $.extend(defaultOptions, settings);
        initializeImageData();
        

        $(document).on("click", options.nextButton, nextImageClick);
        $(document).on("click", options.previousButton, previousImageClick);
    }

    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);
    }

    ///<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')
                            .promise()
                            .then(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>scroll to top tiles handler (large and small screens)</summary>
    function scrollTilesTop(bookmark, callback) {
        $(window).scrollTop($(bookmark).offset().top).promise()
            .then(callback);
    }

    ///<summary>Designed to scroll to the area where the filter button is(so that in small resolutions the user can see changes when he does a search)</summary>
    function scrollToFilterButton(callback) {
        var destinationDiv = $(".show-filters");
        if (destinationDiv != undefined && destinationDiv.is(":visible")) {
            if (destinationDiv.length > 0) {
                destinationDiv = destinationDiv.offset().top;
                var delta = $(document).height() - $(window).height();
                var dest = destinationDiv > delta ? delta : destinationDiv;
                $('html,body').animate({ scrollTop: dest }, 500, 'swing');
            }
        }
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        smoothScrollHandler: smoothScrollHandler,
        scrollTilesTop: scrollTilesTop,
        scrollToFilterButton: scrollToFilterButton
    };
}(jQuery);
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);
    }

    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);
        }

        $popupBox.css("display", "table");
    }

    function close(e) {
        if (e.which === 1 || e.keyCode === 27) {
            $popupContent.html("");
            $popupBox.css("display", "none");
            $popupHeaderTitle.text("");
        }
    }

    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        display: display
    };
}(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.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);
/********************************************************************
* Limit the characters that may be entered in a text field
* Common options: alphanumeric, alphabetic or numeric
* Kevin Sheedy, 2012
* http://github.com/KevinSheedy/jquery.alphanum
*********************************************************************/
(function( $ ){

  // API ///////////////////////////////////////////////////////////////////
  $.fn.alphanum = function(settings) {

    var combinedSettings = getCombinedSettingsAlphaNum(settings);

    var $collection = this;

    setupEventHandlers($collection, trimAlphaNum, combinedSettings);

    return this;
  };

  $.fn.alpha = function(settings) {

    var defaultAlphaSettings = getCombinedSettingsAlphaNum('alpha');
    var combinedSettings = getCombinedSettingsAlphaNum(settings, defaultAlphaSettings);

    var $collection = this;

    setupEventHandlers($collection, trimAlphaNum, combinedSettings);

    return this;
  };

  $.fn.numeric = function(settings) {

    var combinedSettings = getCombinedSettingsNum(settings);
    var $collection = this;

    setupEventHandlers($collection, trimNum, combinedSettings);

    $collection.blur(function(){
      numericField_Blur(this, combinedSettings);
    });

    return this;
  };

  // End of API /////////////////////////////////////////////////////////////


  // Start Settings ////////////////////////////////////////////////////////

  var DEFAULT_SETTINGS_ALPHANUM = {
    allow              : '',    // Allow extra characters
    disallow           : '',    // Disallow extra characters
    allowSpace         : true,  // Allow the space character
    allowNewline       : true,  // Allow the newline character \n ascii 10
    allowNumeric       : true,  // Allow digits 0-9
    allowUpper         : true,  // Allow upper case characters
    allowLower         : true,  // Allow lower case characters
    allowCaseless      : true,  // Allow characters that don't have both upper & lower variants - eg Arabic or Chinese
    allowLatin         : true,  // a-z A-Z
    allowOtherCharSets : true,  // eg é, Á, Arabic, Chinese etc
    forceUpper         : false, // Convert lower case characters to upper case
    forceLower         : false, // Convert upper case characters to lower case
    maxLength          : NaN    // eg Max Length
  };

  var DEFAULT_SETTINGS_NUM = {
    allowPlus           : false, // Allow the + sign
    allowMinus          : true,  // Allow the - sign
    allowThouSep        : true,  // Allow the thousands separator, default is the comma eg 12,000
    allowDecSep         : true,  // Allow the decimal separator, default is the fullstop eg 3.141
    allowLeadingSpaces  : false,
    maxDigits           : NaN,   // The max number of digits
    maxDecimalPlaces    : NaN,   // The max number of decimal places
    maxPreDecimalPlaces : NaN,   // The max number digits before the decimal point
    max                 : NaN,   // The max numeric value allowed
    min                 : NaN    // The min numeric value allowed
  };

  // Some pre-defined groups of settings for convenience
  var CONVENIENCE_SETTINGS_ALPHANUM = {
    'alpha' : {
      allowNumeric  : false
    },
    'upper' : {
      allowNumeric  : false,
      allowUpper    : true,
      allowLower    : false,
      allowCaseless : true
    },
    'lower' : {
      allowNumeric  : false,
      allowUpper    : false,
      allowLower    : true,
      allowCaseless : true
    }
  };

  // Some pre-defined groups of settings for convenience
  var CONVENIENCE_SETTINGS_NUMERIC = {
    'integer' : {
      allowPlus    : false,
      allowMinus   : true,
      allowThouSep : false,
      allowDecSep  : false
    },
    'positiveInteger' : {
      allowPlus    : false,
      allowMinus   : false,
      allowThouSep : false,
      allowDecSep  : false
    }
  };


  var BLACKLIST   = getBlacklistAscii() + getBlacklistNonAscii();
  var THOU_SEP    = ',';
  var DEC_SEP     = '.';
  var DIGITS      = getDigitsMap();
  var LATIN_CHARS = getLatinCharsSet();

  // Return the blacklisted special chars that are encodable using 7-bit ascii
  function getBlacklistAscii(){
    var blacklist = '!@#$%^&*()+=[]\\\';,/{}|":<>?~`.-_';
    blacklist += ' '; // 'Space' is on the blacklist but can be enabled using the 'allowSpace' config entry
    return blacklist;
  }

  // Return the blacklisted special chars that are NOT encodable using 7-bit ascii
  // We want this .js file to be encoded using 7-bit ascii so it can reach the widest possible audience
  // Higher order chars must be escaped eg "\xAC"
  // Not too worried about comments containing higher order characters for now (let's wait and see if it becomes a problem)
  function getBlacklistNonAscii(){
    var blacklist =
        '\xAC'     // ¬
      + '\u20AC'   // €
      + '\xA3'     // £
      + '\xA6'     // ¦
      ;
    return blacklist;
  }

  // End Settings ////////////////////////////////////////////////////////


  // Implementation details go here ////////////////////////////////////////////////////////

  function setupEventHandlers($textboxes, trimFunction, settings) {

    $textboxes.each(function(){

      var $textbox = $(this);

      $textbox
        // Unbind existing alphanum event handlers
        .off('.alphanum')

        .on('keyup.alphanum change.alphanum paste.alphanum', function(e){

          var pastedText = '';

          if(e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData)
            pastedText = e.originalEvent.clipboardData.getData('text/plain');

          // setTimeout is necessary for handling the 'paste' event
          setTimeout(function(){
            trimTextbox($textbox, trimFunction, settings, pastedText);
          }, 0);
        })

        .on('keypress.alphanum', function(e){

        // Determine which key is pressed.
        // If it's a control key, then allow the event's default action to occur eg backspace, tab
          var charCode = !e.charCode ? e.which : e.charCode;
          if(isControlKey(charCode)
          || e.ctrlKey
          || e.metaKey ) // cmd on MacOS
            return;

          var newChar         = String.fromCharCode(charCode);

          // Determine if some text was selected / highlighted when the key was pressed
          var selectionObject = $textbox.selection();
          var start = selectionObject.start;
          var end   = selectionObject.end;

          var textBeforeKeypress  = $textbox.val();

          // The new char may be inserted:
          //  1) At the start
          //  2) In the middle
          //  3) At the end
          //  4) User highlights some text and then presses a key which would replace the highlighted text
          //
          // Here we build the string that would result after the keypress.
          // If the resulting string is invalid, we cancel the event.
          // Unfortunately, it isn't enough to just check if the new char is valid because some chars
          // are position sensitive eg the decimal point '.'' or the minus sign '-'' are only valid in certain positions.
          var potentialTextAfterKeypress = textBeforeKeypress.substring(0, start) + newChar + textBeforeKeypress.substring(end);
          var validatedText              = trimFunction(potentialTextAfterKeypress, settings);

          // If the keypress would cause the textbox to contain invalid characters, then cancel the keypress event
          if(validatedText != potentialTextAfterKeypress)
            e.preventDefault();
        });
    });

  }

  // Ensure the text is a valid number when focus leaves the textbox
  // This catches the case where a user enters '-' or '.' without entering any digits
  function numericField_Blur(inputBox, settings) {
    var fieldValueNumeric = parseFloat($(inputBox).val());
    var $inputBox = $(inputBox);

    if(isNaN(fieldValueNumeric)) {
      $inputBox.val('');
      return;
    }

    if(isNumeric(settings.min) && fieldValueNumeric < settings.min)
      $inputBox.val('');

    if(isNumeric(settings.max) && fieldValueNumeric > settings.max)
      $inputBox.val('');
  }

  function isNumeric(value) {
    return !isNaN(value);
  }

  function isControlKey(charCode) {

    if(charCode >= 32)
      return false;
    if(charCode == 10)
      return false;
    if(charCode == 13)
      return false;

    return true;
  }

  // One way to prevent a character being entered is to cancel the keypress event.
  // However, this gets messy when you have to deal with things like copy paste which isn't a keypress.
  // Which event gets fired first, keypress or keyup? What about IE6 etc etc?
  // Instead, it's easier to allow the 'bad' character to be entered and then to delete it immediately after.

  function trimTextbox($textBox, trimFunction, settings, pastedText){

    var inputString = $textBox.val();

    if(inputString == '' && pastedText.length > 0)
      inputString = pastedText;

    var outputString = trimFunction(inputString, settings);

    if(inputString == outputString)
      return;

    var caretPos = $textBox.alphanum_caret();

    $textBox.val(outputString);

    //Reset the caret position
    if(inputString.length ==(outputString.length + 1))
      $textBox.alphanum_caret(caretPos - 1);
    else
      $textBox.alphanum_caret(caretPos);
  }

  function getCombinedSettingsAlphaNum(settings, defaultSettings){
    if(typeof defaultSettings == 'undefined')
      defaultSettings = DEFAULT_SETTINGS_ALPHANUM;
    var userSettings, combinedSettings = {};
    if(typeof settings === 'string')
      userSettings = CONVENIENCE_SETTINGS_ALPHANUM[settings];
    else if(typeof settings == 'undefined')
      userSettings = {};
    else
      userSettings = settings;

    $.extend(combinedSettings, defaultSettings, userSettings);

    if(typeof combinedSettings.blacklist == 'undefined')
      combinedSettings.blacklistSet = getBlacklistSet(combinedSettings.allow, combinedSettings.disallow);

    return combinedSettings;
  }

  function getCombinedSettingsNum(settings){
    var userSettings, combinedSettings = {};
    if(typeof settings === 'string')
      userSettings = CONVENIENCE_SETTINGS_NUMERIC[settings];
    else if(typeof settings == 'undefined')
      userSettings = {};
    else
      userSettings = settings;

    $.extend(combinedSettings, DEFAULT_SETTINGS_NUM, userSettings);

    return combinedSettings;
  }


  // This is the heart of the algorithm
  function alphanum_allowChar(validatedStringFragment, Char, settings){

    if(settings.maxLength && validatedStringFragment.length >= settings.maxLength)
      return false;

    if(settings.allow.indexOf(Char) >=0 )
      return true;

    if(settings.allowSpace && (Char == ' '))
      return true;

    if(!settings.allowNewline && (Char == '\n' || Char == '\r'))
      return false;

    if(settings.blacklistSet.contains(Char))
      return false;

    if(!settings.allowNumeric && DIGITS[Char])
      return false;

    if(!settings.allowUpper && isUpper(Char))
      return false;

    if(!settings.allowLower && isLower(Char))
      return false;

    if(!settings.allowCaseless && isCaseless(Char))
      return false;

    if(!settings.allowLatin && LATIN_CHARS.contains(Char))
      return false;

    if(!settings.allowOtherCharSets){
      if(DIGITS[Char] || LATIN_CHARS.contains(Char))
        return true;
      else
        return false;
    }

    return true;
  }

  function numeric_allowChar(validatedStringFragment, Char, settings){

    if(DIGITS[Char]) {

      if(isMaxDigitsReached(validatedStringFragment, settings))
        return false;

      if(isMaxPreDecimalsReached(validatedStringFragment, settings))
        return false;

      if(isMaxDecimalsReached(validatedStringFragment, settings))
        return false;

      if(isGreaterThanMax(validatedStringFragment + Char, settings))
        return false;

      if(isLessThanMin(validatedStringFragment + Char, settings))
        return false;

      return true;
    }

    if(settings.allowPlus && Char == '+' && validatedStringFragment == '')
      return true;

    if(settings.allowMinus && Char == '-' && validatedStringFragment == '')
      return true;

    if(Char == THOU_SEP && settings.allowThouSep && allowThouSep(validatedStringFragment))
      return true;

    if(Char == DEC_SEP) {
      // Only one decimal separator allowed
      if(validatedStringFragment.indexOf(DEC_SEP) >= 0)
        return false;
      // Don't allow decimal separator when maxDecimalPlaces is set to 0
      if(settings.allowDecSep && settings.maxDecimalPlaces === 0)
        return false;
      if(settings.allowDecSep)
        return true;
    }

    return false;
  }

  function countDigits(string) {

    // Error handling, nulls etc
    string = string + '';

    // Count the digits
    return string.replace(/[^0-9]/g,'').length;
  }

  function isMaxDigitsReached(string, settings) {

    var maxDigits = settings.maxDigits;

    if(maxDigits === '' || isNaN(maxDigits))
      return false; // In this case, there is no maximum

    var numDigits = countDigits(string);

    if(numDigits >= maxDigits)
      return true;

    return false;
  }

  function isMaxDecimalsReached(string, settings) {

    var maxDecimalPlaces = settings.maxDecimalPlaces;

    if(maxDecimalPlaces === '' || isNaN(maxDecimalPlaces))
      return false; // In this case, there is no maximum

    var indexOfDecimalPoint = string.indexOf(DEC_SEP);

    if(indexOfDecimalPoint == -1)
      return false;

    var decimalSubstring = string.substring(indexOfDecimalPoint);
    var numDecimals = countDigits(decimalSubstring);

    if(numDecimals >= maxDecimalPlaces)
      return true;

    return false;
  }

  function isMaxPreDecimalsReached(string, settings) {

    var maxPreDecimalPlaces = settings.maxPreDecimalPlaces;

    if(maxPreDecimalPlaces === '' || isNaN(maxPreDecimalPlaces))
      return false; // In this case, there is no maximum

    var indexOfDecimalPoint = string.indexOf(DEC_SEP);

    if(indexOfDecimalPoint >= 0)
      return false;

    var numPreDecimalDigits = countDigits(string);

    if(numPreDecimalDigits >= maxPreDecimalPlaces)
      return true;

    return false;
  }

  function isGreaterThanMax(numericString, settings) {

    if(!settings.max || settings.max < 0)
      return false;

    var outputNumber = parseFloat(numericString);
    if(outputNumber > settings.max)
      return true;

    return false;
  }

  function isLessThanMin(numericString, settings) {

    if(!settings.min || settings.min > 0)
      return false;

    var outputNumber = parseFloat(numericString);
    if(outputNumber < settings.min)
      return true;

    return false;
  }

  /********************************
   * Trims a string according to the settings provided
   ********************************/
  function trimAlphaNum(inputString, settings){

    if(typeof inputString != 'string')
      return inputString;

    var inChars = inputString.split('');
    var outChars = [];
    var i = 0;
    var Char;

    for(i=0; i<inChars.length; i++){
      Char = inChars[i];
      var validatedStringFragment = outChars.join('');
      if(alphanum_allowChar(validatedStringFragment, Char, settings))
        outChars.push(Char);
    }

    var outputString = outChars.join('');

    if(settings.forceLower)
      outputString = outputString.toLowerCase();
    else if(settings.forceUpper)
      outputString = outputString.toUpperCase();

    return outputString;
  }

  function trimNum(inputString, settings){
    if(typeof inputString != 'string')
      return inputString;

    var inChars = inputString.split('');
    var outChars = [];
    var i = 0;
    var Char;

    for(i=0; i<inChars.length; i++){
      Char = inChars[i];
      var validatedStringFragment = outChars.join('');
      if(numeric_allowChar(validatedStringFragment, Char, settings))
        outChars.push(Char);
    }

    return outChars.join('');
  }

  function isUpper(Char){
    var upper = Char.toUpperCase();
    var lower = Char.toLowerCase();

    if( (Char == upper) && (upper != lower))
      return true;
    else
      return false;
  }

  function isLower(Char){
    var upper = Char.toUpperCase();
    var lower = Char.toLowerCase();

    if( (Char == lower) && (upper != lower))
      return true;
    else
      return false;
  }

  function isCaseless(Char){
    if(Char.toUpperCase() == Char.toLowerCase())
      return true;
    else
      return false;
  }

  function getBlacklistSet(allow, disallow){

    var setOfBadChars  = new Set(BLACKLIST + disallow);
    var setOfGoodChars = new Set(allow);

    var blacklistSet   = setOfBadChars.subtract(setOfGoodChars);

    return blacklistSet;
  }

  function getDigitsMap(){
    var array = '0123456789'.split('');
    var map = {};
    var i = 0;
    var digit;

    for(i=0; i<array.length; i++){
      digit = array[i];
      map[digit] = true;
    }

    return map;
  }

  function getLatinCharsSet(){
    var lower = 'abcdefghijklmnopqrstuvwxyz';
    var upper = lower.toUpperCase();
    var azAZ = new Set(lower + upper);

    return azAZ;
  }

  function allowThouSep(currentString) {

    // Can't start with a THOU_SEP
    if(currentString.length == 0)
      return false;

    // Can't have a THOU_SEP anywhere after a DEC_SEP
    var posOfDecSep = currentString.indexOf(DEC_SEP);
    if(posOfDecSep >= 0)
      return false;

    var posOfFirstThouSep       = currentString.indexOf(THOU_SEP);

    // Check if this is the first occurrence of a THOU_SEP
    if(posOfFirstThouSep < 0)
      return true;

    var posOfLastThouSep        = currentString.lastIndexOf(THOU_SEP);
    var charsSinceLastThouSep   = currentString.length - posOfLastThouSep - 1;

    // Check if there has been 3 digits since the last THOU_SEP
    if(charsSinceLastThouSep < 3)
      return false;

    var digitsSinceFirstThouSep = countDigits(currentString.substring(posOfFirstThouSep));

    // Check if there has been a multiple of 3 digits since the first THOU_SEP
    if((digitsSinceFirstThouSep % 3) > 0)
      return false;

    return true;
  }

  ////////////////////////////////////////////////////////////////////////////////////
  // Implementation of a Set
  ////////////////////////////////////////////////////////////////////////////////////
  function Set(elems){
    if(typeof elems == 'string')
      this.map = stringToMap(elems);
    else
      this.map = {};
  }

  Set.prototype.add = function(set){

    var newSet = this.clone();

    for(var key in set.map)
      newSet.map[key] = true;

    return newSet;
  };

  Set.prototype.subtract = function(set){

    var newSet = this.clone();

    for(var key in set.map)
      delete newSet.map[key];

    return newSet;
  };

  Set.prototype.contains = function(key){
    if(this.map[key])
      return true;
    else
      return false;
  };

  Set.prototype.clone = function(){
    var newSet = new Set();

    for(var key in this.map)
      newSet.map[key] = true;

    return newSet;
  };
  ////////////////////////////////////////////////////////////////////////////////////

  function stringToMap(string){
    var map = {};
    var array = string.split('');
    var i=0;
    var Char;

    for(i=0; i<array.length; i++){
      Char = array[i];
      map[Char] = true;
    }

    return map;
  }

  // Backdoor for testing
  $.fn.alphanum.backdoorAlphaNum = function(inputString, settings){
    var combinedSettings = getCombinedSettingsAlphaNum(settings);

    return trimAlphaNum(inputString, combinedSettings);
  };

  $.fn.alphanum.backdoorNumeric = function(inputString, settings){
    var combinedSettings = getCombinedSettingsNum(settings);

    return trimNum(inputString, combinedSettings);
  };

  $.fn.alphanum.setNumericSeparators = function(settings) {

    if(settings.thousandsSeparator.length != 1)
      return;

    if(settings.decimalSeparator.length != 1)
      return;

    THOU_SEP = settings.thousandsSeparator;
    DEC_SEP = settings.decimalSeparator;
  };

})( jQuery );

/*eslint-disable */
//Include the 3rd party lib: jquery.caret.js


// Set caret position easily in jQuery
// Written by and Copyright of Luke Morton, 2011
// Licensed under MIT
(function ($) {
  // Behind the scenes method deals with browser
  // idiosyncrasies and such
  function caretTo(el, index) {
    if (el.createTextRange) {
      var range = el.createTextRange();
      range.move("character", index);
      range.select();
    } else if (el.selectionStart != null) {
      el.focus();
      el.setSelectionRange(index, index);
    }
  };

  // Another behind the scenes that collects the
  // current caret position for an element

  // TODO: Get working with Opera
  function caretPos(el) {
    if ("selection" in document) {
      var range = el.createTextRange();
      try {
        range.setEndPoint("EndToStart", document.selection.createRange());
      } catch (e) {
        // Catch IE failure here, return 0 like
        // other browsers
        return 0;
      }
      return range.text.length;
    } else if (el.selectionStart != null) {
      return el.selectionStart;
    }
  };

  // The following methods are queued under fx for more
  // flexibility when combining with $.fn.delay() and
  // jQuery effects.

  // Set caret to a particular index
  $.fn.alphanum_caret = function (index, offset) {
    if (typeof(index) === "undefined") {
      return caretPos(this.get(0));
    }

    return this.queue(function (next) {
      if (isNaN(index)) {
        var i = $(this).val().indexOf(index);

        if (offset === true) {
          i += index.length;
        } else if (typeof(offset) !== "undefined") {
          i += offset;
        }

        caretTo(this, i);
      } else {
        caretTo(this, index);
      }

      next();
    });
  };
}(jQuery));

/**********************************************************
* Selection Library
* Used to determine what text is highlighted in the textbox before a key is pressed.
* http://donejs.com/docs.html#!jQuery.fn.selection
* https://github.com/jupiterjs/jquerymx/blob/master/dom/selection/selection.js
***********************************************************/
(function(e){var t=function(e){return e.replace(/([a-z])([a-z]+)/gi,function(e,t,n){return t+n.toLowerCase()}).replace(/_/g,"")},n=function(e){return e.replace(/^([a-z]+)_TO_([a-z]+)/i,function(e,t,n){return n+"_TO_"+t})},r=function(e){return e?e.ownerDocument.defaultView||e.ownerDocument.parentWindow:window},i=function(t,n){var r=e.Range.current(t).clone(),i=e.Range(t).select(t);if(!r.overlaps(i)){return null}if(r.compare("START_TO_START",i)<1){startPos=0;r.move("START_TO_START",i)}else{fromElementToCurrent=i.clone();fromElementToCurrent.move("END_TO_START",r);startPos=fromElementToCurrent.toString().length}if(r.compare("END_TO_END",i)>=0){endPos=i.toString().length}else{endPos=startPos+r.toString().length}return{start:startPos,end:endPos}},s=function(t){var n=r(t);if(t.selectionStart!==undefined){if(document.activeElement&&document.activeElement!=t&&t.selectionStart==t.selectionEnd&&t.selectionStart==0){return{start:t.value.length,end:t.value.length}}return{start:t.selectionStart,end:t.selectionEnd}}else if(n.getSelection){return i(t,n)}else{try{if(t.nodeName.toLowerCase()=="input"){var s=r(t).document.selection.createRange(),o=t.createTextRange();o.setEndPoint("EndToStart",s);var u=o.text.length;return{start:u,end:u+s.text.length}}else{var a=i(t,n);if(!a){return a}var f=e.Range.current().clone(),l=f.clone().collapse().range,c=f.clone().collapse(false).range;l.moveStart("character",-1);c.moveStart("character",-1);if(a.startPos!=0&&l.text==""){a.startPos+=2}if(a.endPos!=0&&c.text==""){a.endPos+=2}return a}}catch(h){return{start:t.value.length,end:t.value.length}}}},o=function(e,t,n){var i=r(e);if(e.setSelectionRange){if(n===undefined){e.focus();e.setSelectionRange(t,t)}else{e.select();e.selectionStart=t;e.selectionEnd=n}}else if(e.createTextRange){var s=e.createTextRange();s.moveStart("character",t);n=n||t;s.moveEnd("character",n-e.value.length);s.select()}else if(i.getSelection){var o=i.document,u=i.getSelection(),f=o.createRange(),l=[t,n!==undefined?n:t];a([e],l);f.setStart(l[0].el,l[0].count);f.setEnd(l[1].el,l[1].count);u.removeAllRanges();u.addRange(f)}else if(i.document.body.createTextRange){var f=document.body.createTextRange();f.moveToElementText(e);f.collapse();f.moveStart("character",t);f.moveEnd("character",n!==undefined?n:t);f.select()}},u=function(e,t,n,r){if(typeof n[0]==="number"&&n[0]<t){n[0]={el:r,count:n[0]-e}}if(typeof n[1]==="number"&&n[1]<=t){n[1]={el:r,count:n[1]-e};}},a=function(e,t,n){var r,i;n=n||0;for(var s=0;e[s];s++){r=e[s];if(r.nodeType===3||r.nodeType===4){i=n;n+=r.nodeValue.length;u(i,n,t,r)}else if(r.nodeType!==8){n=a(r.childNodes,t,n)}}return n};jQuery.fn.selection=function(e,t){if(e!==undefined){return this.each(function(){o(this,e,t)})}else{return s(this[0])}};e.fn.selection.getCharElement=a})(jQuery);
/*eslint-enable */

window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchSystem = window.eviivo.searchSystem ? window.eviivo.searchSystem : {};
window.eviivo.searchSystem.views = window.eviivo.searchSystem.views ? window.eviivo.searchSystem.views : {};

window.eviivo.searchSystem.views = function (jQuery) {
    var defaultOptions = {
        submitHandler: null,
        userSettingsCookieName: null,
        viewTypeCookieField: null
    };
    var options;
    var viewType;

    ///<summary>Main init method of the eviivo.searchSystem.views object</summary>
    ///<param name="customSettings">external custom settings</param>
    function init(customSettings) {
        //extend internal settings with external ones
        options = jQuery.extend(defaultOptions, customSettings);

        jQuery("div.mod-viewToggle").on("click", _switchViewHandler);

        //Gets the default viewtype (this value is computed on the server side, so it either contains the user cookie value or the the default view type)
        viewType = jQuery("#viewType").val();

        fadeInPromoBanner();
    }

    function fadeInPromoBanner() {
        setTimeout(function () {
            $(".promo-banner.slide").fadeIn('800');
            startPromoBannerAnimation();
        }, 1000);
    }

    function startPromoBannerAnimation() {
        setTimeout(function () {
            $(".promo-banner.slide").addClass('start');
        }, 1000);

    }

    function _switchViewHandler(e) {
        viewType = parseInt(jQuery(e.target).data("view-type"));
        jQuery("div.mod-viewToggle button").removeClass("active");
        jQuery(e.target).addClass("active");

        var currentCookieSession = window.eviivo.webcore.cookieManager.getCookie(options.userSettingsCookieName);
        var values = eviivo.utils.queryStringHelper.getAllKeys(currentCookieSession);
        values[options.viewTypeCookieField] = viewType;
        window.eviivo.webcore.cookieManager.setCookie(options.userSettingsCookieName, eviivo.utils.queryStringHelper.toString(values, false), 30);

        jQuery("#viewType").val(viewType);

        if (viewType == 3) {
            //on map hide the sort and paging
            jQuery(".mod-sort").css("display", "none");
        }
        else {
            jQuery(".mod-sort").css("display", "block");
        }
        _submitAction(e);
    }

    function getViewType() {
        return parseInt(viewType);
    }

    ///<summary></summary>
    function _submitAction(e) {
        if (typeof (options.submitHandler) == "function") {
            options.submitHandler(e);
            return;
        }
        console.log("views: action handler is missing");
    }

    //Accordion     
    function initializeAccordion() {
        jQuery(".accordion a.accordion-toggle").on("click", function () {
            jQuery(this).siblings(".accordion-content").slideToggle("slow");
            jQuery(this).parent().toggleClass("active");

        });
    }
    ///<summary>Expose the internal "private" methods for external use (make them public)</summary>
    return {
        init: init,
        getViewType: getViewType,
        initializeAccordion: initializeAccordion
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchPlugin = window.eviivo.searchPlugin ? window.eviivo.searchPlugin : {};
window.eviivo.searchPlugin.autoComplete = window.eviivo.searchPlugin.autoComplete ? window.eviivo.searchPlugin.autoComplete : {};

window.eviivo.searchPlugin.autoComplete = function (jQuery) {
    var defaultOptions = {
        submitHandler: null,
        mainContainer: null, //"#eviivo-partner-search-box",
        autoCompleteUrl: null,
        culture: null,
        baseSearchUrl: "",
        pointOfSaleShortName: '@(Model.PageSettings != null ?Model.PageSettings.PointOfSaleShortName : string.Empty)',
        clusterType: '@ApplicationConstants.SearchParametersTypes.CLUSTER',
        postCodeType: '@ApplicationConstants.SearchParametersTypes.POSTCODE',
        propertyNameType: '@ApplicationConstants.SearchParametersTypes.PROPERTY_NAME',
        tagType: '@ApplicationConstants.SearchParametersTypes.TAG',
        geoNameType: '@ApplicationConstants.SearchParametersTypes.GEO_NAME',
        countryType: '@ApplicationConstants.SearchParametersTypes.COUNTRY',
        regionType: '@ApplicationConstants.SearchParametersTypes.REGION',
        cityType: '@ApplicationConstants.SearchParametersTypes.CITY',
        separatorType: '@ApplicationConstants.SearchParametersTypes.SEPARATOR',
        resources: {
            searchFormTagIntroText: "@Common.SearchFormTagIntroText",
            searchFormTagText: "@Common.SearchFormTagText"
        },
        channelName: ""
    };

    var options,
        $searchParameterInputField,
        $destinationAndTagsList,
        $searchForm,
        $tooltip,
        numberOfSearchParameters,
        destination,
        destinationType,
        clusterName,
        latitude,
        longitude,
        locationChanged,
        queryString,
        $locationSelectionToolTip;

    ///<summary>Main init method of the eviivo.searchPlugin.occupancySelector object</summary>
    ///<param name="customSettings">external custom settings</param>
    function init(customSettings) {
        options = jQuery.extend(defaultOptions, customSettings);
        queryString = eviivo.utils.queryStringHelper.getAllKeys(window.location.href);

        $searchForm = jQuery(options.mainContainer);

        //hidden fields initialization
        destination = $searchForm.find("#destination");
        destinationType = $searchForm.find("#destinationtype");
        clusterName = $searchForm.find("#clustername");
        latitude = $searchForm.find("#latitude");
        longitude = $searchForm.find("#longitude");
        locationChanged = $('#lc');

        $tooltip = $searchForm.find("div.cp-tooltip");
        $destinationAndTagsList = $searchForm.find("#eviivo-search-destination-tags");
        $searchParameterInputField = $searchForm.find("#eviivo-search-destination");

        numberOfSearchParameters = parseInt($destinationAndTagsList.data("numberofparameters"));

        $searchParameterInputField.on("focus", clearDestinationTooltipValidation)
                                            .keypress(preventAddRoomsOnEnter);

        $destinationAndTagsList.find('a.cp-tag').each(function () {
            $(this).on("click", handleSearchParametersCloseEvent);
        });

        setupAutoComplete();
    }

    function clearDestinationTooltipValidation() {
        var $parent = $searchParameterInputField.parent();
        $parent.removeClass("focus").removeClass("invalid");
        //Also hides the calendar tooltip(useful for mobile views)
        eviivo.searchPlugin.dateRangeInput.clearDatePickerTooltip();
        return $parent;
    }

    function setLocationChangeFlag(change) {
        locationChanged.val(change);
    }

    ///<summary>Populate AutoComplete</summary>
    function setupAutoComplete() {
        // Custom autocomplete instance.
        jQuery.widget("app.autocomplete", jQuery.ui.autocomplete, {
            _create: function () {
                this._super();
                this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)");
            },
            // Which class get's applied to matched text in the menu items.
            options: {
                highlightClass: "ui-state-highlight"
            },
            _renderMenu: autocompleteRenderMenuHandler,
            _renderItem: autocompleteRenderItemHandler
        });

        // On focus out get first item from autocomplete box
        jQuery(document).ready(function () {
            $searchParameterInputField.autocomplete({
                minLength: 1,
                change: true,
                search: autocompleteTriggerHandler,
                source: autocompleteSource,
                select: autocompleteSelectHandler,
                open: autocompleteOpenHandler
            });
            $searchParameterInputField.on('focusout', function () {
                var keyEvent = $.Event("keydown");
                keyEvent.keyCode = $.ui.keyCode.ENTER;
                $(this).trigger(keyEvent);
                // Stop event propagation if needed
                return false;
            });
        });
    }

    //generates the category for the autocomplete (top suggestions)
    function autocompleteRenderMenuHandler(ul, items) {
        var that = this;
        var li;
        $.each(items, function (index, item) {
            if (item.type == options.separatorType) {
                ul.append("<li class='ui-autocomplete-category'>" + item.name + "</li>");
            } else {
                li = that._renderItemData(ul, item);
                li.attr("aria-label", item.type + " : " + item.name);
            }
        });
    }

    function autocompleteRenderItemHandler(ul, item) {
        //If it is a separator type makes the object disabled so it can't be selected
        var $li;
        var label;

        // Replace the matched text with a custom span. This
        // span uses the class found in the "highlightClass" option.
        var re = new RegExp("(" + this.term + ")", "gi"),
            cls = this.options.highlightClass,
            template = "<span class='" + cls + "'>$1</span>";
        label = item.name.replace(re, template);
        $li = jQuery("<li class='ui-menu-item-" + item.type + "' />").appendTo(ul);
        $li.html(label);
        return $li;
    }

    function autocompleteOpenHandler(e, ui) {
        var menu = $(this).data('app-autocomplete').menu;
        var $items = $('li', menu.element);

        if (Modernizr.touch) {
            //Added to support ipad selection. There is a issue with jquery ui and ios(http://bugs.jqueryui.com/ticket/10544)
            //hovers the first element that starts with a value
            $('.ui-autocomplete').off('menufocus hover mouseover');
            //If none starts with the value selects the first element
            if ($items.length >= 1) {
                //add focus to the first element of the list
                menu.focus(null, $items.eq(0));
            }
        } else {
            //If none starts with the value selects the first element
            if ($items.length >= 1) {
                //add focus to the first element of the list
                menu.focus(null, $items.eq(0));
            }
        }

        $(this).parent().removeClass("ui-autocomplete-parent-loading");

    }

    function preventAddRoomsOnEnter(event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == 13) {
            event.preventDefault();
        }
    }


    function autocompleteTriggerHandler() {
        $(this).parent().addClass("ui-autocomplete-parent-loading");
    }

    function autocompleteSelectHandler(e, ui) {
        addSearchParameter(ui.item);
        return false;
    }

    function autocompleteSource(request, response) {

        jQuery.ajax({
            url: options.autoCompleteUrl,
            dataType: "jsonp",
            data: {
                q: request.term,
                pointOfSaleShortName: options.pointOfSaleShortName,
                culture: options.culture,
                onlySearchByPropertyNames: CheckIfIsToSearchOnlyByPropertyNames(),
                onlySearchByLocation: CheckIfIsToSearchOnlyByLocation(),
                channelName: options.channelName,
                searchByChannelName: true
            },
            success: function (data) {
                response($.map(data.results, function (obj) {
                    return {
                        name: obj.name,
                        coord: obj.geoLocation,
                        type: obj.type,
                        id: obj.id,
                        urlName: obj.urlName
                    };
                }));

                trackAutoCompleteTypingEvent(request.term, data.total);
            },
            error: function (jqXhr, textStatus, errorThrown) {
                console.log(textStatus);
                console.log(errorThrown);
            },
            failure: function () {
                console.log("ajax request failed to return data");
            }
        });
    }

    function CheckIfIsToSearchOnlyByPropertyNames() {
        if ($("#search-type").val() == "PRP") {
            return true;
        }

        return false;
    }

    function CheckIfIsToSearchOnlyByLocation() {
        if ($("#search-type").val() == "GGL") {
            return true;
        }

        return false;
        
    }

    //google tracking for autocomplete typing
    function trackAutoCompleteTypingEvent(term, responseTotal) {
        if (typeof ga != "undefined") {
            ga("send", "event", "AutoComplete", "Typed", term, responseTotal);
            if (typeof ga.getByName == "function") {
                var propertyTracker = ga.getByName('propertyTracker');
                if (typeof propertyTracker != "undefined") {
                    ga("propertyTracker.send", "event", "AutoComplete", "Typed", term, responseTotal);
                }
            }
        }
    }

    //google tracking for autocomplete select
    function trackAutoCompleteSelectEvent(term, type) {
        if (typeof ga != "undefined") {
            ga("send", "event", "AutoComplete", "Select", "term: " + term + "  - type: " + type);
            if (typeof ga.getByName == "function") {
                var propertyTracker = ga.getByName('propertyTracker');
                if (typeof propertyTracker != "undefined") {
                    ga("propertyTracker.send", "event", "AutoComplete", "Select", "term: " + term + "  - type: " + type);
                }
            }
        }
    }

    function addSearchParameter(item) {
        var value = item.name;
        var type = item.type;
        var id = item.id;
        var isTagType = type == options.tagType;
        var isPropertyType = type == options.propertyNameType;

        var isGeoNameType = type == options.countryType
            || type == options.regionType
            || type == options.cityType;

        var isLocationType = isGeoNameType
            || type == options.clusterType
            || type == options.postCodeType
            || isPropertyType;

        var classType = isGeoNameType ? defaultOptions.geoNameType : type;

        //Tracks the event in google
        trackAutoCompleteSelectEvent(value, type);
        //Check if input field is not empty and if it's do not add value
        if (value.length) {
            var $element = jQuery('<a></a>');
            $element.on("click", handleSearchParametersCloseEvent);
            $element.addClass("cp-tag cp-tag-" + classType)
                .attr("title", value)
                .attr("href", "javascript:;")
                .attr('data-type', type)
                .html('<span class="ct-tag-text">' + value + '</span></a>'
                    //only adds the input field for tags (so it can appear in the form serialization)
                    + (isTagType ? '<input type="hidden" name="tag" value="' + value + '"/>' : ''));

            if (isLocationType) {
                var $currentGeoNameItem = $destinationAndTagsList.find(
                    "a[data-type='" + options.countryType + "'],"
                    + "a[data-type='" + options.regionType + "'],"
                    + "a[data-type='" + options.cityType + "'],"
                    + "a[data-type='" + options.clusterType + "'],"
                    + "a[data-type='" + options.postCodeType + "'],"
                    + "a[data-type='" + options.propertyNameType + "']");

                //if it finds an object of type location. removes it
                if ($currentGeoNameItem.length > 0) {
                    $currentGeoNameItem.remove();
                }
                
                //If it is a property name search promotes the property 
                $('#psn').val(isPropertyType ? id : '');


                //adds the location to the first position of the list.
                $destinationAndTagsList.prepend($element);

                //sets the new search information in the hidden fields that will used during the postback
                setLocationParameters(item.coord.latitude, item.coord.longitude, item.type, value, item.urlName);
            } else {
                //adds the new element to the autocomplete
                $destinationAndTagsList.append($element);
            }

            //clears the autocomplete input field
            $searchParameterInputField.val('');

            $searchParameterInputField.focus();

            //updates the number into data
            $destinationAndTagsList.data("numberofparameters", numberOfSearchParameters++);
        }
    }

    function handleSearchParametersCloseEvent() {
        //checks if it is a location type, to mark the data accordingly
        var $parameterFormData = $(this).attr('data-type');

        var isGeoNameType = $parameterFormData == options.countryType
            || $parameterFormData == options.regionType
            || $parameterFormData == options.cityType;

        if ($parameterFormData.length && (isGeoNameType || $parameterFormData == options.clusterType)) {
            $destinationAndTagsList.data("haslocation", "false");
            setLocationParameters('', '', '', '', '');
        }

        //removes the object from the DOM
        $(this).remove();
        //decreases the number of parameters and
        //updates the number into data
        $destinationAndTagsList.data("numberofparameters", numberOfSearchParameters--);
    }

    ///<summary>Used to populate hidden fields after auto completer returns</summary>
    function setLocationParameters(lat, lng, type, locationDescription, urlName) {
        destination.val(urlName);
        destinationType.val(type);
        locationChanged.val('true');

        if (type != options.clusterType) {
            latitude.val(lat);
            longitude.val(lng);
            clusterName.val('');
        } else {
            latitude.val('');
            longitude.val('');
            clusterName.val(escapeUrlDestinationClusterString(locationDescription, false));
        }
    }

    ///<summary></summary>
    function escapeUrlDestinationClusterString(str, invert) {
        var spaceExp = new RegExp("\ ", "g");
        var commaExp = new RegExp("\,", "g");
        var doubleHyphenExp = new RegExp("\--", "g");
        var hyphenExp = new RegExp("\-", "g");

        if (invert != null && !invert) {
            str = str.replace(commaExp, '--');
            str = str.replace(spaceExp, "-");
        } else {
            str = str.replace(doubleHyphenExp, ',');
            str = str.replace(hyphenExp, ' ');
        }
        return str;
    }

    return {
        init: init,
        setLocationChangeFlag: setLocationChangeFlag
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchPlugin = window.eviivo.searchPlugin ? window.eviivo.searchPlugin : {};
window.eviivo.searchPlugin.dateRangeInput = window.eviivo.searchPlugin.dateRangeInput ? window.eviivo.searchPlugin.dateRangeInput : {};

window.eviivo.searchPlugin.dateRangeInput = function (jQuery) {
    var defaultOptions = {
        submitHandler: null,
        mainContainer: null, //"#eviivo-partner-search-box",
        cultureLanguageCode: null,
        resources:
        {
            checkinDate: "@Common.SelectCheckInDate",
            checkoutDate: "@Common.SelectCheckOutDate",
            selected: "@Common.Selected",
            nights: "@Common.Nights",
            close: "@Common.Close"
        }
    };

    var options,
        $searchForm,
        $startDate,
        $endDate,
        $nightsLabel,
        currentDate,
        queryString,
        $datePickerSelectionToolTip;

    ///<summary>extend Date javascript object and add extra function "addHours"</summary>
    Date.prototype.addHours = function (hours) {
        this.setHours(this.getHours() + hours);
        return this;
    };

    ///<summary>Get the difference of two dates in days</summary>
    Date.prototype.diffDays = function (b) {
        if (b == undefined || b.constructor !== Date) {
            throw "invalid_date";
        }

        var t1 = this.getTime();
        var t2 = b.getTime();

        return parseInt((t1 - t2) / (24 * 3600 * 1000));
    };

    ///<summary>Main init method of the eviivo.searchPlugin.dateRangeInput object</summary>
    ///<param name="customSettings">external custom settings</param>
    function init(customSettings) {
        options = jQuery.extend(defaultOptions, customSettings);
        queryString = eviivo.utils.queryStringHelper.getAllKeys(window.location.href);

        $searchForm = jQuery(options.mainContainer);
        $startDate = $searchForm.find("input#eviivo-search-start-date");
        $endDate = $searchForm.find("input#eviivo-search-end-date");
        $nightsLabel = $searchForm.find("#eviivo-search-nights");

        //init datepicker (set culture and min date - not in the past)
        currentDate = new Date();
        var dtFormat = eviivo.webcore.formatting.datetime.evGetDateDisplayFormat(options.cultureLanguageCode, "medium");

        //setup culture and get users current culture
        var culture = "en-gb";
        if (options.selectedCultureLanguageCode != null) {
            culture = options.selectedCultureLanguageCode;
        }

        //Date has been extended via eviivo.webcore.formatting.js, this function takes the current users culture as a parameter and then determines what first day of the week should be, returning it as an offset used with date pickers
        var d = new Date();
        var firstDayOffset = d.evStandardFirstDayCalendarOffset(culture);

        $.datepicker.setDefaults(
            $.extend(
            {
                'dateFormat': dtFormat,
                'altFormat': dtFormat,
                'showOtherMonths': true,
                'selectOtherMonths': true,
                'minDate': currentDate,
                'firstDay': firstDayOffset
            }
            )
        );
        //init start datepicker with culture specifics, min date as current date and onSelect custom handler
        $startDate.datepicker({
            onSelect: startDateSelectHandler
        });
        $startDate.on("focus", clearDatePickerTooltip);
        //init end datepicker with culture specifics, min date as current date and onSelect custom handler
        $endDate.datepicker({
            onSelect: validate
        });
        $endDate.on("focus", clearDatePickerTooltip);

        $datePickerSelectionToolTip = $('#datepicker-tooltip');

        setMinimumEndDate();

        setNights();

        //Initialize the validation on load. This will show the tooltip if the user doesnt have dates selected
        validate(true);

        $datePickerSelectionToolTip.on("click", clearDatePickerTooltip);

    }

    function setMinimumEndDate() {
        var startDate = $startDate.datepicker("getDate");
        if (startDate != null) {
            var minimumEndDate = new Date(startDate).addHours(24);
            $endDate.datepicker("option", { "minDate": minimumEndDate });
        }
    }

    function clearDatePickerTooltip() {
        $startDate.removeClass("invalid");
        $endDate.removeClass("invalid");
        $datePickerSelectionToolTip.removeClass("infotip");
        $datePickerSelectionToolTip.hide();
    }

    ///<summary>Performs a validation on all the fields necessary to make the autocomplete / location result valid</summary>
    function validate(isOnLoadValidation) {
        //for OnloadValidation we dont display the invalid object just the infotip
        clearDatePickerTooltip();

        // if both dates fields are empty
        if ($startDate.val() === "" && $endDate.val() === "") {
            if (isOnLoadValidation) {
                $datePickerSelectionToolTip.addClass("infotip");
            } else {
                $startDate.addClass("invalid");
                $endDate.addClass("invalid");
            }
            $datePickerSelectionToolTip.show();
            return false;
        }
        // if start date field is empty
        if ($startDate.val() === "") {
            if (isOnLoadValidation) {
                $datePickerSelectionToolTip.addClass("infotip");
            } else {
                $startDate.addClass("invalid");
            }
            $datePickerSelectionToolTip.show();
            return false;
        }
        // if end date field is empty
        if ($endDate.val() === "") {
            if (isOnLoadValidation) {
                $datePickerSelectionToolTip.addClass("infotip");
            } else {
                $endDate.addClass("invalid");
            }
            $datePickerSelectionToolTip.show();
            return false;
        }
        clearDatePickerTooltip();
        return true;
    }

    ///<summary>Datepicker select handler for start date</summary>
    function startDateSelectHandler(date, instance) {
        //grab selected date and add one extra 24 hours
        var startDate = new Date(instance.selectedYear, instance.selectedMonth, parseInt(instance.selectedDay), 0, 0, 0, 0).addHours(24);
        //set that computed date as being the minDate for the endDate calendar
        $endDate.datepicker("option", { "minDate": startDate });

        //auto show the end date calendar (delay of 100ms because of jquery show effects on datepicker)
        setTimeout(function () {
            $endDate.datepicker("show");
        }, 100);

        setNights();
    }

    ///<summary>Set number of selected nights depending on the dates being selected</summary>
    function setNights() {
        var startDateValue = $startDate.datepicker("getDate");
        var endDateValue = $endDate.datepicker("getDate");

        if (startDateValue == null && endDateValue == null) {
            $nightsLabel.html("<span class='cp-link'>" + options.resources.checkinDate + "</span><a class='cp-close' href='javascript:;' title='" + options.resources.close + "'>" + options.resources.close + "</a>");
        } else if (startDateValue != null && endDateValue == null) {
            $nightsLabel.html("<span class='cp-link'>" + options.resources.checkoutDate + "</span><a class='cp-close' href='javascript:;' title='" + options.resources.close + "'>" + options.resources.close + "</a>");
        } else {
            $nightsLabel.html("<span>" + options.resources.selected + " " + endDateValue.diffDays(startDateValue) + " " + options.resources.nights + "</span> <a class='cp-close' href='javascript:;' title='" + options.resources.close + "'>" + options.resources.close + "</a>");
        }
    }

    function getStartAndEndDateQueryString() {
        var returnQueryString = "";
        var startDateValue = $startDate.datepicker("getDate");
        var stringStartDate;
        if (startDateValue) {
            stringStartDate = $startDate.datepicker("getDate").evStandardIso8601DateExtended();
            if (stringStartDate != null) {
                returnQueryString += "startdate=" + stringStartDate;
            }
            
        }
        var endDateValue = $endDate.datepicker("getDate");
        var stringEndDate;
        if (endDateValue) {
            stringEndDate = $endDate.datepicker("getDate").evStandardIso8601DateExtended();    
            returnQueryString += "&enddate=" + stringEndDate;
        }
        return returnQueryString;
    }

    return {
        init: init,
        validate: validate,
        clearDatePickerTooltip: clearDatePickerTooltip,
        getStartAndEndDateQueryString: getStartAndEndDateQueryString
};
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchPlugin = window.eviivo.searchPlugin ? window.eviivo.searchPlugin : {};
window.eviivo.searchPlugin.occupancySelector = window.eviivo.searchPlugin.occupancySelector ? window.eviivo.searchPlugin.occupancySelector : {};

window.eviivo.searchPlugin.occupancySelector = function (jQuery) {

    var defaultOptions = {
        submitHandler: null,
        mainContainer: null, //"#eviivo-partner-search-box",
        roomsLimit: 3, //default room limit is 3 if not overriden by external settings
        resources: {
            adults: "@Common.Adults",
            children: "@Common.Children",
            rooms: "@Common.Rooms",
            room: "@Common.Room",
            roomsAdded: "@Common.RoomsAdded",
            roomAdded: "Common.RoomAdded"
        }
    };
    var options;
    var $searchForm;
    var cloneOccupancyHtml;
    var roomsRow;
    var occupancyMenus = {};
    var $tooltip;
    var $searchButton;
    var $addButton;
    var $removeButton;
    var $firstAdultsOccupancy;
    var $occupancyDiv;
    var queryString;


    ///<summary>Main init method of the eviivo.searchPlugin.occupancySelector object</summary>
    ///<param name="customSettings">external custom settings</param>
    function init(customSettings) {
        options = jQuery.extend(defaultOptions, customSettings);
        queryString = eviivo.utils.queryStringHelper.getAllKeys(window.location.href);

        $searchForm = jQuery(options.mainContainer);
        $occupancyDiv = $searchForm.find(".cp-tooltipOuter");
        //html cloning for multiroom search
        roomsRow = options.mainContainer + " div.column-inner";
        cloneOccupancyHtml = $searchForm.find("div.column-outer").html();
        jQuery(roomsRow).remove();

        $searchButton = $searchForm.find("#eviivo-search-button");
        $tooltip = $searchForm.find("div.cp-tooltip");

        occupancySelectHandler();
        //end html cloning for multiroom search
        $addButton = $searchForm.find("#btn-addRoom");
        $removeButton = $searchForm.find("#btn-removeRoom");
        $firstAdultsOccupancy = $searchForm.find("div.column-inner:first-child span.column-adult span.ui-selectmenu-button");
        //attach click handler for add room button
        $addButton.on("click", addRoomSelection);
        //attach click handler for remove room button
        $removeButton.on("click", removeRoomSelection);

        //attach click handler for showing the occupancy tooltip
        $searchForm.find(".icon-guest").on("click", tooltipShow);
        $searchForm.find(".icon-guest a").on("click", tooltipShow);

        //initialize the first row of occupancy selectors in the occupancy tooltip
        initSelectMenu($searchForm.find("div.column-inner:first-child select.cp-select"));

        //handle the click outside the occupancy tooltip (close the tooltip and focus on the search price button)
        jQuery(document).on("click", tooltipOutsideClick);

        $searchForm.find("#toggleCheckBox").on("click touch", toggleFilters);

        $searchForm.find("#cp-occupancySearchButton").on("click", function(e) {
            tooltipHide(e, true);
            _selectChangeHandler(e);
        });
        $searchButton.on("click", _selectChangeHandler);

        initDefaultOccupancy();

        //hide occupancy tooltip if we press esc
        $(document).on("keyup", tooltipHideEscape);
    }

    ///<summary>Sort order select change handler</summary>
    function _selectChangeHandler(e) {
        //the true variable in the optional parameters of the submitAction is meant to trigger validation
        //, defaults to the first page
        submitAction(e, true, true);
    }

    ///<summary></summary>
    function submitAction(e, triggerValidation, defaultToFirstPage) {
        if (typeof (options.submitHandler) == "function") {
            options.submitHandler(e, triggerValidation, defaultToFirstPage);
            return;
        }
        console.log("sorting: action handler is missing");
    }

    ///<summary>Toggle filters</summary>
    function toggleFilters() {
        if (jQuery(window).width() < 1024) {
            $searchForm.find("#toggleCheckBox").toggleClass("active");
            $searchForm.find(".mod-filterOuter").slideToggle();
        }
    }

    ///<summary>Initialize the default occupancy</summary>
    function initDefaultOccupancy() {
        var hasOccupancy = false;
        //pass through all query string keys and construct the occupancy selectors
        jQuery.each(queryString, function (key, value) {
            //check for existance of adults and/or children params
            var isAdults = key.indexOf("adults") >= 0;
            var isChildren = key.indexOf("children") >= 0;
            if (isAdults || isChildren) {
                hasOccupancy = true;
                //check to see if occupancy criteria already exists for this param
                if ($searchForm.find("input[name='" + key + "']").length == 0) {
                    addRoomSelection(null, key, value[0]);
                }
                setRoomOccupancySelector(key, value[0]);
            }
        });

        //in case we do not have occupancy specified in querystring
        if (hasOccupancy == false) {
            var numberOfRooms = jQuery(roomsRow).length;
            if (numberOfRooms === 0) {
                addRoomSelection(null, "adults", 2);
                setRoomOccupancySelector("adults", 2);
            }
        }
    }

    ///<summary>Initialize occupancy selectors in the occupancy tooltip</summary>
    ///<param name="selector">the dropdown jquery selector</param>
    function initSelectMenu() {
        var element = $searchForm.find("div.column-inner:last-child");
        var index = element.index() + 1;
        var menu = element.find("select.cp-select").selectmenu({ change: occupancySelectHandler });
        occupancyMenus["adults" + index] = menu[0];
        occupancyMenus["children" + index] = menu[1];
    }

    ///<summary></summary>
    function setRoomOccupancySelector(key, value) {
        if (occupancyMenus[key] != null) {
            var menu = jQuery(occupancyMenus[key]);
            menu.val(value);
            menu.selectmenu("refresh");
            occupancySelectHandler();
        }
    }

    ///<summary>Occupancy selector onChange handler</summary>
    function occupancySelectHandler() {
        var totalAdults = 0;
        var totalChildren = 0;
        $searchForm.find("div.column-inner").each(function (i, e) {
            jQuery(e).find("span.column-adult .ui-selectmenu-text").each(function (ii, ee) {
                totalAdults += setOccupancyField("adults", i, ee);
            });

            jQuery(e).find("span.column-child .ui-selectmenu-text").each(function (ii, ee) {
                totalChildren += setOccupancyField("children", i, ee);
            });
        });

        var numberOfRooms = jQuery(roomsRow).length;
        var searchBoxText = $searchForm.find(".cp-inputValues a span");
        var roomText = "";
        if (numberOfRooms > 1) {
            roomText = options.resources.rooms;
        } else {
            roomText = options.resources.room;
        }
        searchBoxText.html(totalAdults + " " + options.resources.adults + " " + totalChildren + " " + options.resources.children + " " + numberOfRooms + " " + roomText);
    }

    ///<summary>Extract the occupancy value from selector and create the hidden input for form submission</summary>
    function setOccupancyField(keyPart, index, text) {
        var key = keyPart + (index + 1);
        var value = extractNumber(jQuery(text));

        var hidden = $searchForm.find("input[name='" + key + "']");
        if (hidden.length == 0) {
            setHiddenInput(key, value);
        } else {
            hidden.val(value);
        }
        return value;
    }

    ///<summary>Give each room added a number</summary>
    function numberRoomTitle() {
        var count = 1;
        $(".column-outer .column-inner").each(function () {
            var countTitle = options.resources.room + " " + count;
            $(this).find(".room").html(countTitle);

            count++;
        });
    }

    //<summary>Change number of rooms selected in helper text</summary>
    function numberRoomHelper() {
        var roomTotal = $(".column-outer .column-inner").length;
        var roomRow = $(".room-counter");
        var resource;
        if (roomTotal > 1) {
            resource = options.resources.roomsAdded;
        } else {
            resource = options.resources.roomAdded;
        }
        var roomHtml = resource.replace(new RegExp('\\{' + 0 + '\\}', 'gm'), roomTotal);
        roomRow.html(roomHtml);
        roomRow.addClass('pulse');

        var newRow = roomRow.clone(true);
        roomRow.before(newRow);
        $(".room-counter:last").remove();
    }

    ///<summary>Add room onClick handler</summary>
    function addRoomSelection(e) {
        if (e != null) {
            e.preventDefault();
            e.stopPropagation();
        }

        var numberOfRooms = jQuery(roomsRow).length;
        if (numberOfRooms < options.roomsLimit) {
            $searchForm.find("div.column-outer").append(cloneOccupancyHtml).addClass("cloned");
            initSelectMenu();
            occupancySelectHandler();
            numberRoomTitle();
            numberRoomHelper();
        }
        setTooltipButtonsStatus();
    }

    ///<summary>Remove room onClick handler</summary>
    function removeRoomSelection(e) {
        if (e != null) {
            e.preventDefault();
            e.stopPropagation();
        }

        var numberOfRooms = jQuery(roomsRow).length;
        if (numberOfRooms > 1) {
            var item = $searchForm.find("div.column-inner:last");
            var index = item.index() + 1;
            $searchForm.find("input[name='adults" + index + "'],input[name='children" + index + "']").remove();
            occupancyMenus["adults" + index] = null;
            occupancyMenus["children" + index] = null;
            item.remove();
            occupancySelectHandler();
            numberRoomHelper();
        }
        setTooltipButtonsStatus();
    }

    ///<summary>Set the disabled status of the add and remove room buttons in the occupancy tooltip</summary>
    function setTooltipButtonsStatus() {
        var numberOfRooms = jQuery(roomsRow).length;
        if (numberOfRooms > 1) {
            $removeButton.removeAttr("disabled");
        } else {
            $removeButton.attr("disabled", "disabled");
            //once disabled the "remove button" we focus on the "add button" for better interaction
            $addButton.focus();
        }
        if (numberOfRooms < options.roomsLimit) {
            $addButton.removeAttr("disabled");
        } else {
            $addButton.attr("disabled", "disabled");
            //once disabled the "add button" we focus on the "remove button" for better interaction
            $removeButton.focus();
        }
        $occupancyDiv.find("div.column-outer").removeClass("overflow");
        if (numberOfRooms > 2) {
            $occupancyDiv.find("div.column-outer").addClass("overflow");
        }
        //when clicking on + and - and assuming you're on small screen let scroll to top of the form, to improve user experience and not hide search/close button
        if (jQuery(window).width() < 768) {
            $(window).scrollTop($('.mod-search-filters-outer').offset().top);
        }

    }

    ///<summary>Hide tooltip when clicking outside the tooltip area</summary>
    function tooltipOutsideClick(e) {
        if (!$(e.target).hasClass("ui-menu-item-wrapper") && !$(e.target).hasClass("ui-menu-item") && !$(e.target).hasClass("cp-tooltip") && $(e.target).parents("div.cp-tooltip").length === 0) {
            tooltipHide(e, true);
        }
    }

    ///<summary>Hide tooltip handler on escape key</summary>
    function tooltipHideEscape(e) {
        if (e.keyCode === 27) {
            tooltipHide(e, true);
        }
    }

    ///<summary>Hide tooltip handler</summary>
    function tooltipHide(e, bypassFocus) {
        if ($tooltip.is(":visible")) {
            $tooltip.hide();

            //we check if we bypass focus for search button
            if (!bypassFocus) {
                $searchButton.focus();
            }
        }
    }

    ///<summary>Show tooltip handler</summary>
    function tooltipShow(e) {
        if (e != null) {
            e.stopPropagation();
        }
        if (($tooltip).is(":hidden")) {
            $tooltip.show('fast');
            //when showing tooltip we focus on first select input element
            $firstAdultsOccupancy.focus();
        }
    }

    ///<summary>helper function to extract number from occupancy selector text (adult or child)</summary>
    function extractNumber(selector) {
        return parseInt(selector.text().slice(0, 2).trim());
    }

    ///<summary>Set the value for a hidden input</summary>
    function setHiddenInput(key, value) {
        var element = jQuery(document.createElement('input'));
        element.attr("type", "hidden")
            .attr("name", key)
            .val(value);
        $searchForm.append(element);
    }

    return {
        init: init
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.searchPlugin = window.eviivo.searchPlugin ? window.eviivo.searchPlugin : {};
window.eviivo.searchPlugin.tags = window.eviivo.searchPlugin.tags ? window.eviivo.searchPlugin.tags : {};

window.eviivo.searchPlugin.tags = function (jQuery) {

    var defaultOptions = {
        mainContainer: null //"#eviivo-partner-search-box",
    };
    var options;
    var $selectedTags = $(".s-selected-tags");
    var $totalTagsCount = $(".s-tags-count");
    var $clearTagSelection = $(".s-icon-clear");
    var $tagPlaceholder = $(".s-tag-placeholder");
    var $selectedTagsText = $(".s-selected-tags-text");
    var $tagInput = $(".selectable-tag-list input[type='checkbox']");
    var $tagListItem = $(".selectable-tag-list li");
    var $searchTypeDropdown = $("#search-type");
    var $tagContainer = $(".eviivo-search-tag");
    var $locationContainer = $(".s-location-input");
    var $hiddenFieldSearchType = $("#searchtype");
    var $hiddenSelectedTags = $("#selectedtags");
    var selectedTags = [];

    ///<param name="customSettings">external custom settings</param>
    function init(customSettings) {
        options = jQuery.extend(defaultOptions, customSettings);

        searchTypeSelection();
        tagsSelection();
        tagsCount();  
        

        // Clear tags 
        $clearTagSelection.on("click", function () {
            $tagInput.prop('checked', false);
            uncheckSelectAll();
            $clearTagSelection.addClass("hide");
            tagsCount();
            removeActiveState();
        });


        // Checkbox tag change
        $tagInput.on("change",function () {

            // Uncheck "select all", if one of the listed checkbox item is unchecked
            if (false === $(this).prop("checked")) { 
                uncheckSelectAll();
            }
            // Check "select all" if all checkbox items are checked
            if ($tagInput.is(":checked").length === $tagInput.length) {
                $("#selectAll").prop('checked', true);
            }

            var itemValue = $(this).data("searchtagid");

            // Add grey bg to list if checked
            if ($(this).is(':checked')) {
                $(this).closest("li").addClass("selected");

                selectedTags.push(itemValue);
            }
            else {
                $(this).closest("li").removeClass("selected");

                var index = selectedTags.indexOf(itemValue);
                
                if (index > -1) {
                    selectedTags.splice(index, 1);
                }
            }
            tagsSelection();
            tagsCount();

            UpdateHiddenSelectTags();

            UpdateCheckAllStatus();
        });
         
        // Select all 
        $("#selectAll").on("click", function () {
            $tagInput.prop('checked', this.checked);
            tagsCount();
            
            if ($(this).is(":checked")) {
                addActiveState();
                $clearTagSelection.removeClass("hide");
                selectedTags = [];

                $(".selectable-tag-list input[type='checkbox']:checked")
                    .each(function() {
                        selectedTags.push($(this).data("searchtagid"));
                    });
            } else {
                selectedTags = [];
                removeActiveState();
                $clearTagSelection.addClass("hide");

            }

            UpdateHiddenSelectTags();
        });

        // Tag input 
        $selectedTags.on("click", function () {
            $(this).parent().toggleClass("active");
        });

        // On ESC hide dropdown
        $(document).on("keydown", hideDropdown);

        // Search type change
        $searchTypeDropdown.on("change", searchTypeSelection);

    }

    function UpdateHiddenSelectTags() {
        $hiddenSelectedTags.val((selectedTags.join(',')));
    }

    function uncheckSelectAll() {
        $("#selectAll").prop('checked', false);

        UpdateHiddenSelectTags();
    }

    function checkSelectAll() {
        $("#selectAll").prop('checked', true);
    }

    function UpdateCheckAllStatus(){
        var $checkedTag = $(".selectable-tag-list input[type='checkbox']:checked").length;
        var $availableTag = $(".selectable-tag-list input[type='checkbox']").length;

        if ($checkedTag == $availableTag) {
            checkSelectAll();
        }
    }

    function hideTagInput() {
        $tagContainer.hide();
    }

    function showTagInput() {
        $tagContainer.show();
    }

    function hideLocationInput() {
        $locationContainer.hide();
    }
    function showLocationInput() {
        $locationContainer.show();
    }

    function tagsCount() {
        var $checkedTag = $(".selectable-tag-list input[type='checkbox']:checked").length;

        if ($checkedTag > 0) {
            var selectwording = $totalTagsCount.data("selectwording");
            selectwording = selectwording.replace('{0}', $checkedTag);

            $totalTagsCount.text(selectwording);
            $tagPlaceholder.addClass("hide");
            $selectedTagsText.removeClass("hide");
        } else {
            $totalTagsCount.text('0');
            $tagPlaceholder.removeClass("hide");
            $selectedTagsText.addClass("hide");
        }
    }

    function removeActiveState() {
        $tagListItem.removeClass("selected");

    }

    function addActiveState() {
        $tagListItem.addClass("selected");
    }


    function hideDropdown(e) {
        if (e.keyCode === 27) {
            $(".eviivo-search-tag").removeClass("active");
            $clearTagSelection.addClass("hide");
        }
    }


    function tagsSelection() {

        if ($(".selectable-tag-list input[type='checkbox']:checked").length > 0) {
            $clearTagSelection.removeClass("hide");
        }
        else {
            $clearTagSelection.addClass("hide");
        }

    }

    function searchTypeSelection() {
        var searchValue = $searchTypeDropdown.val();

        $("#eviivo-search-destination").attr("placeholder", $searchTypeDropdown.find(':selected').data('placeholdertext'))

        $hiddenFieldSearchType.val(searchValue);

        if (searchValue === "GGL" || searchValue === "PRP") {
            hideTagInput();
            showLocationInput();
            ResetSelection(true);
        }
        else if (searchValue === "TAG") {
            ResetSelection(false);
            showTagInput();
            hideLocationInput();
        }
    }

    function ResetSelection(removeTagSelection) {
        if (removeTagSelection) {
            $("#eviivo-search-destination-tags").find(':first').remove();
            $(".selectable-tag-list input[type='checkbox']").prop("checked", false);
            uncheckSelectAll();
        }

        UpdateCheckAllStatus();
        UpdateHiddenSelectTags();
        tagsCount();
    }

    $(document).mouseup(function (e) {
        
        // if the target of the click isn't the container nor a descendant of the container
        if (!$tagContainer.is(e.target) && $tagContainer.has(e.target).length === 0) {
            $(".eviivo-search-tag").removeClass("active");
            $clearTagSelection.addClass("hide");
        }
    });

    return {
        init: init
    };
}(jQuery);
window.eviivo = window.eviivo ? window.eviivo : {};
window.eviivo.quickView = window.eviivo.quickView ? window.eviivo.quickView : {};

window.eviivo.quickView = function ($) {
    var defaultOptions = {
        requestUrl: '/search/GetPropertyAvailability',
        searchCriteria: '#serializedSearchCriteria',
        contentPlaceHolder: "#quickViewPlaceHolder",
        bookButtonsSelector: 'button.cp-button-book',
        radioButtonsSelector: '.radio-buttons',
        readMore: "Read more",
        readLess: "Read less",
        previousButtonSelector: '.cp-arrow-l',
        nextButtonSelector: '.cp-arrow-r',
        tabsSelector: ".mod-tabs a",
        toggleTrigger: ".toggle-trigger",
        loadingText: "Loading property information please wait.",
        seeRemaining: "See remaining",
        remainingImages: "images",
        isQuickBookEnabled: "false",
        enterDateLink: 'button.cp-button-text',
        viewDesc: "View Description",
        viewMap: "View Map"
    };
    //TODO: refactor several instances if the same initialization used
    var $contentPlaceHolder;
    var options;
    var propertiesShortName;
    var $quickViewCta;
    var $ajaxRequest = null;
    var $viewportWidth;
    var $startDate;

    function init(settings) {

        options = $.extend(defaultOptions, settings);

        $quickViewCta = $(".mod-tile-image, .mod-tile-content, .mod-tile-title a");
        $viewPage = $(".cp-button-viewProperty");
        $searchContentWrapper = $(".content-wrapper");
        $modTile = $(".mod-tile");
        $contentPlaceHolder = $(options.contentPlaceHolder);
        $viewportWidth = $(window).width();
        $startDate = $("#eviivo-search-start-date");

        var mapLocations = $('#results-map-locations').val();

        if (mapLocations != null && mapLocations != "") {
            var mapLocationsArray = JSON.parse(mapLocations);

            propertiesShortName = $.map(mapLocationsArray, function (element) { return element.ShortName; });

            loadQuickBook(options);

            window.addEventListener("resize", loadQuickBookSetup);

            $viewPage.on("click", function () {
                trackPropertyViewViewEvent();
            });


            $(document).on("keyup",function (e) {
                if (e.keyCode == 27) {
                    if ($(".mod-quickView").is(":visible")) {
                        closeQuickView();
                    }
                }
            });
        }
    }

    function loadQuickBookSetup() {
        var queue = eviivo.util.debounce({ func: loadQuickBook, params: options, unique: "loadQuickBook" });
    }

    ///<summary>Load quickbook if it's enabled and toggle between required urls</summary>
    function loadQuickBook(options) {
        //if more than a tablet, make grid view expandable
        if ($(window).width() > 768 && options.isQuickBookEnabled == "True") {
            $quickViewCta.on("click", function () {
                getPageContent(null, $(this));
                trackQuickViewShowEvent();
            });
            // toggle src with tada src
            $modTile.each(function () {
                $(this).find(".cp-button-viewProperty, .mod-tile-title a").attr('href', 'javascript:;');
            });
        } else {
            $modTile.each(function () {
                var datasrcUrl = $(this).find(".cp-button-viewProperty, .mod-tile-title a").data('srcurl');
                $(this).find(".cp-button-viewProperty, .mod-tile-title a").attr('href', datasrcUrl);
            });
            if ($(".mod-quickView").is(":visible")) {
                closeQuickView();
            }
        }
    }

    ///<summary>Google Analytics Tracking Event, when the user clicks book from inside Quick View</summary>
    function trackQuickViewClickBookEvent() {
        if (typeof ga != "undefined") {
            ga("send", "event", "QuickBook", "Book");
            if (typeof ga.getByName == "function") {
                var propertyTracker = ga.getByName('propertyTracker');
                if (typeof propertyTracker != "undefined") {
                    ga("propertyTracker.send", "event", "QuickBook", "Book");
                }
            }
        }
    }

    ///<summary>Google Analytics Tracking Event, when the user clicks to open Quick View</summary>
    function trackQuickViewShowEvent() {
        if (typeof ga != "undefined") {
            ga("send", "event", "QuickBook", "View");
            if (typeof ga.getByName == "function") {
                var propertyTracker = ga.getByName('propertyTracker');
                if (typeof propertyTracker != "undefined") {
                    ga("propertyTracker.send", "event", "QuickBook", "View");
                }
            }
        }
    }

    ///<summary>Google Analytics Tracking Event, when the user clicks view property from within the Quick View</summary>
    function trackPropertyViewFromQuickBookEvent() {
        if (typeof ga != "undefined") {
            ga("send", "event", "ViewProperty", "View From QuickBook");
            if (typeof ga.getByName == "function") {
                var propertyTracker = ga.getByName('propertyTracker');
                if (typeof propertyTracker != "undefined") {
                    ga("propertyTracker.send", "event", "ViewProperty", "View From QuickBook");
                }
            }
        }
    }

    ///<summary>Google Analytics Tracking Event, when the user clicks view Property</summary>
    function trackPropertyViewViewEvent() {
        if (typeof ga != "undefined") {
            ga("send", "event", "ViewProperty", "View");
            if (typeof ga.getByName == "function") {
                var propertyTracker = ga.getByName('propertyTracker');
                if (typeof propertyTracker != "undefined") {
                    ga("propertyTracker.send", "event", "ViewProperty", "View");
                }
            }
        }
    }

    function closeQuickView() {
        //clears every possible highlighted property
        modTileHighlight();
        //hides the quickview popup
        $(".mod-quickView").removeClass("quickView--isActive");
        $("div#quickViewPlaceHolder").remove();
    }

    function tooltip() {
        $(".mod-quickView .cp-tip").tooltip({
            tooltipClass: "tooltip-white",
            position: {
                my: "center bottom-15",
                at: "center top",
                using: function (position, feedback) {
                    $(this).css(position);
                    $("<div ckl>")
                    .addClass("arrow")
                    .addClass(feedback.vertical)
                    .addClass(feedback.horizontal)
                    .appendTo(this);
                }
            },
            content: function () {
                return $(this).prop('title');
            }
        });
    }

    function simpleGalleryinit() {
        var mainImage = $('.mod-simpleGallery-main img');
       
        //initilize simple gallery after successful ajax call
        $(".mod-simpleGallery-thumbs li:first-child").addClass("active");

        $(".mod-simpleGallery-thumbs a").on("click", function () {
            $(".mod-simpleGallery-thumbs li").removeClass("active");
            $(this).parent().addClass("active");
        });

        function replaceImgSource(sourceElement) {
            mainImage.attr('src', sourceElement.attr("data-main_url"));
        }

        $('.mod-simpleGallery-thumbs img').on("click", function () {
            replaceImgSource($(this));
        });

        $(".mod-simpleGallery-next").on("click", function () {
            $(".mod-simpleGallery-thumbs li.active:not(:last-child)").removeClass("active").next("li").addClass("active");
            replaceImgSource($(".mod-simpleGallery-thumbs li.active img"));
        });

        $(".mod-simpleGallery-prev").on("click", function () {
            $(".mod-simpleGallery-thumbs li.active:not(:first-child)").removeClass("active").prev("li").addClass("active");
            replaceImgSource($(".mod-simpleGallery-thumbs li.active img"));
        });

    }

    ///<summary></summary>
    function getPageContent(propertyShortName, $propertyDivContainer) {

        var serializedData = eviivo.searchSystem.search.getSerializedData();
        if (propertyShortName == null) {
            propertyShortName = $propertyDivContainer.data('shortname');
        }
        serializedData += "&shortname=" + propertyShortName;
        if (!jQuery.isEmptyObject($contentPlaceHolder)) {
            //If an ajax call is still taking place cancels it
            if ($ajaxRequest != null) {
                return;
            }
            //add spinner icon on the tile
            addLoading();

            var searchData = JSON.parse($('#results-properties-summary').val());

            var result = JSON.stringify(searchData.find(item => {
                return item.ShortName.toLowerCase() === propertyShortName.toLowerCase()
            }));

            $ajaxRequest = $.ajax({
                type: 'POST',
                url: options.requestUrl + '?' + serializedData,                                
                data: { propertyData: result },
                dataType: 'html',
                success: function (data) {
                    $ajaxRequest = null;

                    // if placeholder exist remove it
                    if ($(".mod-quickView").length === 1) {
                        $(".mod-quickView").remove();
                    }

                    var $quickViewPlaceholder = $("<div id='quickViewPlaceHolder' class='mod-quickView " + propertyShortName + "'></div>");

                    $contentPlaceHolder = $(options.contentPlaceHolder);


                    // find current tile id and insert placeholder container after
                    $quickViewPlaceholder.insertAfter("#" + propertyShortName + "-tile");
                    // populate quikclook data
                    $quickViewPlaceholder.html(data);
                    if ($contentPlaceHolder.length == 0) {
                        $contentPlaceHolder = $(options.contentPlaceHolder);
                    }
                    $('html, body').animate({ scrollTop: $("#" + propertyShortName + "-tile").offset().top - 5 }, 800);
                    setPropertyNameAndBookingPagesUrl(propertyShortName, $propertyDivContainer);
                    bindQuickViewEvents(propertyShortName);
                    tooltip();
                    simpleGalleryinit();

                    if ($contentPlaceHolder.find(options.radioButtonsSelector).length > 0) {
                        $contentPlaceHolder.find(options.radioButtonsSelector).buttonset();
                    }
                },
                error: getPageContentError
            }).done(function () {
                //remove spinner icon on the tile
                removeLoading();
            });
        } else {
            console.log("no placeholder available");
        }
    }

    function removeLoading() {
        if ($(window).width() > 768) {
            //remove loading icon from the tile if screen is is bigger than ipad
            $(".mod-tile-image").find(".cp--loading").remove();
        }
    }

    function addLoading() {
        if ($(window).width() > 768) {
            $(".mod-tile").on("click", function () {
                var $loader = $("<div class='cp--loading'><span class='circle'></span></div>");
                $(this).find(".mod-tile-image").prepend($loader);
            });
        }
    }

    function bindQuickViewEvents(shortName) {
        //Initialize the tabs feature
        $(options.tabsSelector).on('click', onTabClick);

        //Initialize toggle view
        $(options.toggleTrigger).on('click', toggleView);

        //Binds the book buttons to the postback
        $contentPlaceHolder.find(options.bookButtonsSelector).on("click", submitOrder);

        //Sets the highlight for the property mod-tile.
        modTileHighlight(shortName);

        //Applies the picturefill action to all the loaded images
        picturefill();

        //Toggles the read more option in the reviews tab
        $(".mod-quickView").find(".column-review-content .icon-dropdown").on("click", toggleReadMore);

        //binds the close button 
        $contentPlaceHolder.find(".cp-close").on("click", closeQuickView);

        //when a user clicks view property inside que quick view, it should trigger the google analytics event
        $(".mod-quickView").find(".cp-button-viewProperty").on("click", trackPropertyViewFromQuickBookEvent);

        $contentPlaceHolder.find(options.enterDateLink).on("click", showStartDateCalendar);


        bindNavigationButtonEvents(shortName);

    }

    function showStartDateCalendar() {
        if (!$viewportWidth < 768) { //smaller than ipad
            $('html,body').animate({ scrollTop: $startDate.offset().top }, 500, 'swing');
            $startDate.datepicker("show");

        }
    }

    function bindNavigationButtonEvents(shortName) {
        //Initialize previous and next button
        var $previousButton = $(options.previousButtonSelector);
        var $nextButton = $(options.nextButtonSelector);
        var currentPropertyIndex = $.inArray(shortName, propertiesShortName);
        var arraySize = propertiesShortName.length;
        var previousProperty;
        var nextProperty;
        if (arraySize > 1) {
            //Sets the necessary logic to make a loop in the previous next.
            //If the current property is the first on the list, sets the previous to the last object in the list.
            if (currentPropertyIndex == 0) {
                previousProperty = propertiesShortName[arraySize - 1];
            } else {
                previousProperty = propertiesShortName[currentPropertyIndex - 1];
            }
            //If the current property is the last in the list set the next as the first object
            if (currentPropertyIndex == arraySize - 1) {
                nextProperty = propertiesShortName[0];
            } else {
                nextProperty = propertiesShortName[currentPropertyIndex + 1];
            }
            $previousButton.on('click', function () {
                getPageContent(previousProperty);
            });
            $nextButton.on('click', function () {
                getPageContent(nextProperty);
            });
        } else {
            $nextButton.hide();
            $previousButton.hide();
        }
    }

    ///<summary>Hover states to add active state to tile</summary>
  function modTileHighlight(shortName) {
    var $contentTile = $(".mod-tile");
    $contentTile.removeClass("active dimmed"); // Remove both classes initially

    if (shortName == undefined) {
        return;
    }

    // Add 'active' class to the current tile and 'dimmed' class to others
    $contentTile.each(function () {
        if ($(this).data('shortname') === shortName) {
            $(this).addClass("active");
        } else {
            $(this).addClass("dimmed");
        }
    });
}




    function getPageContentError(jqXhr, textStatus, errorThrown) {
        $ajaxRequest = null;
        if (textStatus != "abort") {
            $contentPlaceHolder.html(errorThrown);

        }
    }

    function getPropertyName(shortName, $propertyDivContainer) {
        if ($propertyDivContainer == undefined) {
            $propertyDivContainer = $quickViewCta.filter(function () {
                return $(this).data('shortname') && $(this).data('shortname') === shortName;
            });
        }
        return $propertyDivContainer.parents('section.mod-tile').find('div.mod-tile-title h3.propertyName');
    }

    function setPropertyNameAndBookingPagesUrl(shortName, $propertyDivContainer) {

        var propertyName = getPropertyName(shortName, $propertyDivContainer);

        var bookingPagesUrlAnchor = $(propertyName).find('a');

        if (bookingPagesUrlAnchor.length) {
            var href = $(bookingPagesUrlAnchor).data('srcurl');

            var $alternativeRateplansButton = $contentPlaceHolder.find('a#alternative-rateplans');
            if ($alternativeRateplansButton.length) {
                var roomsBookmark = $alternativeRateplansButton.attr('href');
                $alternativeRateplansButton.attr('href', href + roomsBookmark);
                $alternativeRateplansButton.attr('target', '_blank');
            }

            var $alternativeReviewsButton = $contentPlaceHolder.find('a#alternative-reviews');
            if ($alternativeReviewsButton.length) {
                var reviewsBookmark = $alternativeReviewsButton.attr('href');
                $alternativeReviewsButton.attr('href', href + reviewsBookmark);
                $alternativeReviewsButton.attr('target', '_blank');
            }


            var $readMoretext = $contentPlaceHolder.find('.qw-outerContent a.cp-link');
            if ($readMoretext.length) {
                var $readMoretext1 = $readMoretext.attr('href');
                $readMoretext.attr('href', href + $readMoretext1);
                $readMoretext.attr('target', '_blank');
            }

            var $linkToPropertyButton = $contentPlaceHolder.find('a#linkToProperty, .qw-header h1 a');
            if ($linkToPropertyButton.length) {
                $linkToPropertyButton.attr('href', href);
                $linkToPropertyButton.attr('target', '_blank');
            }

            var $linkToPropertyVirtualTourButton = $contentPlaceHolder.find('#linkToPropertyVirtualTour');
            if ($linkToPropertyVirtualTourButton.length) {
                var virtualTourLinkHref = href + "&virtualTour=true";
                $linkToPropertyVirtualTourButton.attr('href', virtualTourLinkHref);
                $linkToPropertyVirtualTourButton.attr('target', '_blank');
            }
            
            var $linkToPropertyAnchorButton = $contentPlaceHolder.find('#linkToPropertyAnchor');
            if ($linkToPropertyAnchorButton.length) {
                var virtualTourLinkHref = href + "#mod-results";
                $linkToPropertyAnchorButton.attr('href', virtualTourLinkHref);
                $linkToPropertyAnchorButton.attr('target', '_blank');
            }

            var $linkToRoom = $contentPlaceHolder.find('.qw-content-details h4 a, .qw-content-actions a');
            $linkToRoom.each(function () {
                var $roomGroupLink = $(this).attr('href');
                $(this).attr('href', href + $roomGroupLink);
                $(this).attr('target', '_blank');
            });

            var $linkToPropertyMap = $contentPlaceHolder.find('a#linkToMap');
            if ($linkToPropertyMap.length) {
                var qsAppend = document.location.search.length ? '&' : '?';
                $linkToPropertyMap.attr('href', href + qsAppend + "showMapByDefault=true");
                $linkToPropertyMap.attr('target', '_blank');
            }
        }
    }

    ///<summary></summary>
    function submitOrder() {
        trackQuickViewClickBookEvent();
        var $submitForm = $("#submit-reservation");
        var productId = $(this).parents(".qw-content-actions").find("input[type='hidden']");
        $submitForm.find("input[name^='product']").val(productId.val());
        $submitForm.attr("action", window.location.href);
        $submitForm.attr('target', '_blank');
        $submitForm.trigger("submit");
    }


    function onTabClick(event) {
        event.preventDefault();

        $(this).parent().addClass("current");
        $(this).parent().siblings().removeClass("current");

        var tab = $(this).attr("href");

        $(".mod-tab-content").not(tab).css("display", "none");
        $(tab).show();
    }

    function toggleView() {
        var $toggleDesc = $('.toggle-desc');
        var $toggleMap = $('.toggle-map');

        if ($toggleDesc.is(':visible')) {
            $toggleDesc.hide();
            $toggleMap.show();
            $(this).text(options.viewDesc);
        } else {
            $toggleMap.hide();
            $toggleDesc.show();
            $(this).text(options.viewMap);
        }
    }

    function toggleReadMore() {
        $(this).parent().siblings(".review-item-details").slideToggle();
        $(this).parent().parent().toggleClass("active");
        var textDefault = options.readMore;
        var textExpanded = options.readLess;
        $(this).text(function (i, text) {
            return text === textExpanded ? textDefault : textExpanded;
        });

    }

    return {
        init: init
    };

}(jQuery);
/*! 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 } } });
