// source --> https://classified.maalz.com/wp-content/plugins/listingpro-plugin/assets/js/submit-listing.js?ver=4fca74de5e3fa981b9659807f09e9e55 
var widgetsubmit;


/**
 * detect IE
 * returns version of IE or false, if browser is not Internet Explorer
 */
function detectIE() {
    var ua = window.navigator.userAgent;

    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
        // Edge (IE 12+) => return version number
        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }

    // other browser
    return false;
}

function recaptchaCallbackk() {
    if (jQuery('#recaptcha-securet').length) {
        var sitekey = jQuery('#recaptcha-securet').data('sitekey');
        widgetsubmit = grecaptcha.render(document.getElementById('recaptcha-securet'), {
            'sitekey': sitekey
        })
    }
}
window.onload = recaptchaCallbackk;
jQuery(document).on('submit', '#lp-submit-form', function(e) {

    jQuery('.error_box').hide('');
    jQuery('.error_box').html('');
    jQuery('.error_box').text('');
    jQuery('.username-invalid-error').html('');
    jQuery('.username-invalid-error').text('');
    var $this = jQuery(this);
    jQuery('span.email-exist-error').remove();
    jQuery('input').removeClass('error-msg');
    jQuery('textarea').removeClass('error-msg');

    var checkforgallery = false;
    if (jQuery('.jFiler-input-dragDrop .jFiler-input-inner .filediv input').hasClass('lp-required-field')) {
        checkforgallery = true;
    }
    if (checkforgallery){
        if (jQuery('div.filediv').length > 1) {
            jQuery('.jFiler-input-dragDrop').css('border-color', '#C8CBCE');
            jQuery('.jFiler-input-dragDrop .jFiler-input-inner .filediv input').removeClass('error-msg');
        }else {
            jQuery('.jFiler-input-dragDrop').css('border-color', '#eb5439');
            jQuery('.jFiler-input-dragDrop .jFiler-input-inner .filediv input').addClass('error-msg');
        }
    }

    var checkforfimage = false;
    if (jQuery('#lp-featuredimage').hasClass('lp-required-field')) {
        checkforfimage = true;
    }
    if (checkforfimage){
        if( document.getElementById("lp-featuredimage").files.length != 0 ){
            jQuery('.featured-img-label').css('border-color', '#C8CBCE');
            jQuery('#lp-featuredimage').removeClass('error-msg');
        }else {
            jQuery('.featured-img-label').css('border-color', '#eb5439');
            jQuery('#lp-featuredimage').addClass('error-msg');
        }
    }

    var checkforblogo = false;
    if (jQuery('#business_logo').hasClass('lp-required-field')) {
        checkforblogo = true;
    }
    if (checkforblogo){
        if( document.getElementById("business_logo").files.length != 0 ){
            jQuery('.b-logo-img-label').css('border-color', '#C8CBCE');
            jQuery('#business_logo').removeClass('error-msg');
        }else {
            jQuery('.b-logo-img-label').css('border-color', '#eb5439');
            jQuery('#business_logo').addClass('error-msg');
        }
    }

    if (jQuery('#citiess').hasClass('lp-required-field')) {
        if (jQuery('.lp-selected-locs .lpsinglelocselected').length>0) {
            jQuery('#citiess').removeClass('lp-required-field');
        }
    }
    if (jQuery('#inputAddresss,#inputAddress').hasClass('lp-required-field')) {
        if (jQuery('#inputAddresss').val()!=''){
            jQuery('#inputAddress').removeClass('lp-required-field');
            if(!jQuery('#inputAddresss').hasClass('lp-required-field')){
                jQuery('#inputAddresss').addClass('lp-required-field');
            }
        }
        else if(jQuery('#inputAddress').val()!=''){
            jQuery('#inputAddresss').removeClass('lp-required-field');
            if(!jQuery('#inputAddress').hasClass('lp-required-field')){
                jQuery('#inputAddress').addClass('lp-required-field');
            }
        }
    }

    var is_valid_form = true;
    $this.find('input.lp-required-field, select.lp-required-field, textarea.lp-required-field').each(function() {
        var tag_name = jQuery(this).prop("tagName").toLowerCase();
        var field_val = jQuery(this).val();

        if ((jQuery(this).attr('id') == 'inputUsername') || (jQuery(this).attr('id') == 'inputUserpass') || (jQuery(this).attr('id') == 'inputEmail') || (jQuery(this).attr('id') == 'customUname')) {
            if (jQuery('#already-account').is(':checked')) {
                if (jQuery('input#inputUsername').val() == '' || jQuery('input#inputUserpass').val() == '') {
                    jQuery('input#inputUsername').addClass('error-msg');
                    jQuery('input#inputUserpass').addClass('error-msg');
                    is_valid_form = false;
                }else {
                    jQuery('input#inputEmail').removeClass('error-msg');
                }
            }else {
                if (jQuery('input#inputEmail').val() == '') {
                    jQuery('input#inputEmail').addClass('error-msg');
                    is_valid_form = false;
                }else {
                    jQuery('input#inputEmail').removeClass('error-msg');
                }
                if (jQuery('input#customUname').length > 0) {
                    if (jQuery('input#customUname').val() == '') {
                        jQuery('input#customUname').addClass('error-msg');
                        is_valid_form = false;
                    } else {
                        jQuery('input#customUname').removeClass('error-msg');
                    }
                }
            }
        } else {
            if (field_val == '') {
                if (tag_name === 'select') {
                    jQuery(this).next().addClass('error-msg');
                } else if (jQuery(this).hasClass('wp-editor-area')) {
                    jQuery(this).closest(".wp-editor-container").addClass('error-msg');
                } else {
                    jQuery(this).addClass('error-msg');
                }
                is_valid_form = false;
            } else {
                if (tag_name === 'select') {
                    jQuery(this).next().removeClass('error-msg');
                } else if (jQuery(this).hasClass('wp-editor-area')) {
                    jQuery(this).closest(".wp-editor-container").removeClass('error-msg');
                } else {
                    jQuery(this).removeClass('error-msg');
                }
            }
        }
    });

    var checksocial = false;
    if (jQuery('.required-social-media').length > 0) {
        checksocial = true;
    }
    if (checksocial) {
        if (jQuery('.style2-social-list-section .social-row').length > 0) {
            jQuery('#get_media_url').removeClass('error');
            jQuery('#get_media_url').removeClass('error-msg');
            jQuery('#select2-get_media-container').removeClass('error');
            jQuery('#select2-get_media-container').removeClass('error-msg');
            if( is_valid_form === true ) {
                is_valid_form = true;
            }
        }else {
            jQuery('#get_media_url').addClass('error');
            jQuery('#get_media_url').addClass('error-msg');
            jQuery('#select2-get_media-container').addClass('error');
            jQuery('#select2-get_media-container').addClass('error-msg');
            if( is_valid_form === true ) {
                is_valid_form = false;
            }
        }
    }

    if( is_valid_form === true ){

        $this.find('.preview-section .fa-angle-right').removeClass('fa-angle-right');
        $this.find('.preview-section .fa').addClass('fa-spinner fa-spin');
        jQuery('.bottomofbutton.lpsubmitloading').addClass('fa-spinner fa-spin');
        jQuery('.loaderoneditbutton.lpsubmitloading').addClass('fa-spinner fa-spin');

        isCaptcha = jQuery(this).data('lp-recaptcha');
        siteKey = jQuery(this).data('lp-recaptcha-sitekey');
        token = '';

        var fd = new FormData(this);

        $maxAlloedSize = parseInt(jQuery('#lp-submit-form').data('imgsize'));
        $totalAlloedImgs = parseInt(jQuery('#lp-submit-form').data('imgcount'));

        if(detectIE() == false){

            var $fullbrowserdet = navigator.sayswho;
            var $browserArray = $fullbrowserdet.split(" ");// outputs: `Chrome 62`
            if($browserArray[0]=="Safari"){
                if($browserArray[1] >= 12){
                    fd.delete('listingfiles[]');
                    fd.delete('lp-featuredimage[]');
                    fd.delete('business_logo[]');
                }

            }else{

                fd.delete('listingfiles[]');
                fd.delete('lp-featuredimage[]');
                fd.delete('business_logo[]');

            }


        }

        $totalfilesize = 0;
        var lpcount = 0;
        var lpcountsize = 0;
        $totalfilesize = jQuery('.lplistgallery').attr('data-savedgallweight');
        $selectedImagesCount = jQuery('.lplistgallery').attr('data-savedgallerysize');
        if (jQuery("input[name='listingfiles[]']").length){
            jQuery.each(jQuery("input[name='listingfiles[]']"), function(k, files) {
                jQuery.each(jQuery("input[name='listingfiles[]']")[k].files, function(i, file) {
                    if(file.size > 1 || file.fileSize > 1) {
                        fd.append('listingfiles[' + lpcount + ']', file);
                        lpcount++;
                    }
                });
            });
        }

        $AlloedSize = true;
        $Alloedimgcount = true;
        if(!isNaN($totalfilesize)){
            if($totalfilesize > $maxAlloedSize){
                msgf = jQuery('#lp-submit-form').data('sizenotice');
                var resError = {response : 'fail', msg : msgf};
                listing_ajax_response_notice(resError);
                $this.find('.preview-section').addClass('fa-angle-right');
                jQuery('.lpsubmitloading').addClass('fa-angle-right');
                $this.find('.preview-section .fa').removeClass('fa-spinner fa-spin');
                jQuery('.bottomofbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                $AlloedSize = false;
                return false;
            }
        }
        if($selectedImagesCount > $totalAlloedImgs){
            msgf = jQuery('#lp-submit-form').data('countnotice');
            var resError = {response : 'fail', msg : msgf};
            listing_ajax_response_notice(resError);
            jQuery('.lpsubmitloading').addClass('fa-angle-right');
            $this.find('.preview-section').addClass('fa-angle-right');
            $this.find('.preview-section .fa').removeClass('fa-spinner fa-spin');
            jQuery('.bottomofbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
            jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
            $Alloedimgcount = false;
        }else{



            if (jQuery("input[name='business_logo[]']").length){
                fd.append('business_logo[]', jQuery("input[name='business_logo[]']")[0].files[0]);
            }

            if (jQuery("input[name='lp-featuredimage[]']").length){
                fd.append('lp-featuredimage[]', jQuery("input[name='lp-featuredimage[]']")[0].files[0]);
            }
            jQuery("#listingsubmitBTN").prop('disabled', !0);
            fd.append('action', 'listingpro_submit_listing_ajax');
            if (jQuery('#already-account').is(':checked')) {
                fd.append('processLogin', 'yes')
            } else {
                fd.append('processLogin', 'no')
            }
            var postContent = tinymce.editors.inputDescription.getContent();
            if (postContent != '' || postContent != null || postContent != !1) {
                fd.append('postContent', postContent)
            } else {
                fd.append('postContent', '')
            }
            if($Alloedimgcount == true){
                fd.append('imageCount', lpcount)
            }
            if ( (isCaptcha == '' || isCaptcha === null) || (siteKey == '' || siteKey === null) ) {
                jQuery.ajax({
                    type: 'POST',
                    url: ajax_listingpro_submit_object.ajaxurl,
                    data: fd,
                    contentType: !1,
                    processData: !1,
                    success: function(res) {

                        var resp = jQuery.parseJSON(res);
                        listing_ajax_response_notice(resp);
                        if (resp.response === "fail") {
                            jQuery("#listingsubmitBTN").prop('disabled', !1);
                            jQuery.each(resp.status, function(k, v) {
                                if (k === "postTitle") {
                                    jQuery("input:text[name='postTitle']").addClass('error-msg')
                                } else if (k === "gAddress") {
                                    jQuery("input:text[name='gAddress']").addClass('error-msg')
                                } else if (k === "category") {
                                    jQuery("#inputCategory_chosen").find('a.chosen-single').addClass('error-msg');
                                    jQuery("#inputCategory").next('.select2-container').find('.selection').find('.select2-selection--single').addClass('error-msg');
                                    jQuery("#inputCategory").next('.select2-container').find('.selection').find('.select2-selection--multiple').addClass('error-msg')
                                } else if (k === "location") {
                                    jQuery("#inputCity_chosen").find('a.chosen-single').addClass('error-msg');
                                    jQuery("#inputCity").next('.select2-container').find('.selection').find('.select2-selection--single').addClass('error-msg');
                                    jQuery("#inputCity").next('.select2-container').find('.selection').find('.select2-selection--multiple').addClass('error-msg')
                                } else if (k === "postContent") {
                                    jQuery("textarea[name='postContent']").addClass('error-msg');
                                    jQuery("#lp-submit-form .wp-editor-container").addClass('error-msg')
                                } else if (k === "email") {
                                    jQuery("input#inputEmail").addClass('error-msg')
                                } else if (k === "inputUsername") {
                                    jQuery("input#inputUsername").addClass('error-msg')
                                } else if (k === "inputUserpass") {
                                    jQuery("input#inputUserpass").addClass('error-msg')
                                }
                            });
                            var errorrmsg = jQuery("input[name='errorrmsg']").val();
                            $this.find('.preview-section .fa-spinner').removeClass('fa-spinner fa-spin');
                            $this.find('.preview-section .fa').addClass('fa-times');
                            $this.find('.preview-section').find('.error_box').text(errorrmsg).show();
                            jQuery('.bottomofbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                            jQuery('.bottomofbutton.lpsubmitloading').addClass('fa-times');
                            jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                            jQuery('.loaderoneditbutton.lpsubmitloading').addClass('fa-times');
                        } else if (resp.response === "failure") {
                            if (jQuery('#already-account').is(':checked')) {
                                jQuery('.lp-submit-have-account').append(resp.status)
                            } else {
                                jQuery("input#inputEmail").after(resp.status);
                                jQuery("div#inputEmail").after(resp.status)
                            }
                            $this.find('.preview-section .fa-spinner').removeClass('fa-spinner fa-spin');
                            $this.find('.preview-section .fa').addClass('fa-angle-right');
                            jQuery("#listingsubmitBTN").prop('disabled', !1);
                            jQuery('.bottomofbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                            jQuery('.bottomofbutton.lpsubmitloading').addClass('fa-times');
                            jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                            jQuery('.loaderoneditbutton.lpsubmitloading').addClass('fa-times');
                        } else if (resp.response === "success") {
                            $this.find('.preview-section .fa-spinner').removeClass('fa-times');
                            $this.find('.preview-section .fa-spinner').removeClass('fa-spinner fa-spin');
                            $this.find('.preview-section .fa').addClass('fa-check');
                            jQuery('.bottomofbutton.lpsubmitloading').removeClass('fa-times');
                            jQuery('.bottomofbutton.lpsubmitloading').addClass('fa-check');
                            jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                            jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-angle-right');
                            jQuery('.loaderoneditbutton.lpsubmitloading').addClass('fa-check');
                            var redURL = resp.status;

                            function redirectPageNow() {
                                window.location.href = redURL
                            }
                            setTimeout(redirectPageNow, 1000)
                        }
                    },
                    error: function(request, error) {

                        $this.find('.preview-section .fa-spinner').removeClass('fa-times');
                        $this.find('.preview-section .fa-spinner').removeClass('fa-spinner fa-spin');
                        $this.find('.preview-section .fa').addClass('fa-times');
                        alert(error)
                    }
                });


            }else{
                //for recaptcha
                grecaptcha.ready(function() {
                    grecaptcha.execute(siteKey, {action: 'lp_submitlisting'}).then(function(token) {
                        fd.append('recaptha-action', 'lp_submitlisting');
                        fd.append('token', token);


                        jQuery.ajax({
                            type: 'POST',
                            url: ajax_listingpro_submit_object.ajaxurl,
                            data: fd,
                            contentType: !1,
                            processData: !1,
                            success: function(res) {

                                var resp = jQuery.parseJSON(res);
                                listing_ajax_response_notice(resp);
                                if (resp.response === "fail") {
                                    jQuery("#listingsubmitBTN").prop('disabled', !1);
                                    jQuery.each(resp.status, function(k, v) {
                                        if (k === "postTitle") {
                                            jQuery("input:text[name='postTitle']").addClass('error-msg')
                                        } else if (k === "gAddress") {
                                            jQuery("input:text[name='gAddress']").addClass('error-msg')
                                        } else if (k === "category") {
                                            jQuery("#inputCategory_chosen").find('a.chosen-single').addClass('error-msg');
                                            jQuery("#inputCategory").next('.select2-container').find('.selection').find('.select2-selection--single').addClass('error-msg');
                                            jQuery("#inputCategory").next('.select2-container').find('.selection').find('.select2-selection--multiple').addClass('error-msg')
                                        } else if (k === "location") {
                                            jQuery("#inputCity_chosen").find('a.chosen-single').addClass('error-msg');
                                            jQuery("#inputCity").next('.select2-container').find('.selection').find('.select2-selection--single').addClass('error-msg');
                                            jQuery("#inputCity").next('.select2-container').find('.selection').find('.select2-selection--multiple').addClass('error-msg')
                                        } else if (k === "postContent") {
                                            jQuery("textarea[name='postContent']").addClass('error-msg');
                                            jQuery("#lp-submit-form .wp-editor-container").addClass('error-msg')
                                        } else if (k === "email") {
                                            jQuery("input#inputEmail").addClass('error-msg')
                                        } else if (k === "inputUsername") {
                                            jQuery("input#inputUsername").addClass('error-msg')
                                        } else if (k === "inputUserpass") {
                                            jQuery("input#inputUserpass").addClass('error-msg')
                                        }
                                    });
                                    var errorrmsg = jQuery("input[name='errorrmsg']").val();
                                    $this.find('.preview-section .fa-spinner').removeClass('fa-spinner fa-spin');
                                    $this.find('.preview-section .fa').addClass('fa-times');
                                    $this.find('.preview-section').find('.error_box').text(errorrmsg).show();
                                    jQuery('.bottomofbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                                    jQuery('.bottomofbutton.lpsubmitloading').addClass('fa-times');
                                    jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                                    jQuery('.loaderoneditbutton.lpsubmitloading').addClass('fa-times');
                                } else if (resp.response === "failure") {
                                    if (jQuery('#already-account').is(':checked')) {
                                        jQuery('.lp-submit-have-account').append(resp.status)
                                    } else {
                                        jQuery("input#inputEmail").after(resp.status);
                                        jQuery("div#inputEmail").after(resp.status)
                                    }
                                    $this.find('.preview-section .fa-spinner').removeClass('fa-spinner fa-spin');
                                    $this.find('.preview-section .fa').addClass('fa-angle-right');
                                    jQuery("#listingsubmitBTN").prop('disabled', !1);
                                    jQuery('.bottomofbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                                    jQuery('.bottomofbutton.lpsubmitloading').addClass('fa-times');
                                    jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                                    jQuery('.loaderoneditbutton.lpsubmitloading').addClass('fa-times');
                                } else if (resp.response === "success") {
                                    $this.find('.preview-section .fa-spinner').removeClass('fa-times');
                                    $this.find('.preview-section .fa-spinner').removeClass('fa-spinner fa-spin');
                                    $this.find('.preview-section .fa').addClass('fa-check');
                                    jQuery('.bottomofbutton.lpsubmitloading').removeClass('fa-times');
                                    jQuery('.bottomofbutton.lpsubmitloading').addClass('fa-check');
                                    jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-spinner fa-spin');
                                    jQuery('.loaderoneditbutton.lpsubmitloading').removeClass('fa-angle-right');
                                    jQuery('.loaderoneditbutton.lpsubmitloading').addClass('fa-check');
                                    var redURL = resp.status;

                                    function redirectPageNow() {
                                        window.location.href = redURL
                                    }
                                    setTimeout(redirectPageNow, 1000)
                                }
                            },
                            error: function(request, error) {
                                if (!jQuery('#recaptcha-securet').length === 0) {
                                    lp_reset_grecaptcha()
                                }
                                $this.find('.preview-section .fa-spinner').removeClass('fa-times');
                                $this.find('.preview-section .fa-spinner').removeClass('fa-spinner fa-spin');
                                $this.find('.preview-section .fa').addClass('fa-times');
                                alert(error)
                            }
                        });


                    });
                })


            }
        }
    }else{
        var error_msg = 'Sorry! There is problem in your submission';
        if(jQuery('.lp-notifaction-error').length > 0){
            error_msg = jQuery('.lp-notifaction-error').data('error-msg');
        }
        var resp = {
            response: 'fail',
            msg: error_msg
        };
        listing_ajax_response_notice(resp);
        return false;
    }
    e.preventDefault()
});



function listing_ajax_response_notice(res){
    if( res.response == 'success' ){
        jQuery('.lp-notifaction-area').find('h4').text(res.msg);
        jQuery('.lp-notifaction-area').removeClass('lp-notifaction-error').addClass('lp-notifaction-success');
        jQuery('.lp-notifaction-area').addClass('active-wrap');

    }
    if ( res.response == 'fail' || res.response == 'failure' ){
        jQuery('.lp-notifaction-area').find('h4').text(res.msg);
        jQuery('.lp-notifaction-area').removeClass('lp-notifaction-success').addClass('lp-notifaction-error');
        jQuery('.lp-notifaction-area').addClass('active-wrap');
    }
}

//check browser code

navigator.sayswho= (function(){
    var ua= navigator.userAgent, tem,
        M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();
// source --> https://classified.maalz.com/wp-content/plugins/listingpro-lead-form/assets/js/moment.js?ver=4fca74de5e3fa981b9659807f09e9e55 
//! moment.js
//! version : 2.13.0
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com

;(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    global.moment = factory()
}(this, function () { 'use strict';

    var hookCallback;

    function utils_hooks__hooks () {
        return hookCallback.apply(null, arguments);
    }

    // This is done to register the method called with moment()
    // without creating circular dependencies.
    function setHookCallback (callback) {
        hookCallback = callback;
    }

    function isArray(input) {
        return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
    }

    function isDate(input) {
        return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
    }

    function map(arr, fn) {
        var res = [], i;
        for (i = 0; i < arr.length; ++i) {
            res.push(fn(arr[i], i));
        }
        return res;
    }

    function hasOwnProp(a, b) {
        return Object.prototype.hasOwnProperty.call(a, b);
    }

    function extend(a, b) {
        for (var i in b) {
            if (hasOwnProp(b, i)) {
                a[i] = b[i];
            }
        }

        if (hasOwnProp(b, 'toString')) {
            a.toString = b.toString;
        }

        if (hasOwnProp(b, 'valueOf')) {
            a.valueOf = b.valueOf;
        }

        return a;
    }

    function create_utc__createUTC (input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, true).utc();
    }

    function defaultParsingFlags() {
        // We need to deep clone this object.
        return {
            empty           : false,
            unusedTokens    : [],
            unusedInput     : [],
            overflow        : -2,
            charsLeftOver   : 0,
            nullInput       : false,
            invalidMonth    : null,
            invalidFormat   : false,
            userInvalidated : false,
            iso             : false,
            parsedDateParts : [],
            meridiem        : null
        };
    }

    function getParsingFlags(m) {
        if (m._pf == null) {
            m._pf = defaultParsingFlags();
        }
        return m._pf;
    }

    var some;
    if (Array.prototype.some) {
        some = Array.prototype.some;
    } else {
        some = function (fun) {
            var t = Object(this);
            var len = t.length >>> 0;

            for (var i = 0; i < len; i++) {
                if (i in t && fun.call(this, t[i], i, t)) {
                    return true;
                }
            }

            return false;
        };
    }

    function valid__isValid(m) {
        if (m._isValid == null) {
            var flags = getParsingFlags(m);
            var parsedParts = some.call(flags.parsedDateParts, function (i) {
                return i != null;
            });
            m._isValid = !isNaN(m._d.getTime()) &&
                flags.overflow < 0 &&
                !flags.empty &&
                !flags.invalidMonth &&
                !flags.invalidWeekday &&
                !flags.nullInput &&
                !flags.invalidFormat &&
                !flags.userInvalidated &&
                (!flags.meridiem || (flags.meridiem && parsedParts));

            if (m._strict) {
                m._isValid = m._isValid &&
                    flags.charsLeftOver === 0 &&
                    flags.unusedTokens.length === 0 &&
                    flags.bigHour === undefined;
            }
        }
        return m._isValid;
    }

    function valid__createInvalid (flags) {
        var m = create_utc__createUTC(NaN);
        if (flags != null) {
            extend(getParsingFlags(m), flags);
        }
        else {
            getParsingFlags(m).userInvalidated = true;
        }

        return m;
    }

    function isUndefined(input) {
        return input === void 0;
    }

    // Plugins that add properties should also add the key here (null value),
    // so we can properly clone ourselves.
    var momentProperties = utils_hooks__hooks.momentProperties = [];

    function copyConfig(to, from) {
        var i, prop, val;

        if (!isUndefined(from._isAMomentObject)) {
            to._isAMomentObject = from._isAMomentObject;
        }
        if (!isUndefined(from._i)) {
            to._i = from._i;
        }
        if (!isUndefined(from._f)) {
            to._f = from._f;
        }
        if (!isUndefined(from._l)) {
            to._l = from._l;
        }
        if (!isUndefined(from._strict)) {
            to._strict = from._strict;
        }
        if (!isUndefined(from._tzm)) {
            to._tzm = from._tzm;
        }
        if (!isUndefined(from._isUTC)) {
            to._isUTC = from._isUTC;
        }
        if (!isUndefined(from._offset)) {
            to._offset = from._offset;
        }
        if (!isUndefined(from._pf)) {
            to._pf = getParsingFlags(from);
        }
        if (!isUndefined(from._locale)) {
            to._locale = from._locale;
        }

        if (momentProperties.length > 0) {
            for (i in momentProperties) {
                prop = momentProperties[i];
                val = from[prop];
                if (!isUndefined(val)) {
                    to[prop] = val;
                }
            }
        }

        return to;
    }

    var updateInProgress = false;

    // Moment prototype object
    function Moment(config) {
        copyConfig(this, config);
        this._d = new Date(config._d != null ? config._d.getTime() : NaN);
        // Prevent infinite loop in case updateOffset creates new moment
        // objects.
        if (updateInProgress === false) {
            updateInProgress = true;
            utils_hooks__hooks.updateOffset(this);
            updateInProgress = false;
        }
    }

    function isMoment (obj) {
        return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
    }

    function absFloor (number) {
        if (number < 0) {
            return Math.ceil(number);
        } else {
            return Math.floor(number);
        }
    }

    function toInt(argumentForCoercion) {
        var coercedNumber = +argumentForCoercion,
            value = 0;

        if (coercedNumber !== 0 && isFinite(coercedNumber)) {
            value = absFloor(coercedNumber);
        }

        return value;
    }

    // compare two arrays, return the number of differences
    function compareArrays(array1, array2, dontConvert) {
        var len = Math.min(array1.length, array2.length),
            lengthDiff = Math.abs(array1.length - array2.length),
            diffs = 0,
            i;
        for (i = 0; i < len; i++) {
            if ((dontConvert && array1[i] !== array2[i]) ||
                (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }

    function warn(msg) {
        if (utils_hooks__hooks.suppressDeprecationWarnings === false &&
                (typeof console !==  'undefined') && console.warn) {
            console.warn('Deprecation warning: ' + msg);
        }
    }

    function deprecate(msg, fn) {
        var firstTime = true;

        return extend(function () {
            if (utils_hooks__hooks.deprecationHandler != null) {
                utils_hooks__hooks.deprecationHandler(null, msg);
            }
            if (firstTime) {
                warn(msg + '\nArguments: ' + Array.prototype.slice.call(arguments).join(', ') + '\n' + (new Error()).stack);
                firstTime = false;
            }
            return fn.apply(this, arguments);
        }, fn);
    }

    var deprecations = {};

    function deprecateSimple(name, msg) {
        if (utils_hooks__hooks.deprecationHandler != null) {
            utils_hooks__hooks.deprecationHandler(name, msg);
        }
        if (!deprecations[name]) {
            warn(msg);
            deprecations[name] = true;
        }
    }

    utils_hooks__hooks.suppressDeprecationWarnings = false;
    utils_hooks__hooks.deprecationHandler = null;

    function isFunction(input) {
        return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
    }

    function isObject(input) {
        return Object.prototype.toString.call(input) === '[object Object]';
    }

    function locale_set__set (config) {
        var prop, i;
        for (i in config) {
            prop = config[i];
            if (isFunction(prop)) {
                this[i] = prop;
            } else {
                this['_' + i] = prop;
            }
        }
        this._config = config;
        // Lenient ordinal parsing accepts just a number in addition to
        // number + (possibly) stuff coming from _ordinalParseLenient.
        this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source);
    }

    function mergeConfigs(parentConfig, childConfig) {
        var res = extend({}, parentConfig), prop;
        for (prop in childConfig) {
            if (hasOwnProp(childConfig, prop)) {
                if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
                    res[prop] = {};
                    extend(res[prop], parentConfig[prop]);
                    extend(res[prop], childConfig[prop]);
                } else if (childConfig[prop] != null) {
                    res[prop] = childConfig[prop];
                } else {
                    delete res[prop];
                }
            }
        }
        return res;
    }

    function Locale(config) {
        if (config != null) {
            this.set(config);
        }
    }

    var keys;

    if (Object.keys) {
        keys = Object.keys;
    } else {
        keys = function (obj) {
            var i, res = [];
            for (i in obj) {
                if (hasOwnProp(obj, i)) {
                    res.push(i);
                }
            }
            return res;
        };
    }

    // internal storage for locale config files
    var locales = {};
    var globalLocale;

    function normalizeLocale(key) {
        return key ? key.toLowerCase().replace('_', '-') : key;
    }

    // pick the locale from the array
    // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
    // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
    function chooseLocale(names) {
        var i = 0, j, next, locale, split;

        while (i < names.length) {
            split = normalizeLocale(names[i]).split('-');
            j = split.length;
            next = normalizeLocale(names[i + 1]);
            next = next ? next.split('-') : null;
            while (j > 0) {
                locale = loadLocale(split.slice(0, j).join('-'));
                if (locale) {
                    return locale;
                }
                if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
                    //the next array item is better than a shallower substring of this one
                    break;
                }
                j--;
            }
            i++;
        }
        return null;
    }

    function loadLocale(name) {
        var oldLocale = null;
        // TODO: Find a better way to register and load all the locales in Node
        if (!locales[name] && (typeof module !== 'undefined') &&
                module && module.exports) {
            try {
                oldLocale = globalLocale._abbr;
                require('./locale/' + name);
                // because defineLocale currently also sets the global locale, we
                // want to undo that for lazy loaded locales
                locale_locales__getSetGlobalLocale(oldLocale);
            } catch (e) { }
        }
        return locales[name];
    }

    // This function will load locale and then set the global locale.  If
    // no arguments are passed in, it will simply return the current global
    // locale key.
    function locale_locales__getSetGlobalLocale (key, values) {
        var data;
        if (key) {
            if (isUndefined(values)) {
                data = locale_locales__getLocale(key);
            }
            else {
                data = defineLocale(key, values);
            }

            if (data) {
                // moment.duration._locale = moment._locale = data;
                globalLocale = data;
            }
        }

        return globalLocale._abbr;
    }

    function defineLocale (name, config) {
        if (config !== null) {
            config.abbr = name;
            if (locales[name] != null) {
                deprecateSimple('defineLocaleOverride',
                        'use moment.updateLocale(localeName, config) to change ' +
                        'an existing locale. moment.defineLocale(localeName, ' +
                        'config) should only be used for creating a new locale');
                config = mergeConfigs(locales[name]._config, config);
            } else if (config.parentLocale != null) {
                if (locales[config.parentLocale] != null) {
                    config = mergeConfigs(locales[config.parentLocale]._config, config);
                } else {
                    // treat as if there is no base config
                    deprecateSimple('parentLocaleUndefined',
                            'specified parentLocale is not defined yet');
                }
            }
            locales[name] = new Locale(config);

            // backwards compat for now: also set the locale
            locale_locales__getSetGlobalLocale(name);

            return locales[name];
        } else {
            // useful for testing
            delete locales[name];
            return null;
        }
    }

    function updateLocale(name, config) {
        if (config != null) {
            var locale;
            if (locales[name] != null) {
                config = mergeConfigs(locales[name]._config, config);
            }
            locale = new Locale(config);
            locale.parentLocale = locales[name];
            locales[name] = locale;

            // backwards compat for now: also set the locale
            locale_locales__getSetGlobalLocale(name);
        } else {
            // pass null for config to unupdate, useful for tests
            if (locales[name] != null) {
                if (locales[name].parentLocale != null) {
                    locales[name] = locales[name].parentLocale;
                } else if (locales[name] != null) {
                    delete locales[name];
                }
            }
        }
        return locales[name];
    }

    // returns locale data
    function locale_locales__getLocale (key) {
        var locale;

        if (key && key._locale && key._locale._abbr) {
            key = key._locale._abbr;
        }

        if (!key) {
            return globalLocale;
        }

        if (!isArray(key)) {
            //short-circuit everything else
            locale = loadLocale(key);
            if (locale) {
                return locale;
            }
            key = [key];
        }

        return chooseLocale(key);
    }

    function locale_locales__listLocales() {
        return keys(locales);
    }

    var aliases = {};

    function addUnitAlias (unit, shorthand) {
        var lowerCase = unit.toLowerCase();
        aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
    }

    function normalizeUnits(units) {
        return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
    }

    function normalizeObjectUnits(inputObject) {
        var normalizedInput = {},
            normalizedProp,
            prop;

        for (prop in inputObject) {
            if (hasOwnProp(inputObject, prop)) {
                normalizedProp = normalizeUnits(prop);
                if (normalizedProp) {
                    normalizedInput[normalizedProp] = inputObject[prop];
                }
            }
        }

        return normalizedInput;
    }

    function makeGetSet (unit, keepTime) {
        return function (value) {
            if (value != null) {
                get_set__set(this, unit, value);
                utils_hooks__hooks.updateOffset(this, keepTime);
                return this;
            } else {
                return get_set__get(this, unit);
            }
        };
    }

    function get_set__get (mom, unit) {
        return mom.isValid() ?
            mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
    }

    function get_set__set (mom, unit, value) {
        if (mom.isValid()) {
            mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
        }
    }

    // MOMENTS

    function getSet (units, value) {
        var unit;
        if (typeof units === 'object') {
            for (unit in units) {
                this.set(unit, units[unit]);
            }
        } else {
            units = normalizeUnits(units);
            if (isFunction(this[units])) {
                return this[units](value);
            }
        }
        return this;
    }

    function zeroFill(number, targetLength, forceSign) {
        var absNumber = '' + Math.abs(number),
            zerosToFill = targetLength - absNumber.length,
            sign = number >= 0;
        return (sign ? (forceSign ? '+' : '') : '-') +
            Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
    }

    var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;

    var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;

    var formatFunctions = {};

    var formatTokenFunctions = {};

    // token:    'M'
    // padded:   ['MM', 2]
    // ordinal:  'Mo'
    // callback: function () { this.month() + 1 }
    function addFormatToken (token, padded, ordinal, callback) {
        var func = callback;
        if (typeof callback === 'string') {
            func = function () {
                return this[callback]();
            };
        }
        if (token) {
            formatTokenFunctions[token] = func;
        }
        if (padded) {
            formatTokenFunctions[padded[0]] = function () {
                return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
            };
        }
        if (ordinal) {
            formatTokenFunctions[ordinal] = function () {
                return this.localeData().ordinal(func.apply(this, arguments), token);
            };
        }
    }

    function removeFormattingTokens(input) {
        if (input.match(/\[[\s\S]/)) {
            return input.replace(/^\[|\]$/g, '');
        }
        return input.replace(/\\/g, '');
    }

    function makeFormatFunction(format) {
        var array = format.match(formattingTokens), i, length;

        for (i = 0, length = array.length; i < length; i++) {
            if (formatTokenFunctions[array[i]]) {
                array[i] = formatTokenFunctions[array[i]];
            } else {
                array[i] = removeFormattingTokens(array[i]);
            }
        }

        return function (mom) {
            var output = '', i;
            for (i = 0; i < length; i++) {
                output += array[i] instanceof Function ? array[i].call(mom, format) : array[i];
            }
            return output;
        };
    }

    // format date using native date object
    function formatMoment(m, format) {
        if (!m.isValid()) {
            return m.localeData().invalidDate();
        }

        format = expandFormat(format, m.localeData());
        formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);

        return formatFunctions[format](m);
    }

    function expandFormat(format, locale) {
        var i = 5;

        function replaceLongDateFormatTokens(input) {
            return locale.longDateFormat(input) || input;
        }

        localFormattingTokens.lastIndex = 0;
        while (i >= 0 && localFormattingTokens.test(format)) {
            format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
            localFormattingTokens.lastIndex = 0;
            i -= 1;
        }

        return format;
    }

    var match1         = /\d/;            //       0 - 9
    var match2         = /\d\d/;          //      00 - 99
    var match3         = /\d{3}/;         //     000 - 999
    var match4         = /\d{4}/;         //    0000 - 9999
    var match6         = /[+-]?\d{6}/;    // -999999 - 999999
    var match1to2      = /\d\d?/;         //       0 - 99
    var match3to4      = /\d\d\d\d?/;     //     999 - 9999
    var match5to6      = /\d\d\d\d\d\d?/; //   99999 - 999999
    var match1to3      = /\d{1,3}/;       //       0 - 999
    var match1to4      = /\d{1,4}/;       //       0 - 9999
    var match1to6      = /[+-]?\d{1,6}/;  // -999999 - 999999

    var matchUnsigned  = /\d+/;           //       0 - inf
    var matchSigned    = /[+-]?\d+/;      //    -inf - inf

    var matchOffset    = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
    var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z

    var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123

    // any word (or two) characters or numbers including two/three word month in arabic.
    // includes scottish gaelic two word and hyphenated months
    var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;


    var regexes = {};

    function addRegexToken (token, regex, strictRegex) {
        regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
            return (isStrict && strictRegex) ? strictRegex : regex;
        };
    }

    function getParseRegexForToken (token, config) {
        if (!hasOwnProp(regexes, token)) {
            return new RegExp(unescapeFormat(token));
        }

        return regexes[token](config._strict, config._locale);
    }

    // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
    function unescapeFormat(s) {
        return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
            return p1 || p2 || p3 || p4;
        }));
    }

    function regexEscape(s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }

    var tokens = {};

    function addParseToken (token, callback) {
        var i, func = callback;
        if (typeof token === 'string') {
            token = [token];
        }
        if (typeof callback === 'number') {
            func = function (input, array) {
                array[callback] = toInt(input);
            };
        }
        for (i = 0; i < token.length; i++) {
            tokens[token[i]] = func;
        }
    }

    function addWeekParseToken (token, callback) {
        addParseToken(token, function (input, array, config, token) {
            config._w = config._w || {};
            callback(input, config._w, config, token);
        });
    }

    function addTimeToArrayFromToken(token, input, config) {
        if (input != null && hasOwnProp(tokens, token)) {
            tokens[token](input, config._a, config, token);
        }
    }

    var YEAR = 0;
    var MONTH = 1;
    var DATE = 2;
    var HOUR = 3;
    var MINUTE = 4;
    var SECOND = 5;
    var MILLISECOND = 6;
    var WEEK = 7;
    var WEEKDAY = 8;

    var indexOf;

    if (Array.prototype.indexOf) {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function (o) {
            // I know
            var i;
            for (i = 0; i < this.length; ++i) {
                if (this[i] === o) {
                    return i;
                }
            }
            return -1;
        };
    }

    function daysInMonth(year, month) {
        return new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
    }

    // FORMATTING

    addFormatToken('M', ['MM', 2], 'Mo', function () {
        return this.month() + 1;
    });

    addFormatToken('MMM', 0, 0, function (format) {
        return this.localeData().monthsShort(this, format);
    });

    addFormatToken('MMMM', 0, 0, function (format) {
        return this.localeData().months(this, format);
    });

    // ALIASES

    addUnitAlias('month', 'M');

    // PARSING

    addRegexToken('M',    match1to2);
    addRegexToken('MM',   match1to2, match2);
    addRegexToken('MMM',  function (isStrict, locale) {
        return locale.monthsShortRegex(isStrict);
    });
    addRegexToken('MMMM', function (isStrict, locale) {
        return locale.monthsRegex(isStrict);
    });

    addParseToken(['M', 'MM'], function (input, array) {
        array[MONTH] = toInt(input) - 1;
    });

    addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
        var month = config._locale.monthsParse(input, token, config._strict);
        // if we didn't find a month name, mark the date as invalid.
        if (month != null) {
            array[MONTH] = month;
        } else {
            getParsingFlags(config).invalidMonth = input;
        }
    });

    // LOCALES

    var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/;
    var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
    function localeMonths (m, format) {
        return isArray(this._months) ? this._months[m.month()] :
            this._months[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
    }

    var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
    function localeMonthsShort (m, format) {
        return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
            this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
    }

    function units_month__handleStrictParse(monthName, format, strict) {
        var i, ii, mom, llc = monthName.toLocaleLowerCase();
        if (!this._monthsParse) {
            // this is not used
            this._monthsParse = [];
            this._longMonthsParse = [];
            this._shortMonthsParse = [];
            for (i = 0; i < 12; ++i) {
                mom = create_utc__createUTC([2000, i]);
                this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
                this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
            }
        }

        if (strict) {
            if (format === 'MMM') {
                ii = indexOf.call(this._shortMonthsParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf.call(this._longMonthsParse, llc);
                return ii !== -1 ? ii : null;
            }
        } else {
            if (format === 'MMM') {
                ii = indexOf.call(this._shortMonthsParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._longMonthsParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf.call(this._longMonthsParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._shortMonthsParse, llc);
                return ii !== -1 ? ii : null;
            }
        }
    }

    function localeMonthsParse (monthName, format, strict) {
        var i, mom, regex;

        if (this._monthsParseExact) {
            return units_month__handleStrictParse.call(this, monthName, format, strict);
        }

        if (!this._monthsParse) {
            this._monthsParse = [];
            this._longMonthsParse = [];
            this._shortMonthsParse = [];
        }

        // TODO: add sorting
        // Sorting makes sure if one month (or abbr) is a prefix of another
        // see sorting in computeMonthsParse
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = create_utc__createUTC([2000, i]);
            if (strict && !this._longMonthsParse[i]) {
                this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
                this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
            }
            if (!strict && !this._monthsParse[i]) {
                regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
                this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
                return i;
            } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
                return i;
            } else if (!strict && this._monthsParse[i].test(monthName)) {
                return i;
            }
        }
    }

    // MOMENTS

    function setMonth (mom, value) {
        var dayOfMonth;

        if (!mom.isValid()) {
            // No op
            return mom;
        }

        if (typeof value === 'string') {
            if (/^\d+$/.test(value)) {
                value = toInt(value);
            } else {
                value = mom.localeData().monthsParse(value);
                // TODO: Another silent failure?
                if (typeof value !== 'number') {
                    return mom;
                }
            }
        }

        dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
        return mom;
    }

    function getSetMonth (value) {
        if (value != null) {
            setMonth(this, value);
            utils_hooks__hooks.updateOffset(this, true);
            return this;
        } else {
            return get_set__get(this, 'Month');
        }
    }

    function getDaysInMonth () {
        return daysInMonth(this.year(), this.month());
    }

    var defaultMonthsShortRegex = matchWord;
    function monthsShortRegex (isStrict) {
        if (this._monthsParseExact) {
            if (!hasOwnProp(this, '_monthsRegex')) {
                computeMonthsParse.call(this);
            }
            if (isStrict) {
                return this._monthsShortStrictRegex;
            } else {
                return this._monthsShortRegex;
            }
        } else {
            return this._monthsShortStrictRegex && isStrict ?
                this._monthsShortStrictRegex : this._monthsShortRegex;
        }
    }

    var defaultMonthsRegex = matchWord;
    function monthsRegex (isStrict) {
        if (this._monthsParseExact) {
            if (!hasOwnProp(this, '_monthsRegex')) {
                computeMonthsParse.call(this);
            }
            if (isStrict) {
                return this._monthsStrictRegex;
            } else {
                return this._monthsRegex;
            }
        } else {
            return this._monthsStrictRegex && isStrict ?
                this._monthsStrictRegex : this._monthsRegex;
        }
    }

    function computeMonthsParse () {
        function cmpLenRev(a, b) {
            return b.length - a.length;
        }

        var shortPieces = [], longPieces = [], mixedPieces = [],
            i, mom;
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = create_utc__createUTC([2000, i]);
            shortPieces.push(this.monthsShort(mom, ''));
            longPieces.push(this.months(mom, ''));
            mixedPieces.push(this.months(mom, ''));
            mixedPieces.push(this.monthsShort(mom, ''));
        }
        // Sorting makes sure if one month (or abbr) is a prefix of another it
        // will match the longer piece.
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        for (i = 0; i < 12; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
        this._monthsShortRegex = this._monthsRegex;
        this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
        this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
    }

    function checkOverflow (m) {
        var overflow;
        var a = m._a;

        if (a && getParsingFlags(m).overflow === -2) {
            overflow =
                a[MONTH]       < 0 || a[MONTH]       > 11  ? MONTH :
                a[DATE]        < 1 || a[DATE]        > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
                a[HOUR]        < 0 || a[HOUR]        > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
                a[MINUTE]      < 0 || a[MINUTE]      > 59  ? MINUTE :
                a[SECOND]      < 0 || a[SECOND]      > 59  ? SECOND :
                a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
                -1;

            if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
                overflow = DATE;
            }
            if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
                overflow = WEEK;
            }
            if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
                overflow = WEEKDAY;
            }

            getParsingFlags(m).overflow = overflow;
        }

        return m;
    }

    // iso 8601 regex
    // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
    var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/;
    var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/;

    var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;

    var isoDates = [
        ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
        ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
        ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
        ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
        ['YYYY-DDD', /\d{4}-\d{3}/],
        ['YYYY-MM', /\d{4}-\d\d/, false],
        ['YYYYYYMMDD', /[+-]\d{10}/],
        ['YYYYMMDD', /\d{8}/],
        // YYYYMM is NOT allowed by the standard
        ['GGGG[W]WWE', /\d{4}W\d{3}/],
        ['GGGG[W]WW', /\d{4}W\d{2}/, false],
        ['YYYYDDD', /\d{7}/]
    ];

    // iso time formats and regexes
    var isoTimes = [
        ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
        ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
        ['HH:mm:ss', /\d\d:\d\d:\d\d/],
        ['HH:mm', /\d\d:\d\d/],
        ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
        ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
        ['HHmmss', /\d\d\d\d\d\d/],
        ['HHmm', /\d\d\d\d/],
        ['HH', /\d\d/]
    ];

    var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;

    // date from iso format
    function configFromISO(config) {
        var i, l,
            string = config._i,
            match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
            allowTime, dateFormat, timeFormat, tzFormat;

        if (match) {
            getParsingFlags(config).iso = true;

            for (i = 0, l = isoDates.length; i < l; i++) {
                if (isoDates[i][1].exec(match[1])) {
                    dateFormat = isoDates[i][0];
                    allowTime = isoDates[i][2] !== false;
                    break;
                }
            }
            if (dateFormat == null) {
                config._isValid = false;
                return;
            }
            if (match[3]) {
                for (i = 0, l = isoTimes.length; i < l; i++) {
                    if (isoTimes[i][1].exec(match[3])) {
                        // match[2] should be 'T' or space
                        timeFormat = (match[2] || ' ') + isoTimes[i][0];
                        break;
                    }
                }
                if (timeFormat == null) {
                    config._isValid = false;
                    return;
                }
            }
            if (!allowTime && timeFormat != null) {
                config._isValid = false;
                return;
            }
            if (match[4]) {
                if (tzRegex.exec(match[4])) {
                    tzFormat = 'Z';
                } else {
                    config._isValid = false;
                    return;
                }
            }
            config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
            configFromStringAndFormat(config);
        } else {
            config._isValid = false;
        }
    }

    // date from iso format or fallback
    function configFromString(config) {
        var matched = aspNetJsonRegex.exec(config._i);

        if (matched !== null) {
            config._d = new Date(+matched[1]);
            return;
        }

        configFromISO(config);
        if (config._isValid === false) {
            delete config._isValid;
            utils_hooks__hooks.createFromInputFallback(config);
        }
    }

    utils_hooks__hooks.createFromInputFallback = deprecate(
        'moment construction falls back to js Date. This is ' +
        'discouraged and will be removed in upcoming major ' +
        'release. Please refer to ' +
        'https://github.com/moment/moment/issues/1407 for more info.',
        function (config) {
            config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
        }
    );

    function createDate (y, m, d, h, M, s, ms) {
        //can't just apply() to create a date:
        //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply
        var date = new Date(y, m, d, h, M, s, ms);

        //the date constructor remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
            date.setFullYear(y);
        }
        return date;
    }

    function createUTCDate (y) {
        var date = new Date(Date.UTC.apply(null, arguments));

        //the Date.UTC function remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
            date.setUTCFullYear(y);
        }
        return date;
    }

    // FORMATTING

    addFormatToken('Y', 0, 0, function () {
        var y = this.year();
        return y <= 9999 ? '' + y : '+' + y;
    });

    addFormatToken(0, ['YY', 2], 0, function () {
        return this.year() % 100;
    });

    addFormatToken(0, ['YYYY',   4],       0, 'year');
    addFormatToken(0, ['YYYYY',  5],       0, 'year');
    addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');

    // ALIASES

    addUnitAlias('year', 'y');

    // PARSING

    addRegexToken('Y',      matchSigned);
    addRegexToken('YY',     match1to2, match2);
    addRegexToken('YYYY',   match1to4, match4);
    addRegexToken('YYYYY',  match1to6, match6);
    addRegexToken('YYYYYY', match1to6, match6);

    addParseToken(['YYYYY', 'YYYYYY'], YEAR);
    addParseToken('YYYY', function (input, array) {
        array[YEAR] = input.length === 2 ? utils_hooks__hooks.parseTwoDigitYear(input) : toInt(input);
    });
    addParseToken('YY', function (input, array) {
        array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input);
    });
    addParseToken('Y', function (input, array) {
        array[YEAR] = parseInt(input, 10);
    });

    // HELPERS

    function daysInYear(year) {
        return isLeapYear(year) ? 366 : 365;
    }

    function isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }

    // HOOKS

    utils_hooks__hooks.parseTwoDigitYear = function (input) {
        return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
    };

    // MOMENTS

    var getSetYear = makeGetSet('FullYear', true);

    function getIsLeapYear () {
        return isLeapYear(this.year());
    }

    // start-of-first-week - start-of-year
    function firstWeekOffset(year, dow, doy) {
        var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
            fwd = 7 + dow - doy,
            // first-week day local weekday -- which local weekday is fwd
            fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;

        return -fwdlw + fwd - 1;
    }

    //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
    function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
        var localWeekday = (7 + weekday - dow) % 7,
            weekOffset = firstWeekOffset(year, dow, doy),
            dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
            resYear, resDayOfYear;

        if (dayOfYear <= 0) {
            resYear = year - 1;
            resDayOfYear = daysInYear(resYear) + dayOfYear;
        } else if (dayOfYear > daysInYear(year)) {
            resYear = year + 1;
            resDayOfYear = dayOfYear - daysInYear(year);
        } else {
            resYear = year;
            resDayOfYear = dayOfYear;
        }

        return {
            year: resYear,
            dayOfYear: resDayOfYear
        };
    }

    function weekOfYear(mom, dow, doy) {
        var weekOffset = firstWeekOffset(mom.year(), dow, doy),
            week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
            resWeek, resYear;

        if (week < 1) {
            resYear = mom.year() - 1;
            resWeek = week + weeksInYear(resYear, dow, doy);
        } else if (week > weeksInYear(mom.year(), dow, doy)) {
            resWeek = week - weeksInYear(mom.year(), dow, doy);
            resYear = mom.year() + 1;
        } else {
            resYear = mom.year();
            resWeek = week;
        }

        return {
            week: resWeek,
            year: resYear
        };
    }

    function weeksInYear(year, dow, doy) {
        var weekOffset = firstWeekOffset(year, dow, doy),
            weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
        return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
    }

    // Pick the first defined of two or three arguments.
    function defaults(a, b, c) {
        if (a != null) {
            return a;
        }
        if (b != null) {
            return b;
        }
        return c;
    }

    function currentDateArray(config) {
        // hooks is actually the exported moment object
        var nowValue = new Date(utils_hooks__hooks.now());
        if (config._useUTC) {
            return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
        }
        return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
    }

    // convert an array to a date.
    // the array should mirror the parameters below
    // note: all values past the year are optional and will default to the lowest possible value.
    // [year, month, day , hour, minute, second, millisecond]
    function configFromArray (config) {
        var i, date, input = [], currentDate, yearToUse;

        if (config._d) {
            return;
        }

        currentDate = currentDateArray(config);

        //compute day of the year from weeks and weekdays
        if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
            dayOfYearFromWeekInfo(config);
        }

        //if the day of the year is set, figure out what it is
        if (config._dayOfYear) {
            yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);

            if (config._dayOfYear > daysInYear(yearToUse)) {
                getParsingFlags(config)._overflowDayOfYear = true;
            }

            date = createUTCDate(yearToUse, 0, config._dayOfYear);
            config._a[MONTH] = date.getUTCMonth();
            config._a[DATE] = date.getUTCDate();
        }

        // Default to current date.
        // * if no year, month, day of month are given, default to today
        // * if day of month is given, default month and year
        // * if month is given, default only year
        // * if year is given, don't default anything
        for (i = 0; i < 3 && config._a[i] == null; ++i) {
            config._a[i] = input[i] = currentDate[i];
        }

        // Zero out whatever was not defaulted, including time
        for (; i < 7; i++) {
            config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
        }

        // Check for 24:00:00.000
        if (config._a[HOUR] === 24 &&
                config._a[MINUTE] === 0 &&
                config._a[SECOND] === 0 &&
                config._a[MILLISECOND] === 0) {
            config._nextDay = true;
            config._a[HOUR] = 0;
        }

        config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
        // Apply timezone offset from input. The actual utcOffset can be changed
        // with parseZone.
        if (config._tzm != null) {
            config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
        }

        if (config._nextDay) {
            config._a[HOUR] = 24;
        }
    }

    function dayOfYearFromWeekInfo(config) {
        var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;

        w = config._w;
        if (w.GG != null || w.W != null || w.E != null) {
            dow = 1;
            doy = 4;

            // TODO: We need to take the current isoWeekYear, but that depends on
            // how we interpret now (local, utc, fixed offset). So create
            // a now version of current config (take local/utc/offset flags, and
            // create now).
            weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year);
            week = defaults(w.W, 1);
            weekday = defaults(w.E, 1);
            if (weekday < 1 || weekday > 7) {
                weekdayOverflow = true;
            }
        } else {
            dow = config._locale._week.dow;
            doy = config._locale._week.doy;

            weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year);
            week = defaults(w.w, 1);

            if (w.d != null) {
                // weekday -- low day numbers are considered next week
                weekday = w.d;
                if (weekday < 0 || weekday > 6) {
                    weekdayOverflow = true;
                }
            } else if (w.e != null) {
                // local weekday -- counting starts from begining of week
                weekday = w.e + dow;
                if (w.e < 0 || w.e > 6) {
                    weekdayOverflow = true;
                }
            } else {
                // default to begining of week
                weekday = dow;
            }
        }
        if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
            getParsingFlags(config)._overflowWeeks = true;
        } else if (weekdayOverflow != null) {
            getParsingFlags(config)._overflowWeekday = true;
        } else {
            temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
            config._a[YEAR] = temp.year;
            config._dayOfYear = temp.dayOfYear;
        }
    }

    // constant that refers to the ISO standard
    utils_hooks__hooks.ISO_8601 = function () {};

    // date from string and format string
    function configFromStringAndFormat(config) {
        // TODO: Move this to another part of the creation flow to prevent circular deps
        if (config._f === utils_hooks__hooks.ISO_8601) {
            configFromISO(config);
            return;
        }

        config._a = [];
        getParsingFlags(config).empty = true;

        // This array is used to make a Date, either with `new Date` or `Date.UTC`
        var string = '' + config._i,
            i, parsedInput, tokens, token, skipped,
            stringLength = string.length,
            totalParsedInputLength = 0;

        tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];

        for (i = 0; i < tokens.length; i++) {
            token = tokens[i];
            parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
            // console.log('token', token, 'parsedInput', parsedInput,
            //         'regex', getParseRegexForToken(token, config));
            if (parsedInput) {
                skipped = string.substr(0, string.indexOf(parsedInput));
                if (skipped.length > 0) {
                    getParsingFlags(config).unusedInput.push(skipped);
                }
                string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
                totalParsedInputLength += parsedInput.length;
            }
            // don't parse if it's not a known token
            if (formatTokenFunctions[token]) {
                if (parsedInput) {
                    getParsingFlags(config).empty = false;
                }
                else {
                    getParsingFlags(config).unusedTokens.push(token);
                }
                addTimeToArrayFromToken(token, parsedInput, config);
            }
            else if (config._strict && !parsedInput) {
                getParsingFlags(config).unusedTokens.push(token);
            }
        }

        // add remaining unparsed input length to the string
        getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
        if (string.length > 0) {
            getParsingFlags(config).unusedInput.push(string);
        }

        // clear _12h flag if hour is <= 12
        if (getParsingFlags(config).bigHour === true &&
                config._a[HOUR] <= 12 &&
                config._a[HOUR] > 0) {
            getParsingFlags(config).bigHour = undefined;
        }

        getParsingFlags(config).parsedDateParts = config._a.slice(0);
        getParsingFlags(config).meridiem = config._meridiem;
        // handle meridiem
        config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);

        configFromArray(config);
        checkOverflow(config);
    }


    function meridiemFixWrap (locale, hour, meridiem) {
        var isPm;

        if (meridiem == null) {
            // nothing to do
            return hour;
        }
        if (locale.meridiemHour != null) {
            return locale.meridiemHour(hour, meridiem);
        } else if (locale.isPM != null) {
            // Fallback
            isPm = locale.isPM(meridiem);
            if (isPm && hour < 12) {
                hour += 12;
            }
            if (!isPm && hour === 12) {
                hour = 0;
            }
            return hour;
        } else {
            // this is not supposed to happen
            return hour;
        }
    }

    // date from string and array of format strings
    function configFromStringAndArray(config) {
        var tempConfig,
            bestMoment,

            scoreToBeat,
            i,
            currentScore;

        if (config._f.length === 0) {
            getParsingFlags(config).invalidFormat = true;
            config._d = new Date(NaN);
            return;
        }

        for (i = 0; i < config._f.length; i++) {
            currentScore = 0;
            tempConfig = copyConfig({}, config);
            if (config._useUTC != null) {
                tempConfig._useUTC = config._useUTC;
            }
            tempConfig._f = config._f[i];
            configFromStringAndFormat(tempConfig);

            if (!valid__isValid(tempConfig)) {
                continue;
            }

            // if there is any input that was not parsed add a penalty for that format
            currentScore += getParsingFlags(tempConfig).charsLeftOver;

            //or tokens
            currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;

            getParsingFlags(tempConfig).score = currentScore;

            if (scoreToBeat == null || currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempConfig;
            }
        }

        extend(config, bestMoment || tempConfig);
    }

    function configFromObject(config) {
        if (config._d) {
            return;
        }

        var i = normalizeObjectUnits(config._i);
        config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
            return obj && parseInt(obj, 10);
        });

        configFromArray(config);
    }

    function createFromConfig (config) {
        var res = new Moment(checkOverflow(prepareConfig(config)));
        if (res._nextDay) {
            // Adding is smart enough around DST
            res.add(1, 'd');
            res._nextDay = undefined;
        }

        return res;
    }

    function prepareConfig (config) {
        var input = config._i,
            format = config._f;

        config._locale = config._locale || locale_locales__getLocale(config._l);

        if (input === null || (format === undefined && input === '')) {
            return valid__createInvalid({nullInput: true});
        }

        if (typeof input === 'string') {
            config._i = input = config._locale.preparse(input);
        }

        if (isMoment(input)) {
            return new Moment(checkOverflow(input));
        } else if (isArray(format)) {
            configFromStringAndArray(config);
        } else if (format) {
            configFromStringAndFormat(config);
        } else if (isDate(input)) {
            config._d = input;
        } else {
            configFromInput(config);
        }

        if (!valid__isValid(config)) {
            config._d = null;
        }

        return config;
    }

    function configFromInput(config) {
        var input = config._i;
        if (input === undefined) {
            config._d = new Date(utils_hooks__hooks.now());
        } else if (isDate(input)) {
            config._d = new Date(input.valueOf());
        } else if (typeof input === 'string') {
            configFromString(config);
        } else if (isArray(input)) {
            config._a = map(input.slice(0), function (obj) {
                return parseInt(obj, 10);
            });
            configFromArray(config);
        } else if (typeof(input) === 'object') {
            configFromObject(config);
        } else if (typeof(input) === 'number') {
            // from milliseconds
            config._d = new Date(input);
        } else {
            utils_hooks__hooks.createFromInputFallback(config);
        }
    }

    function createLocalOrUTC (input, format, locale, strict, isUTC) {
        var c = {};

        if (typeof(locale) === 'boolean') {
            strict = locale;
            locale = undefined;
        }
        // object construction must be done this way.
        // https://github.com/moment/moment/issues/1423
        c._isAMomentObject = true;
        c._useUTC = c._isUTC = isUTC;
        c._l = locale;
        c._i = input;
        c._f = format;
        c._strict = strict;

        return createFromConfig(c);
    }

    function local__createLocal (input, format, locale, strict) {
        return createLocalOrUTC(input, format, locale, strict, false);
    }

    var prototypeMin = deprecate(
         'moment().min is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548',
         function () {
             var other = local__createLocal.apply(null, arguments);
             if (this.isValid() && other.isValid()) {
                 return other < this ? this : other;
             } else {
                 return valid__createInvalid();
             }
         }
     );

    var prototypeMax = deprecate(
        'moment().max is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548',
        function () {
            var other = local__createLocal.apply(null, arguments);
            if (this.isValid() && other.isValid()) {
                return other > this ? this : other;
            } else {
                return valid__createInvalid();
            }
        }
    );

    // Pick a moment m from moments so that m[fn](other) is true for all
    // other. This relies on the function fn to be transitive.
    //
    // moments should either be an array of moment objects or an array, whose
    // first element is an array of moment objects.
    function pickBy(fn, moments) {
        var res, i;
        if (moments.length === 1 && isArray(moments[0])) {
            moments = moments[0];
        }
        if (!moments.length) {
            return local__createLocal();
        }
        res = moments[0];
        for (i = 1; i < moments.length; ++i) {
            if (!moments[i].isValid() || moments[i][fn](res)) {
                res = moments[i];
            }
        }
        return res;
    }

    // TODO: Use [].sort instead?
    function min () {
        var args = [].slice.call(arguments, 0);

        return pickBy('isBefore', args);
    }

    function max () {
        var args = [].slice.call(arguments, 0);

        return pickBy('isAfter', args);
    }

    var now = function () {
        return Date.now ? Date.now() : +(new Date());
    };

    function Duration (duration) {
        var normalizedInput = normalizeObjectUnits(duration),
            years = normalizedInput.year || 0,
            quarters = normalizedInput.quarter || 0,
            months = normalizedInput.month || 0,
            weeks = normalizedInput.week || 0,
            days = normalizedInput.day || 0,
            hours = normalizedInput.hour || 0,
            minutes = normalizedInput.minute || 0,
            seconds = normalizedInput.second || 0,
            milliseconds = normalizedInput.millisecond || 0;

        // representation for dateAddRemove
        this._milliseconds = +milliseconds +
            seconds * 1e3 + // 1000
            minutes * 6e4 + // 1000 * 60
            hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
        // Because of dateAddRemove treats 24 hours as different from a
        // day when working around DST, we need to store them separately
        this._days = +days +
            weeks * 7;
        // It is impossible translate months into days without knowing
        // which months you are are talking about, so we have to store
        // it separately.
        this._months = +months +
            quarters * 3 +
            years * 12;

        this._data = {};

        this._locale = locale_locales__getLocale();

        this._bubble();
    }

    function isDuration (obj) {
        return obj instanceof Duration;
    }

    // FORMATTING

    function offset (token, separator) {
        addFormatToken(token, 0, 0, function () {
            var offset = this.utcOffset();
            var sign = '+';
            if (offset < 0) {
                offset = -offset;
                sign = '-';
            }
            return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
        });
    }

    offset('Z', ':');
    offset('ZZ', '');

    // PARSING

    addRegexToken('Z',  matchShortOffset);
    addRegexToken('ZZ', matchShortOffset);
    addParseToken(['Z', 'ZZ'], function (input, array, config) {
        config._useUTC = true;
        config._tzm = offsetFromString(matchShortOffset, input);
    });

    // HELPERS

    // timezone chunker
    // '+10:00' > ['10',  '00']
    // '-1530'  > ['-15', '30']
    var chunkOffset = /([\+\-]|\d\d)/gi;

    function offsetFromString(matcher, string) {
        var matches = ((string || '').match(matcher) || []);
        var chunk   = matches[matches.length - 1] || [];
        var parts   = (chunk + '').match(chunkOffset) || ['-', 0, 0];
        var minutes = +(parts[1] * 60) + toInt(parts[2]);

        return parts[0] === '+' ? minutes : -minutes;
    }

    // Return a moment from input, that is local/utc/zone equivalent to model.
    function cloneWithOffset(input, model) {
        var res, diff;
        if (model._isUTC) {
            res = model.clone();
            diff = (isMoment(input) || isDate(input) ? input.valueOf() : local__createLocal(input).valueOf()) - res.valueOf();
            // Use low-level api, because this fn is low-level api.
            res._d.setTime(res._d.valueOf() + diff);
            utils_hooks__hooks.updateOffset(res, false);
            return res;
        } else {
            return local__createLocal(input).local();
        }
    }

    function getDateOffset (m) {
        // On Firefox.24 Date#getTimezoneOffset returns a floating point.
        // https://github.com/moment/moment/pull/1871
        return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
    }

    // HOOKS

    // This function will be called whenever a moment is mutated.
    // It is intended to keep the offset in sync with the timezone.
    utils_hooks__hooks.updateOffset = function () {};

    // MOMENTS

    // keepLocalTime = true means only change the timezone, without
    // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
    // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
    // +0200, so we adjust the time as needed, to be valid.
    //
    // Keeping the time actually adds/subtracts (one hour)
    // from the actual represented time. That is why we call updateOffset
    // a second time. In case it wants us to change the offset again
    // _changeInProgress == true case, then we have to adjust, because
    // there is no such time in the given timezone.
    function getSetOffset (input, keepLocalTime) {
        var offset = this._offset || 0,
            localAdjust;
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        if (input != null) {
            if (typeof input === 'string') {
                input = offsetFromString(matchShortOffset, input);
            } else if (Math.abs(input) < 16) {
                input = input * 60;
            }
            if (!this._isUTC && keepLocalTime) {
                localAdjust = getDateOffset(this);
            }
            this._offset = input;
            this._isUTC = true;
            if (localAdjust != null) {
                this.add(localAdjust, 'm');
            }
            if (offset !== input) {
                if (!keepLocalTime || this._changeInProgress) {
                    add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false);
                } else if (!this._changeInProgress) {
                    this._changeInProgress = true;
                    utils_hooks__hooks.updateOffset(this, true);
                    this._changeInProgress = null;
                }
            }
            return this;
        } else {
            return this._isUTC ? offset : getDateOffset(this);
        }
    }

    function getSetZone (input, keepLocalTime) {
        if (input != null) {
            if (typeof input !== 'string') {
                input = -input;
            }

            this.utcOffset(input, keepLocalTime);

            return this;
        } else {
            return -this.utcOffset();
        }
    }

    function setOffsetToUTC (keepLocalTime) {
        return this.utcOffset(0, keepLocalTime);
    }

    function setOffsetToLocal (keepLocalTime) {
        if (this._isUTC) {
            this.utcOffset(0, keepLocalTime);
            this._isUTC = false;

            if (keepLocalTime) {
                this.subtract(getDateOffset(this), 'm');
            }
        }
        return this;
    }

    function setOffsetToParsedOffset () {
        if (this._tzm) {
            this.utcOffset(this._tzm);
        } else if (typeof this._i === 'string') {
            this.utcOffset(offsetFromString(matchOffset, this._i));
        }
        return this;
    }

    function hasAlignedHourOffset (input) {
        if (!this.isValid()) {
            return false;
        }
        input = input ? local__createLocal(input).utcOffset() : 0;

        return (this.utcOffset() - input) % 60 === 0;
    }

    function isDaylightSavingTime () {
        return (
            this.utcOffset() > this.clone().month(0).utcOffset() ||
            this.utcOffset() > this.clone().month(5).utcOffset()
        );
    }

    function isDaylightSavingTimeShifted () {
        if (!isUndefined(this._isDSTShifted)) {
            return this._isDSTShifted;
        }

        var c = {};

        copyConfig(c, this);
        c = prepareConfig(c);

        if (c._a) {
            var other = c._isUTC ? create_utc__createUTC(c._a) : local__createLocal(c._a);
            this._isDSTShifted = this.isValid() &&
                compareArrays(c._a, other.toArray()) > 0;
        } else {
            this._isDSTShifted = false;
        }

        return this._isDSTShifted;
    }

    function isLocal () {
        return this.isValid() ? !this._isUTC : false;
    }

    function isUtcOffset () {
        return this.isValid() ? this._isUTC : false;
    }

    function isUtc () {
        return this.isValid() ? this._isUTC && this._offset === 0 : false;
    }

    // ASP.NET json date format regex
    var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/;

    // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
    // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
    // and further modified to allow for strings containing both week and day
    var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;

    function create__createDuration (input, key) {
        var duration = input,
            // matching against regexp is expensive, do it on demand
            match = null,
            sign,
            ret,
            diffRes;

        if (isDuration(input)) {
            duration = {
                ms : input._milliseconds,
                d  : input._days,
                M  : input._months
            };
        } else if (typeof input === 'number') {
            duration = {};
            if (key) {
                duration[key] = input;
            } else {
                duration.milliseconds = input;
            }
        } else if (!!(match = aspNetRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            duration = {
                y  : 0,
                d  : toInt(match[DATE])        * sign,
                h  : toInt(match[HOUR])        * sign,
                m  : toInt(match[MINUTE])      * sign,
                s  : toInt(match[SECOND])      * sign,
                ms : toInt(match[MILLISECOND]) * sign
            };
        } else if (!!(match = isoRegex.exec(input))) {
            sign = (match[1] === '-') ? -1 : 1;
            duration = {
                y : parseIso(match[2], sign),
                M : parseIso(match[3], sign),
                w : parseIso(match[4], sign),
                d : parseIso(match[5], sign),
                h : parseIso(match[6], sign),
                m : parseIso(match[7], sign),
                s : parseIso(match[8], sign)
            };
        } else if (duration == null) {// checks for null or undefined
            duration = {};
        } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
            diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to));

            duration = {};
            duration.ms = diffRes.milliseconds;
            duration.M = diffRes.months;
        }

        ret = new Duration(duration);

        if (isDuration(input) && hasOwnProp(input, '_locale')) {
            ret._locale = input._locale;
        }

        return ret;
    }

    create__createDuration.fn = Duration.prototype;

    function parseIso (inp, sign) {
        // We'd normally use ~~inp for this, but unfortunately it also
        // converts floats to ints.
        // inp may be undefined, so careful calling replace on it.
        var res = inp && parseFloat(inp.replace(',', '.'));
        // apply sign while we're at it
        return (isNaN(res) ? 0 : res) * sign;
    }

    function positiveMomentsDifference(base, other) {
        var res = {milliseconds: 0, months: 0};

        res.months = other.month() - base.month() +
            (other.year() - base.year()) * 12;
        if (base.clone().add(res.months, 'M').isAfter(other)) {
            --res.months;
        }

        res.milliseconds = +other - +(base.clone().add(res.months, 'M'));

        return res;
    }

    function momentsDifference(base, other) {
        var res;
        if (!(base.isValid() && other.isValid())) {
            return {milliseconds: 0, months: 0};
        }

        other = cloneWithOffset(other, base);
        if (base.isBefore(other)) {
            res = positiveMomentsDifference(base, other);
        } else {
            res = positiveMomentsDifference(other, base);
            res.milliseconds = -res.milliseconds;
            res.months = -res.months;
        }

        return res;
    }

    function absRound (number) {
        if (number < 0) {
            return Math.round(-1 * number) * -1;
        } else {
            return Math.round(number);
        }
    }

    // TODO: remove 'name' arg after deprecation is removed
    function createAdder(direction, name) {
        return function (val, period) {
            var dur, tmp;
            //invert the arguments, but complain about it
            if (period !== null && !isNaN(+period)) {
                deprecateSimple(name, 'moment().' + name  + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
                tmp = val; val = period; period = tmp;
            }

            val = typeof val === 'string' ? +val : val;
            dur = create__createDuration(val, period);
            add_subtract__addSubtract(this, dur, direction);
            return this;
        };
    }

    function add_subtract__addSubtract (mom, duration, isAdding, updateOffset) {
        var milliseconds = duration._milliseconds,
            days = absRound(duration._days),
            months = absRound(duration._months);

        if (!mom.isValid()) {
            // No op
            return;
        }

        updateOffset = updateOffset == null ? true : updateOffset;

        if (milliseconds) {
            mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
        }
        if (days) {
            get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding);
        }
        if (months) {
            setMonth(mom, get_set__get(mom, 'Month') + months * isAdding);
        }
        if (updateOffset) {
            utils_hooks__hooks.updateOffset(mom, days || months);
        }
    }

    var add_subtract__add      = createAdder(1, 'add');
    var add_subtract__subtract = createAdder(-1, 'subtract');

    function moment_calendar__calendar (time, formats) {
        // We want to compare the start of today, vs this.
        // Getting start-of-today depends on whether we're local/utc/offset or not.
        var now = time || local__createLocal(),
            sod = cloneWithOffset(now, this).startOf('day'),
            diff = this.diff(sod, 'days', true),
            format = diff < -6 ? 'sameElse' :
                diff < -1 ? 'lastWeek' :
                diff < 0 ? 'lastDay' :
                diff < 1 ? 'sameDay' :
                diff < 2 ? 'nextDay' :
                diff < 7 ? 'nextWeek' : 'sameElse';

        var output = formats && (isFunction(formats[format]) ? formats[format]() : formats[format]);

        return this.format(output || this.localeData().calendar(format, this, local__createLocal(now)));
    }

    function clone () {
        return new Moment(this);
    }

    function isAfter (input, units) {
        var localInput = isMoment(input) ? input : local__createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() > localInput.valueOf();
        } else {
            return localInput.valueOf() < this.clone().startOf(units).valueOf();
        }
    }

    function isBefore (input, units) {
        var localInput = isMoment(input) ? input : local__createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() < localInput.valueOf();
        } else {
            return this.clone().endOf(units).valueOf() < localInput.valueOf();
        }
    }

    function isBetween (from, to, units, inclusivity) {
        inclusivity = inclusivity || '()';
        return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
            (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
    }

    function isSame (input, units) {
        var localInput = isMoment(input) ? input : local__createLocal(input),
            inputMs;
        if (!(this.isValid() && localInput.isValid())) {
            return false;
        }
        units = normalizeUnits(units || 'millisecond');
        if (units === 'millisecond') {
            return this.valueOf() === localInput.valueOf();
        } else {
            inputMs = localInput.valueOf();
            return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
        }
    }

    function isSameOrAfter (input, units) {
        return this.isSame(input, units) || this.isAfter(input,units);
    }

    function isSameOrBefore (input, units) {
        return this.isSame(input, units) || this.isBefore(input,units);
    }

    function diff (input, units, asFloat) {
        var that,
            zoneDelta,
            delta, output;

        if (!this.isValid()) {
            return NaN;
        }

        that = cloneWithOffset(input, this);

        if (!that.isValid()) {
            return NaN;
        }

        zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;

        units = normalizeUnits(units);

        if (units === 'year' || units === 'month' || units === 'quarter') {
            output = monthDiff(this, that);
            if (units === 'quarter') {
                output = output / 3;
            } else if (units === 'year') {
                output = output / 12;
            }
        } else {
            delta = this - that;
            output = units === 'second' ? delta / 1e3 : // 1000
                units === 'minute' ? delta / 6e4 : // 1000 * 60
                units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60
                units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst
                units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst
                delta;
        }
        return asFloat ? output : absFloor(output);
    }

    function monthDiff (a, b) {
        // difference in months
        var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
            // b is in (anchor - 1 month, anchor + 1 month)
            anchor = a.clone().add(wholeMonthDiff, 'months'),
            anchor2, adjust;

        if (b - anchor < 0) {
            anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor - anchor2);
        } else {
            anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
            // linear across the month
            adjust = (b - anchor) / (anchor2 - anchor);
        }

        //check for negative zero, return zero if negative zero
        return -(wholeMonthDiff + adjust) || 0;
    }

    utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
    utils_hooks__hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';

    function toString () {
        return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
    }

    function moment_format__toISOString () {
        var m = this.clone().utc();
        if (0 < m.year() && m.year() <= 9999) {
            if (isFunction(Date.prototype.toISOString)) {
                // native implementation is ~50x faster, use it when we can
                return this.toDate().toISOString();
            } else {
                return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
            }
        } else {
            return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
        }
    }

    function format (inputString) {
        if (!inputString) {
            inputString = this.isUtc() ? utils_hooks__hooks.defaultFormatUtc : utils_hooks__hooks.defaultFormat;
        }
        var output = formatMoment(this, inputString);
        return this.localeData().postformat(output);
    }

    function from (time, withoutSuffix) {
        if (this.isValid() &&
                ((isMoment(time) && time.isValid()) ||
                 local__createLocal(time).isValid())) {
            return create__createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
        } else {
            return this.localeData().invalidDate();
        }
    }

    function fromNow (withoutSuffix) {
        return this.from(local__createLocal(), withoutSuffix);
    }

    function to (time, withoutSuffix) {
        if (this.isValid() &&
                ((isMoment(time) && time.isValid()) ||
                 local__createLocal(time).isValid())) {
            return create__createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
        } else {
            return this.localeData().invalidDate();
        }
    }

    function toNow (withoutSuffix) {
        return this.to(local__createLocal(), withoutSuffix);
    }

    // If passed a locale key, it will set the locale for this
    // instance.  Otherwise, it will return the locale configuration
    // variables for this instance.
    function locale (key) {
        var newLocaleData;

        if (key === undefined) {
            return this._locale._abbr;
        } else {
            newLocaleData = locale_locales__getLocale(key);
            if (newLocaleData != null) {
                this._locale = newLocaleData;
            }
            return this;
        }
    }

    var lang = deprecate(
        'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
        function (key) {
            if (key === undefined) {
                return this.localeData();
            } else {
                return this.locale(key);
            }
        }
    );

    function localeData () {
        return this._locale;
    }

    function startOf (units) {
        units = normalizeUnits(units);
        // the following switch intentionally omits break keywords
        // to utilize falling through the cases.
        switch (units) {
        case 'year':
            this.month(0);
            /* falls through */
        case 'quarter':
        case 'month':
            this.date(1);
            /* falls through */
        case 'week':
        case 'isoWeek':
        case 'day':
        case 'date':
            this.hours(0);
            /* falls through */
        case 'hour':
            this.minutes(0);
            /* falls through */
        case 'minute':
            this.seconds(0);
            /* falls through */
        case 'second':
            this.milliseconds(0);
        }

        // weeks are a special case
        if (units === 'week') {
            this.weekday(0);
        }
        if (units === 'isoWeek') {
            this.isoWeekday(1);
        }

        // quarters are also special
        if (units === 'quarter') {
            this.month(Math.floor(this.month() / 3) * 3);
        }

        return this;
    }

    function endOf (units) {
        units = normalizeUnits(units);
        if (units === undefined || units === 'millisecond') {
            return this;
        }

        // 'date' is an alias for 'day', so it should be considered as such.
        if (units === 'date') {
            units = 'day';
        }

        return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
    }

    function to_type__valueOf () {
        return this._d.valueOf() - ((this._offset || 0) * 60000);
    }

    function unix () {
        return Math.floor(this.valueOf() / 1000);
    }

    function toDate () {
        return this._offset ? new Date(this.valueOf()) : this._d;
    }

    function toArray () {
        var m = this;
        return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
    }

    function toObject () {
        var m = this;
        return {
            years: m.year(),
            months: m.month(),
            date: m.date(),
            hours: m.hours(),
            minutes: m.minutes(),
            seconds: m.seconds(),
            milliseconds: m.milliseconds()
        };
    }

    function toJSON () {
        // new Date(NaN).toJSON() === null
        return this.isValid() ? this.toISOString() : null;
    }

    function moment_valid__isValid () {
        return valid__isValid(this);
    }

    function parsingFlags () {
        return extend({}, getParsingFlags(this));
    }

    function invalidAt () {
        return getParsingFlags(this).overflow;
    }

    function creationData() {
        return {
            input: this._i,
            format: this._f,
            locale: this._locale,
            isUTC: this._isUTC,
            strict: this._strict
        };
    }

    // FORMATTING

    addFormatToken(0, ['gg', 2], 0, function () {
        return this.weekYear() % 100;
    });

    addFormatToken(0, ['GG', 2], 0, function () {
        return this.isoWeekYear() % 100;
    });

    function addWeekYearFormatToken (token, getter) {
        addFormatToken(0, [token, token.length], 0, getter);
    }

    addWeekYearFormatToken('gggg',     'weekYear');
    addWeekYearFormatToken('ggggg',    'weekYear');
    addWeekYearFormatToken('GGGG',  'isoWeekYear');
    addWeekYearFormatToken('GGGGG', 'isoWeekYear');

    // ALIASES

    addUnitAlias('weekYear', 'gg');
    addUnitAlias('isoWeekYear', 'GG');

    // PARSING

    addRegexToken('G',      matchSigned);
    addRegexToken('g',      matchSigned);
    addRegexToken('GG',     match1to2, match2);
    addRegexToken('gg',     match1to2, match2);
    addRegexToken('GGGG',   match1to4, match4);
    addRegexToken('gggg',   match1to4, match4);
    addRegexToken('GGGGG',  match1to6, match6);
    addRegexToken('ggggg',  match1to6, match6);

    addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
        week[token.substr(0, 2)] = toInt(input);
    });

    addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
        week[token] = utils_hooks__hooks.parseTwoDigitYear(input);
    });

    // MOMENTS

    function getSetWeekYear (input) {
        return getSetWeekYearHelper.call(this,
                input,
                this.week(),
                this.weekday(),
                this.localeData()._week.dow,
                this.localeData()._week.doy);
    }

    function getSetISOWeekYear (input) {
        return getSetWeekYearHelper.call(this,
                input, this.isoWeek(), this.isoWeekday(), 1, 4);
    }

    function getISOWeeksInYear () {
        return weeksInYear(this.year(), 1, 4);
    }

    function getWeeksInYear () {
        var weekInfo = this.localeData()._week;
        return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
    }

    function getSetWeekYearHelper(input, week, weekday, dow, doy) {
        var weeksTarget;
        if (input == null) {
            return weekOfYear(this, dow, doy).year;
        } else {
            weeksTarget = weeksInYear(input, dow, doy);
            if (week > weeksTarget) {
                week = weeksTarget;
            }
            return setWeekAll.call(this, input, week, weekday, dow, doy);
        }
    }

    function setWeekAll(weekYear, week, weekday, dow, doy) {
        var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
            date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);

        this.year(date.getUTCFullYear());
        this.month(date.getUTCMonth());
        this.date(date.getUTCDate());
        return this;
    }

    // FORMATTING

    addFormatToken('Q', 0, 'Qo', 'quarter');

    // ALIASES

    addUnitAlias('quarter', 'Q');

    // PARSING

    addRegexToken('Q', match1);
    addParseToken('Q', function (input, array) {
        array[MONTH] = (toInt(input) - 1) * 3;
    });

    // MOMENTS

    function getSetQuarter (input) {
        return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
    }

    // FORMATTING

    addFormatToken('w', ['ww', 2], 'wo', 'week');
    addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');

    // ALIASES

    addUnitAlias('week', 'w');
    addUnitAlias('isoWeek', 'W');

    // PARSING

    addRegexToken('w',  match1to2);
    addRegexToken('ww', match1to2, match2);
    addRegexToken('W',  match1to2);
    addRegexToken('WW', match1to2, match2);

    addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
        week[token.substr(0, 1)] = toInt(input);
    });

    // HELPERS

    // LOCALES

    function localeWeek (mom) {
        return weekOfYear(mom, this._week.dow, this._week.doy).week;
    }

    var defaultLocaleWeek = {
        dow : 0, // Sunday is the first day of the week.
        doy : 6  // The week that contains Jan 1st is the first week of the year.
    };

    function localeFirstDayOfWeek () {
        return this._week.dow;
    }

    function localeFirstDayOfYear () {
        return this._week.doy;
    }

    // MOMENTS

    function getSetWeek (input) {
        var week = this.localeData().week(this);
        return input == null ? week : this.add((input - week) * 7, 'd');
    }

    function getSetISOWeek (input) {
        var week = weekOfYear(this, 1, 4).week;
        return input == null ? week : this.add((input - week) * 7, 'd');
    }

    // FORMATTING

    addFormatToken('D', ['DD', 2], 'Do', 'date');

    // ALIASES

    addUnitAlias('date', 'D');

    // PARSING

    addRegexToken('D',  match1to2);
    addRegexToken('DD', match1to2, match2);
    addRegexToken('Do', function (isStrict, locale) {
        return isStrict ? locale._ordinalParse : locale._ordinalParseLenient;
    });

    addParseToken(['D', 'DD'], DATE);
    addParseToken('Do', function (input, array) {
        array[DATE] = toInt(input.match(match1to2)[0], 10);
    });

    // MOMENTS

    var getSetDayOfMonth = makeGetSet('Date', true);

    // FORMATTING

    addFormatToken('d', 0, 'do', 'day');

    addFormatToken('dd', 0, 0, function (format) {
        return this.localeData().weekdaysMin(this, format);
    });

    addFormatToken('ddd', 0, 0, function (format) {
        return this.localeData().weekdaysShort(this, format);
    });

    addFormatToken('dddd', 0, 0, function (format) {
        return this.localeData().weekdays(this, format);
    });

    addFormatToken('e', 0, 0, 'weekday');
    addFormatToken('E', 0, 0, 'isoWeekday');

    // ALIASES

    addUnitAlias('day', 'd');
    addUnitAlias('weekday', 'e');
    addUnitAlias('isoWeekday', 'E');

    // PARSING

    addRegexToken('d',    match1to2);
    addRegexToken('e',    match1to2);
    addRegexToken('E',    match1to2);
    addRegexToken('dd',   function (isStrict, locale) {
        return locale.weekdaysMinRegex(isStrict);
    });
    addRegexToken('ddd',   function (isStrict, locale) {
        return locale.weekdaysShortRegex(isStrict);
    });
    addRegexToken('dddd',   function (isStrict, locale) {
        return locale.weekdaysRegex(isStrict);
    });

    addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
        var weekday = config._locale.weekdaysParse(input, token, config._strict);
        // if we didn't get a weekday name, mark the date as invalid
        if (weekday != null) {
            week.d = weekday;
        } else {
            getParsingFlags(config).invalidWeekday = input;
        }
    });

    addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
        week[token] = toInt(input);
    });

    // HELPERS

    function parseWeekday(input, locale) {
        if (typeof input !== 'string') {
            return input;
        }

        if (!isNaN(input)) {
            return parseInt(input, 10);
        }

        input = locale.weekdaysParse(input);
        if (typeof input === 'number') {
            return input;
        }

        return null;
    }

    // LOCALES

    var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
    function localeWeekdays (m, format) {
        return isArray(this._weekdays) ? this._weekdays[m.day()] :
            this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
    }

    var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
    function localeWeekdaysShort (m) {
        return this._weekdaysShort[m.day()];
    }

    var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
    function localeWeekdaysMin (m) {
        return this._weekdaysMin[m.day()];
    }

    function day_of_week__handleStrictParse(weekdayName, format, strict) {
        var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
        if (!this._weekdaysParse) {
            this._weekdaysParse = [];
            this._shortWeekdaysParse = [];
            this._minWeekdaysParse = [];

            for (i = 0; i < 7; ++i) {
                mom = create_utc__createUTC([2000, 1]).day(i);
                this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
                this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
                this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
            }
        }

        if (strict) {
            if (format === 'dddd') {
                ii = indexOf.call(this._weekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else if (format === 'ddd') {
                ii = indexOf.call(this._shortWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            }
        } else {
            if (format === 'dddd') {
                ii = indexOf.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._shortWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else if (format === 'ddd') {
                ii = indexOf.call(this._shortWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._minWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            } else {
                ii = indexOf.call(this._minWeekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._weekdaysParse, llc);
                if (ii !== -1) {
                    return ii;
                }
                ii = indexOf.call(this._shortWeekdaysParse, llc);
                return ii !== -1 ? ii : null;
            }
        }
    }

    function localeWeekdaysParse (weekdayName, format, strict) {
        var i, mom, regex;

        if (this._weekdaysParseExact) {
            return day_of_week__handleStrictParse.call(this, weekdayName, format, strict);
        }

        if (!this._weekdaysParse) {
            this._weekdaysParse = [];
            this._minWeekdaysParse = [];
            this._shortWeekdaysParse = [];
            this._fullWeekdaysParse = [];
        }

        for (i = 0; i < 7; i++) {
            // make the regex if we don't have it already

            mom = create_utc__createUTC([2000, 1]).day(i);
            if (strict && !this._fullWeekdaysParse[i]) {
                this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
                this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
                this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
            }
            if (!this._weekdaysParse[i]) {
                regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
                this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
            }
            // test the regex
            if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
                return i;
            } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
                return i;
            }
        }
    }

    // MOMENTS

    function getSetDayOfWeek (input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
        if (input != null) {
            input = parseWeekday(input, this.localeData());
            return this.add(input - day, 'd');
        } else {
            return day;
        }
    }

    function getSetLocaleDayOfWeek (input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
        return input == null ? weekday : this.add(input - weekday, 'd');
    }

    function getSetISODayOfWeek (input) {
        if (!this.isValid()) {
            return input != null ? this : NaN;
        }
        // behaves the same as moment#day except
        // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
        // as a setter, sunday should belong to the previous week.
        return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7);
    }

    var defaultWeekdaysRegex = matchWord;
    function weekdaysRegex (isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysStrictRegex;
            } else {
                return this._weekdaysRegex;
            }
        } else {
            return this._weekdaysStrictRegex && isStrict ?
                this._weekdaysStrictRegex : this._weekdaysRegex;
        }
    }

    var defaultWeekdaysShortRegex = matchWord;
    function weekdaysShortRegex (isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysShortStrictRegex;
            } else {
                return this._weekdaysShortRegex;
            }
        } else {
            return this._weekdaysShortStrictRegex && isStrict ?
                this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
        }
    }

    var defaultWeekdaysMinRegex = matchWord;
    function weekdaysMinRegex (isStrict) {
        if (this._weekdaysParseExact) {
            if (!hasOwnProp(this, '_weekdaysRegex')) {
                computeWeekdaysParse.call(this);
            }
            if (isStrict) {
                return this._weekdaysMinStrictRegex;
            } else {
                return this._weekdaysMinRegex;
            }
        } else {
            return this._weekdaysMinStrictRegex && isStrict ?
                this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
        }
    }


    function computeWeekdaysParse () {
        function cmpLenRev(a, b) {
            return b.length - a.length;
        }

        var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
            i, mom, minp, shortp, longp;
        for (i = 0; i < 7; i++) {
            // make the regex if we don't have it already
            mom = create_utc__createUTC([2000, 1]).day(i);
            minp = this.weekdaysMin(mom, '');
            shortp = this.weekdaysShort(mom, '');
            longp = this.weekdays(mom, '');
            minPieces.push(minp);
            shortPieces.push(shortp);
            longPieces.push(longp);
            mixedPieces.push(minp);
            mixedPieces.push(shortp);
            mixedPieces.push(longp);
        }
        // Sorting makes sure if one weekday (or abbr) is a prefix of another it
        // will match the longer piece.
        minPieces.sort(cmpLenRev);
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        for (i = 0; i < 7; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
        this._weekdaysShortRegex = this._weekdaysRegex;
        this._weekdaysMinRegex = this._weekdaysRegex;

        this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
        this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
        this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
    }

    // FORMATTING

    addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');

    // ALIASES

    addUnitAlias('dayOfYear', 'DDD');

    // PARSING

    addRegexToken('DDD',  match1to3);
    addRegexToken('DDDD', match3);
    addParseToken(['DDD', 'DDDD'], function (input, array, config) {
        config._dayOfYear = toInt(input);
    });

    // HELPERS

    // MOMENTS

    function getSetDayOfYear (input) {
        var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
        return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
    }

    // FORMATTING

    function hFormat() {
        return this.hours() % 12 || 12;
    }

    function kFormat() {
        return this.hours() || 24;
    }

    addFormatToken('H', ['HH', 2], 0, 'hour');
    addFormatToken('h', ['hh', 2], 0, hFormat);
    addFormatToken('k', ['kk', 2], 0, kFormat);

    addFormatToken('hmm', 0, 0, function () {
        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
    });

    addFormatToken('hmmss', 0, 0, function () {
        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
            zeroFill(this.seconds(), 2);
    });

    addFormatToken('Hmm', 0, 0, function () {
        return '' + this.hours() + zeroFill(this.minutes(), 2);
    });

    addFormatToken('Hmmss', 0, 0, function () {
        return '' + this.hours() + zeroFill(this.minutes(), 2) +
            zeroFill(this.seconds(), 2);
    });

    function meridiem (token, lowercase) {
        addFormatToken(token, 0, 0, function () {
            return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
        });
    }

    meridiem('a', true);
    meridiem('A', false);

    // ALIASES

    addUnitAlias('hour', 'h');

    // PARSING

    function matchMeridiem (isStrict, locale) {
        return locale._meridiemParse;
    }

    addRegexToken('a',  matchMeridiem);
    addRegexToken('A',  matchMeridiem);
    addRegexToken('H',  match1to2);
    addRegexToken('h',  match1to2);
    addRegexToken('HH', match1to2, match2);
    addRegexToken('hh', match1to2, match2);

    addRegexToken('hmm', match3to4);
    addRegexToken('hmmss', match5to6);
    addRegexToken('Hmm', match3to4);
    addRegexToken('Hmmss', match5to6);

    addParseToken(['H', 'HH'], HOUR);
    addParseToken(['a', 'A'], function (input, array, config) {
        config._isPm = config._locale.isPM(input);
        config._meridiem = input;
    });
    addParseToken(['h', 'hh'], function (input, array, config) {
        array[HOUR] = toInt(input);
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('hmm', function (input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('hmmss', function (input, array, config) {
        var pos1 = input.length - 4;
        var pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
        getParsingFlags(config).bigHour = true;
    });
    addParseToken('Hmm', function (input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
    });
    addParseToken('Hmmss', function (input, array, config) {
        var pos1 = input.length - 4;
        var pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
    });

    // LOCALES

    function localeIsPM (input) {
        // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
        // Using charAt should be more compatible.
        return ((input + '').toLowerCase().charAt(0) === 'p');
    }

    var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
    function localeMeridiem (hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'pm' : 'PM';
        } else {
            return isLower ? 'am' : 'AM';
        }
    }


    // MOMENTS

    // Setting the hour should keep the time, because the user explicitly
    // specified which hour he wants. So trying to maintain the same hour (in
    // a new timezone) makes sense. Adding/subtracting hours does not follow
    // this rule.
    var getSetHour = makeGetSet('Hours', true);

    // FORMATTING

    addFormatToken('m', ['mm', 2], 0, 'minute');

    // ALIASES

    addUnitAlias('minute', 'm');

    // PARSING

    addRegexToken('m',  match1to2);
    addRegexToken('mm', match1to2, match2);
    addParseToken(['m', 'mm'], MINUTE);

    // MOMENTS

    var getSetMinute = makeGetSet('Minutes', false);

    // FORMATTING

    addFormatToken('s', ['ss', 2], 0, 'second');

    // ALIASES

    addUnitAlias('second', 's');

    // PARSING

    addRegexToken('s',  match1to2);
    addRegexToken('ss', match1to2, match2);
    addParseToken(['s', 'ss'], SECOND);

    // MOMENTS

    var getSetSecond = makeGetSet('Seconds', false);

    // FORMATTING

    addFormatToken('S', 0, 0, function () {
        return ~~(this.millisecond() / 100);
    });

    addFormatToken(0, ['SS', 2], 0, function () {
        return ~~(this.millisecond() / 10);
    });

    addFormatToken(0, ['SSS', 3], 0, 'millisecond');
    addFormatToken(0, ['SSSS', 4], 0, function () {
        return this.millisecond() * 10;
    });
    addFormatToken(0, ['SSSSS', 5], 0, function () {
        return this.millisecond() * 100;
    });
    addFormatToken(0, ['SSSSSS', 6], 0, function () {
        return this.millisecond() * 1000;
    });
    addFormatToken(0, ['SSSSSSS', 7], 0, function () {
        return this.millisecond() * 10000;
    });
    addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
        return this.millisecond() * 100000;
    });
    addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
        return this.millisecond() * 1000000;
    });


    // ALIASES

    addUnitAlias('millisecond', 'ms');

    // PARSING

    addRegexToken('S',    match1to3, match1);
    addRegexToken('SS',   match1to3, match2);
    addRegexToken('SSS',  match1to3, match3);

    var token;
    for (token = 'SSSS'; token.length <= 9; token += 'S') {
        addRegexToken(token, matchUnsigned);
    }

    function parseMs(input, array) {
        array[MILLISECOND] = toInt(('0.' + input) * 1000);
    }

    for (token = 'S'; token.length <= 9; token += 'S') {
        addParseToken(token, parseMs);
    }
    // MOMENTS

    var getSetMillisecond = makeGetSet('Milliseconds', false);

    // FORMATTING

    addFormatToken('z',  0, 0, 'zoneAbbr');
    addFormatToken('zz', 0, 0, 'zoneName');

    // MOMENTS

    function getZoneAbbr () {
        return this._isUTC ? 'UTC' : '';
    }

    function getZoneName () {
        return this._isUTC ? 'Coordinated Universal Time' : '';
    }

    var momentPrototype__proto = Moment.prototype;

    momentPrototype__proto.add               = add_subtract__add;
    momentPrototype__proto.calendar          = moment_calendar__calendar;
    momentPrototype__proto.clone             = clone;
    momentPrototype__proto.diff              = diff;
    momentPrototype__proto.endOf             = endOf;
    momentPrototype__proto.format            = format;
    momentPrototype__proto.from              = from;
    momentPrototype__proto.fromNow           = fromNow;
    momentPrototype__proto.to                = to;
    momentPrototype__proto.toNow             = toNow;
    momentPrototype__proto.get               = getSet;
    momentPrototype__proto.invalidAt         = invalidAt;
    momentPrototype__proto.isAfter           = isAfter;
    momentPrototype__proto.isBefore          = isBefore;
    momentPrototype__proto.isBetween         = isBetween;
    momentPrototype__proto.isSame            = isSame;
    momentPrototype__proto.isSameOrAfter     = isSameOrAfter;
    momentPrototype__proto.isSameOrBefore    = isSameOrBefore;
    momentPrototype__proto.isValid           = moment_valid__isValid;
    momentPrototype__proto.lang              = lang;
    momentPrototype__proto.locale            = locale;
    momentPrototype__proto.localeData        = localeData;
    momentPrototype__proto.max               = prototypeMax;
    momentPrototype__proto.min               = prototypeMin;
    momentPrototype__proto.parsingFlags      = parsingFlags;
    momentPrototype__proto.set               = getSet;
    momentPrototype__proto.startOf           = startOf;
    momentPrototype__proto.subtract          = add_subtract__subtract;
    momentPrototype__proto.toArray           = toArray;
    momentPrototype__proto.toObject          = toObject;
    momentPrototype__proto.toDate            = toDate;
    momentPrototype__proto.toISOString       = moment_format__toISOString;
    momentPrototype__proto.toJSON            = toJSON;
    momentPrototype__proto.toString          = toString;
    momentPrototype__proto.unix              = unix;
    momentPrototype__proto.valueOf           = to_type__valueOf;
    momentPrototype__proto.creationData      = creationData;

    // Year
    momentPrototype__proto.year       = getSetYear;
    momentPrototype__proto.isLeapYear = getIsLeapYear;

    // Week Year
    momentPrototype__proto.weekYear    = getSetWeekYear;
    momentPrototype__proto.isoWeekYear = getSetISOWeekYear;

    // Quarter
    momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter;

    // Month
    momentPrototype__proto.month       = getSetMonth;
    momentPrototype__proto.daysInMonth = getDaysInMonth;

    // Week
    momentPrototype__proto.week           = momentPrototype__proto.weeks        = getSetWeek;
    momentPrototype__proto.isoWeek        = momentPrototype__proto.isoWeeks     = getSetISOWeek;
    momentPrototype__proto.weeksInYear    = getWeeksInYear;
    momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear;

    // Day
    momentPrototype__proto.date       = getSetDayOfMonth;
    momentPrototype__proto.day        = momentPrototype__proto.days             = getSetDayOfWeek;
    momentPrototype__proto.weekday    = getSetLocaleDayOfWeek;
    momentPrototype__proto.isoWeekday = getSetISODayOfWeek;
    momentPrototype__proto.dayOfYear  = getSetDayOfYear;

    // Hour
    momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour;

    // Minute
    momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute;

    // Second
    momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond;

    // Millisecond
    momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond;

    // Offset
    momentPrototype__proto.utcOffset            = getSetOffset;
    momentPrototype__proto.utc                  = setOffsetToUTC;
    momentPrototype__proto.local                = setOffsetToLocal;
    momentPrototype__proto.parseZone            = setOffsetToParsedOffset;
    momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset;
    momentPrototype__proto.isDST                = isDaylightSavingTime;
    momentPrototype__proto.isDSTShifted         = isDaylightSavingTimeShifted;
    momentPrototype__proto.isLocal              = isLocal;
    momentPrototype__proto.isUtcOffset          = isUtcOffset;
    momentPrototype__proto.isUtc                = isUtc;
    momentPrototype__proto.isUTC                = isUtc;

    // Timezone
    momentPrototype__proto.zoneAbbr = getZoneAbbr;
    momentPrototype__proto.zoneName = getZoneName;

    // Deprecations
    momentPrototype__proto.dates  = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
    momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
    momentPrototype__proto.years  = deprecate('years accessor is deprecated. Use year instead', getSetYear);
    momentPrototype__proto.zone   = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone);

    var momentPrototype = momentPrototype__proto;

    function moment__createUnix (input) {
        return local__createLocal(input * 1000);
    }

    function moment__createInZone () {
        return local__createLocal.apply(null, arguments).parseZone();
    }

    var defaultCalendar = {
        sameDay : '[Today at] LT',
        nextDay : '[Tomorrow at] LT',
        nextWeek : 'dddd [at] LT',
        lastDay : '[Yesterday at] LT',
        lastWeek : '[Last] dddd [at] LT',
        sameElse : 'L'
    };

    function locale_calendar__calendar (key, mom, now) {
        var output = this._calendar[key];
        return isFunction(output) ? output.call(mom, now) : output;
    }

    var defaultLongDateFormat = {
        LTS  : 'h:mm:ss A',
        LT   : 'h:mm A',
        L    : 'MM/DD/YYYY',
        LL   : 'MMMM D, YYYY',
        LLL  : 'MMMM D, YYYY h:mm A',
        LLLL : 'dddd, MMMM D, YYYY h:mm A'
    };

    function longDateFormat (key) {
        var format = this._longDateFormat[key],
            formatUpper = this._longDateFormat[key.toUpperCase()];

        if (format || !formatUpper) {
            return format;
        }

        this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
            return val.slice(1);
        });

        return this._longDateFormat[key];
    }

    var defaultInvalidDate = 'Invalid date';

    function invalidDate () {
        return this._invalidDate;
    }

    var defaultOrdinal = '%d';
    var defaultOrdinalParse = /\d{1,2}/;

    function ordinal (number) {
        return this._ordinal.replace('%d', number);
    }

    function preParsePostFormat (string) {
        return string;
    }

    var defaultRelativeTime = {
        future : 'in %s',
        past   : '%s ago',
        s  : 'a few seconds',
        m  : 'a minute',
        mm : '%d minutes',
        h  : 'an hour',
        hh : '%d hours',
        d  : 'a day',
        dd : '%d days',
        M  : 'a month',
        MM : '%d months',
        y  : 'a year',
        yy : '%d years'
    };

    function relative__relativeTime (number, withoutSuffix, string, isFuture) {
        var output = this._relativeTime[string];
        return (isFunction(output)) ?
            output(number, withoutSuffix, string, isFuture) :
            output.replace(/%d/i, number);
    }

    function pastFuture (diff, output) {
        var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
        return isFunction(format) ? format(output) : format.replace(/%s/i, output);
    }

    var prototype__proto = Locale.prototype;

    prototype__proto._calendar       = defaultCalendar;
    prototype__proto.calendar        = locale_calendar__calendar;
    prototype__proto._longDateFormat = defaultLongDateFormat;
    prototype__proto.longDateFormat  = longDateFormat;
    prototype__proto._invalidDate    = defaultInvalidDate;
    prototype__proto.invalidDate     = invalidDate;
    prototype__proto._ordinal        = defaultOrdinal;
    prototype__proto.ordinal         = ordinal;
    prototype__proto._ordinalParse   = defaultOrdinalParse;
    prototype__proto.preparse        = preParsePostFormat;
    prototype__proto.postformat      = preParsePostFormat;
    prototype__proto._relativeTime   = defaultRelativeTime;
    prototype__proto.relativeTime    = relative__relativeTime;
    prototype__proto.pastFuture      = pastFuture;
    prototype__proto.set             = locale_set__set;

    // Month
    prototype__proto.months            =        localeMonths;
    prototype__proto._months           = defaultLocaleMonths;
    prototype__proto.monthsShort       =        localeMonthsShort;
    prototype__proto._monthsShort      = defaultLocaleMonthsShort;
    prototype__proto.monthsParse       =        localeMonthsParse;
    prototype__proto._monthsRegex      = defaultMonthsRegex;
    prototype__proto.monthsRegex       = monthsRegex;
    prototype__proto._monthsShortRegex = defaultMonthsShortRegex;
    prototype__proto.monthsShortRegex  = monthsShortRegex;

    // Week
    prototype__proto.week = localeWeek;
    prototype__proto._week = defaultLocaleWeek;
    prototype__proto.firstDayOfYear = localeFirstDayOfYear;
    prototype__proto.firstDayOfWeek = localeFirstDayOfWeek;

    // Day of Week
    prototype__proto.weekdays       =        localeWeekdays;
    prototype__proto._weekdays      = defaultLocaleWeekdays;
    prototype__proto.weekdaysMin    =        localeWeekdaysMin;
    prototype__proto._weekdaysMin   = defaultLocaleWeekdaysMin;
    prototype__proto.weekdaysShort  =        localeWeekdaysShort;
    prototype__proto._weekdaysShort = defaultLocaleWeekdaysShort;
    prototype__proto.weekdaysParse  =        localeWeekdaysParse;

    prototype__proto._weekdaysRegex      = defaultWeekdaysRegex;
    prototype__proto.weekdaysRegex       =        weekdaysRegex;
    prototype__proto._weekdaysShortRegex = defaultWeekdaysShortRegex;
    prototype__proto.weekdaysShortRegex  =        weekdaysShortRegex;
    prototype__proto._weekdaysMinRegex   = defaultWeekdaysMinRegex;
    prototype__proto.weekdaysMinRegex    =        weekdaysMinRegex;

    // Hours
    prototype__proto.isPM = localeIsPM;
    prototype__proto._meridiemParse = defaultLocaleMeridiemParse;
    prototype__proto.meridiem = localeMeridiem;

    function lists__get (format, index, field, setter) {
        var locale = locale_locales__getLocale();
        var utc = create_utc__createUTC().set(setter, index);
        return locale[field](utc, format);
    }

    function listMonthsImpl (format, index, field) {
        if (typeof format === 'number') {
            index = format;
            format = undefined;
        }

        format = format || '';

        if (index != null) {
            return lists__get(format, index, field, 'month');
        }

        var i;
        var out = [];
        for (i = 0; i < 12; i++) {
            out[i] = lists__get(format, i, field, 'month');
        }
        return out;
    }

    // ()
    // (5)
    // (fmt, 5)
    // (fmt)
    // (true)
    // (true, 5)
    // (true, fmt, 5)
    // (true, fmt)
    function listWeekdaysImpl (localeSorted, format, index, field) {
        if (typeof localeSorted === 'boolean') {
            if (typeof format === 'number') {
                index = format;
                format = undefined;
            }

            format = format || '';
        } else {
            format = localeSorted;
            index = format;
            localeSorted = false;

            if (typeof format === 'number') {
                index = format;
                format = undefined;
            }

            format = format || '';
        }

        var locale = locale_locales__getLocale(),
            shift = localeSorted ? locale._week.dow : 0;

        if (index != null) {
            return lists__get(format, (index + shift) % 7, field, 'day');
        }

        var i;
        var out = [];
        for (i = 0; i < 7; i++) {
            out[i] = lists__get(format, (i + shift) % 7, field, 'day');
        }
        return out;
    }

    function lists__listMonths (format, index) {
        return listMonthsImpl(format, index, 'months');
    }

    function lists__listMonthsShort (format, index) {
        return listMonthsImpl(format, index, 'monthsShort');
    }

    function lists__listWeekdays (localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
    }

    function lists__listWeekdaysShort (localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
    }

    function lists__listWeekdaysMin (localeSorted, format, index) {
        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
    }

    locale_locales__getSetGlobalLocale('en', {
        ordinalParse: /\d{1,2}(th|st|nd|rd)/,
        ordinal : function (number) {
            var b = number % 10,
                output = (toInt(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });

    // Side effect imports
    utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale);
    utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale);

    var mathAbs = Math.abs;

    function duration_abs__abs () {
        var data           = this._data;

        this._milliseconds = mathAbs(this._milliseconds);
        this._days         = mathAbs(this._days);
        this._months       = mathAbs(this._months);

        data.milliseconds  = mathAbs(data.milliseconds);
        data.seconds       = mathAbs(data.seconds);
        data.minutes       = mathAbs(data.minutes);
        data.hours         = mathAbs(data.hours);
        data.months        = mathAbs(data.months);
        data.years         = mathAbs(data.years);

        return this;
    }

    function duration_add_subtract__addSubtract (duration, input, value, direction) {
        var other = create__createDuration(input, value);

        duration._milliseconds += direction * other._milliseconds;
        duration._days         += direction * other._days;
        duration._months       += direction * other._months;

        return duration._bubble();
    }

    // supports only 2.0-style add(1, 's') or add(duration)
    function duration_add_subtract__add (input, value) {
        return duration_add_subtract__addSubtract(this, input, value, 1);
    }

    // supports only 2.0-style subtract(1, 's') or subtract(duration)
    function duration_add_subtract__subtract (input, value) {
        return duration_add_subtract__addSubtract(this, input, value, -1);
    }

    function absCeil (number) {
        if (number < 0) {
            return Math.floor(number);
        } else {
            return Math.ceil(number);
        }
    }

    function bubble () {
        var milliseconds = this._milliseconds;
        var days         = this._days;
        var months       = this._months;
        var data         = this._data;
        var seconds, minutes, hours, years, monthsFromDays;

        // if we have a mix of positive and negative values, bubble down first
        // check: https://github.com/moment/moment/issues/2166
        if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
                (milliseconds <= 0 && days <= 0 && months <= 0))) {
            milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
            days = 0;
            months = 0;
        }

        // The following code bubbles up values, see the tests for
        // examples of what that means.
        data.milliseconds = milliseconds % 1000;

        seconds           = absFloor(milliseconds / 1000);
        data.seconds      = seconds % 60;

        minutes           = absFloor(seconds / 60);
        data.minutes      = minutes % 60;

        hours             = absFloor(minutes / 60);
        data.hours        = hours % 24;

        days += absFloor(hours / 24);

        // convert days to months
        monthsFromDays = absFloor(daysToMonths(days));
        months += monthsFromDays;
        days -= absCeil(monthsToDays(monthsFromDays));

        // 12 months -> 1 year
        years = absFloor(months / 12);
        months %= 12;

        data.days   = days;
        data.months = months;
        data.years  = years;

        return this;
    }

    function daysToMonths (days) {
        // 400 years have 146097 days (taking into account leap year rules)
        // 400 years have 12 months === 4800
        return days * 4800 / 146097;
    }

    function monthsToDays (months) {
        // the reverse of daysToMonths
        return months * 146097 / 4800;
    }

    function as (units) {
        var days;
        var months;
        var milliseconds = this._milliseconds;

        units = normalizeUnits(units);

        if (units === 'month' || units === 'year') {
            days   = this._days   + milliseconds / 864e5;
            months = this._months + daysToMonths(days);
            return units === 'month' ? months : months / 12;
        } else {
            // handle milliseconds separately because of floating point math errors (issue #1867)
            days = this._days + Math.round(monthsToDays(this._months));
            switch (units) {
                case 'week'   : return days / 7     + milliseconds / 6048e5;
                case 'day'    : return days         + milliseconds / 864e5;
                case 'hour'   : return days * 24    + milliseconds / 36e5;
                case 'minute' : return days * 1440  + milliseconds / 6e4;
                case 'second' : return days * 86400 + milliseconds / 1000;
                // Math.floor prevents floating point math errors here
                case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
                default: throw new Error('Unknown unit ' + units);
            }
        }
    }

    // TODO: Use this.as('ms')?
    function duration_as__valueOf () {
        return (
            this._milliseconds +
            this._days * 864e5 +
            (this._months % 12) * 2592e6 +
            toInt(this._months / 12) * 31536e6
        );
    }

    function makeAs (alias) {
        return function () {
            return this.as(alias);
        };
    }

    var asMilliseconds = makeAs('ms');
    var asSeconds      = makeAs('s');
    var asMinutes      = makeAs('m');
    var asHours        = makeAs('h');
    var asDays         = makeAs('d');
    var asWeeks        = makeAs('w');
    var asMonths       = makeAs('M');
    var asYears        = makeAs('y');

    function duration_get__get (units) {
        units = normalizeUnits(units);
        return this[units + 's']();
    }

    function makeGetter(name) {
        return function () {
            return this._data[name];
        };
    }

    var milliseconds = makeGetter('milliseconds');
    var seconds      = makeGetter('seconds');
    var minutes      = makeGetter('minutes');
    var hours        = makeGetter('hours');
    var days         = makeGetter('days');
    var months       = makeGetter('months');
    var years        = makeGetter('years');

    function weeks () {
        return absFloor(this.days() / 7);
    }

    var round = Math.round;
    var thresholds = {
        s: 45,  // seconds to minute
        m: 45,  // minutes to hour
        h: 22,  // hours to day
        d: 26,  // days to month
        M: 11   // months to year
    };

    // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
    function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
        return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
    }

    function duration_humanize__relativeTime (posNegDuration, withoutSuffix, locale) {
        var duration = create__createDuration(posNegDuration).abs();
        var seconds  = round(duration.as('s'));
        var minutes  = round(duration.as('m'));
        var hours    = round(duration.as('h'));
        var days     = round(duration.as('d'));
        var months   = round(duration.as('M'));
        var years    = round(duration.as('y'));

        var a = seconds < thresholds.s && ['s', seconds]  ||
                minutes <= 1           && ['m']           ||
                minutes < thresholds.m && ['mm', minutes] ||
                hours   <= 1           && ['h']           ||
                hours   < thresholds.h && ['hh', hours]   ||
                days    <= 1           && ['d']           ||
                days    < thresholds.d && ['dd', days]    ||
                months  <= 1           && ['M']           ||
                months  < thresholds.M && ['MM', months]  ||
                years   <= 1           && ['y']           || ['yy', years];

        a[2] = withoutSuffix;
        a[3] = +posNegDuration > 0;
        a[4] = locale;
        return substituteTimeAgo.apply(null, a);
    }

    // This function allows you to set a threshold for relative time strings
    function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) {
        if (thresholds[threshold] === undefined) {
            return false;
        }
        if (limit === undefined) {
            return thresholds[threshold];
        }
        thresholds[threshold] = limit;
        return true;
    }

    function humanize (withSuffix) {
        var locale = this.localeData();
        var output = duration_humanize__relativeTime(this, !withSuffix, locale);

        if (withSuffix) {
            output = locale.pastFuture(+this, output);
        }

        return locale.postformat(output);
    }

    var iso_string__abs = Math.abs;

    function iso_string__toISOString() {
        // for ISO strings we do not use the normal bubbling rules:
        //  * milliseconds bubble up until they become hours
        //  * days do not bubble at all
        //  * months bubble up until they become years
        // This is because there is no context-free conversion between hours and days
        // (think of clock changes)
        // and also not between days and months (28-31 days per month)
        var seconds = iso_string__abs(this._milliseconds) / 1000;
        var days         = iso_string__abs(this._days);
        var months       = iso_string__abs(this._months);
        var minutes, hours, years;

        // 3600 seconds -> 60 minutes -> 1 hour
        minutes           = absFloor(seconds / 60);
        hours             = absFloor(minutes / 60);
        seconds %= 60;
        minutes %= 60;

        // 12 months -> 1 year
        years  = absFloor(months / 12);
        months %= 12;


        // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
        var Y = years;
        var M = months;
        var D = days;
        var h = hours;
        var m = minutes;
        var s = seconds;
        var total = this.asSeconds();

        if (!total) {
            // this is the same as C#'s (Noda) and python (isodate)...
            // but not other JS (goog.date)
            return 'P0D';
        }

        return (total < 0 ? '-' : '') +
            'P' +
            (Y ? Y + 'Y' : '') +
            (M ? M + 'M' : '') +
            (D ? D + 'D' : '') +
            ((h || m || s) ? 'T' : '') +
            (h ? h + 'H' : '') +
            (m ? m + 'M' : '') +
            (s ? s + 'S' : '');
    }

    var duration_prototype__proto = Duration.prototype;

    duration_prototype__proto.abs            = duration_abs__abs;
    duration_prototype__proto.add            = duration_add_subtract__add;
    duration_prototype__proto.subtract       = duration_add_subtract__subtract;
    duration_prototype__proto.as             = as;
    duration_prototype__proto.asMilliseconds = asMilliseconds;
    duration_prototype__proto.asSeconds      = asSeconds;
    duration_prototype__proto.asMinutes      = asMinutes;
    duration_prototype__proto.asHours        = asHours;
    duration_prototype__proto.asDays         = asDays;
    duration_prototype__proto.asWeeks        = asWeeks;
    duration_prototype__proto.asMonths       = asMonths;
    duration_prototype__proto.asYears        = asYears;
    duration_prototype__proto.valueOf        = duration_as__valueOf;
    duration_prototype__proto._bubble        = bubble;
    duration_prototype__proto.get            = duration_get__get;
    duration_prototype__proto.milliseconds   = milliseconds;
    duration_prototype__proto.seconds        = seconds;
    duration_prototype__proto.minutes        = minutes;
    duration_prototype__proto.hours          = hours;
    duration_prototype__proto.days           = days;
    duration_prototype__proto.weeks          = weeks;
    duration_prototype__proto.months         = months;
    duration_prototype__proto.years          = years;
    duration_prototype__proto.humanize       = humanize;
    duration_prototype__proto.toISOString    = iso_string__toISOString;
    duration_prototype__proto.toString       = iso_string__toISOString;
    duration_prototype__proto.toJSON         = iso_string__toISOString;
    duration_prototype__proto.locale         = locale;
    duration_prototype__proto.localeData     = localeData;

    // Deprecations
    duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString);
    duration_prototype__proto.lang = lang;

    // Side effect imports

    // FORMATTING

    addFormatToken('X', 0, 0, 'unix');
    addFormatToken('x', 0, 0, 'valueOf');

    // PARSING

    addRegexToken('x', matchSigned);
    addRegexToken('X', matchTimestamp);
    addParseToken('X', function (input, array, config) {
        config._d = new Date(parseFloat(input, 10) * 1000);
    });
    addParseToken('x', function (input, array, config) {
        config._d = new Date(toInt(input));
    });

    // Side effect imports


    utils_hooks__hooks.version = '2.13.0';

    setHookCallback(local__createLocal);

    utils_hooks__hooks.fn                    = momentPrototype;
    utils_hooks__hooks.min                   = min;
    utils_hooks__hooks.max                   = max;
    utils_hooks__hooks.now                   = now;
    utils_hooks__hooks.utc                   = create_utc__createUTC;
    utils_hooks__hooks.unix                  = moment__createUnix;
    utils_hooks__hooks.months                = lists__listMonths;
    utils_hooks__hooks.isDate                = isDate;
    utils_hooks__hooks.locale                = locale_locales__getSetGlobalLocale;
    utils_hooks__hooks.invalid               = valid__createInvalid;
    utils_hooks__hooks.duration              = create__createDuration;
    utils_hooks__hooks.isMoment              = isMoment;
    utils_hooks__hooks.weekdays              = lists__listWeekdays;
    utils_hooks__hooks.parseZone             = moment__createInZone;
    utils_hooks__hooks.localeData            = locale_locales__getLocale;
    utils_hooks__hooks.isDuration            = isDuration;
    utils_hooks__hooks.monthsShort           = lists__listMonthsShort;
    utils_hooks__hooks.weekdaysMin           = lists__listWeekdaysMin;
    utils_hooks__hooks.defineLocale          = defineLocale;
    utils_hooks__hooks.updateLocale          = updateLocale;
    utils_hooks__hooks.locales               = locale_locales__listLocales;
    utils_hooks__hooks.weekdaysShort         = lists__listWeekdaysShort;
    utils_hooks__hooks.normalizeUnits        = normalizeUnits;
    utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold;
    utils_hooks__hooks.prototype             = momentPrototype;

    var _moment = utils_hooks__hooks;

    return _moment;

}));
// source --> https://classified.maalz.com/wp-content/plugins/listingpro-lead-form/assets/js/bootstrap-datetimepicker.min.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/*! version : 4.17.37
 =========================================================
 bootstrap-datetimejs
 https://github.com/Eonasdan/bootstrap-datetimepicker
 Copyright (c) 2015 Jonathan Peterson
 =========================================================
 */
!function(a){"use strict";if("function"==typeof define&&define.amd)define(["jquery","moment"],a);else if("object"==typeof exports)a(require("jquery"),require("moment"));else{if("undefined"==typeof jQuery)throw"bootstrap-datetimepicker requires jQuery to be loaded first";if("undefined"==typeof moment)throw"bootstrap-datetimepicker requires Moment.js to be loaded first";a(jQuery,moment)}}(function(a,b){"use strict";if(!b)throw new Error("bootstrap-datetimepicker requires Moment.js to be loaded first");var c=function(c,d){var e,f,g,h,i,j,k,l={},m=!0,n=!1,o=!1,p=0,q=[{clsName:"days",navFnc:"M",navStep:1},{clsName:"months",navFnc:"y",navStep:1},{clsName:"years",navFnc:"y",navStep:10},{clsName:"decades",navFnc:"y",navStep:100}],r=["days","months","years","decades"],s=["top","bottom","auto"],t=["left","right","auto"],u=["default","top","bottom"],v={up:38,38:"up",down:40,40:"down",left:37,37:"left",right:39,39:"right",tab:9,9:"tab",escape:27,27:"escape",enter:13,13:"enter",pageUp:33,33:"pageUp",pageDown:34,34:"pageDown",shift:16,16:"shift",control:17,17:"control",space:32,32:"space",t:84,84:"t","delete":46,46:"delete"},w={},x=function(a){var c,e,f,g,h,i=!1;return void 0!==b.tz&&void 0!==d.timeZone&&null!==d.timeZone&&""!==d.timeZone&&(i=!0),void 0===a||null===a?c=i?b().tz(d.timeZone).startOf("d"):b().startOf("d"):i?(e=b().tz(d.timeZone).utcOffset(),f=b(a,j,d.useStrict).utcOffset(),f!==e?(g=b().tz(d.timeZone).format("Z"),h=b(a,j,d.useStrict).format("YYYY-MM-DD[T]HH:mm:ss")+g,c=b(h,j,d.useStrict).tz(d.timeZone)):c=b(a,j,d.useStrict).tz(d.timeZone)):c=b(a,j,d.useStrict),c},y=function(a){if("string"!=typeof a||a.length>1)throw new TypeError("isEnabled expects a single character string parameter");switch(a){case"y":return-1!==i.indexOf("Y");case"M":return-1!==i.indexOf("M");case"d":return-1!==i.toLowerCase().indexOf("d");case"h":case"H":return-1!==i.toLowerCase().indexOf("h");case"m":return-1!==i.indexOf("m");case"s":return-1!==i.indexOf("s");default:return!1}},z=function(){return y("h")||y("m")||y("s")},A=function(){return y("y")||y("M")||y("d")},B=function(){var b=a("<thead>").append(a("<tr>").append(a("<th>").addClass("prev").attr("data-action","previous").append(a("<span>").addClass(d.icons.previous))).append(a("<th>").addClass("picker-switch").attr("data-action","pickerSwitch").attr("colspan",d.calendarWeeks?"6":"5")).append(a("<th>").addClass("next").attr("data-action","next").append(a("<span>").addClass(d.icons.next)))),c=a("<tbody>").append(a("<tr>").append(a("<td>").attr("colspan",d.calendarWeeks?"8":"7")));return[a("<div>").addClass("datepicker-days").append(a("<table>").addClass("table-condensed").append(b).append(a("<tbody>"))),a("<div>").addClass("datepicker-months").append(a("<table>").addClass("table-condensed").append(b.clone()).append(c.clone())),a("<div>").addClass("datepicker-years").append(a("<table>").addClass("table-condensed").append(b.clone()).append(c.clone())),a("<div>").addClass("datepicker-decades").append(a("<table>").addClass("table-condensed").append(b.clone()).append(c.clone()))]},C=function(){var b=a("<tr>"),c=a("<tr>"),e=a("<tr>");return y("h")&&(b.append(a("<td>").append(a("<a>").attr({href:"#",tabindex:"-1",title:d.tooltips.incrementHour}).addClass("btn").attr("data-action","incrementHours").append(a("<span>").addClass(d.icons.up)))),c.append(a("<td>").append(a("<span>").addClass("timepicker-hour").attr({"data-time-component":"hours",title:d.tooltips.pickHour}).attr("data-action","showHours"))),e.append(a("<td>").append(a("<a>").attr({href:"#",tabindex:"-1",title:d.tooltips.decrementHour}).addClass("btn").attr("data-action","decrementHours").append(a("<span>").addClass(d.icons.down))))),y("m")&&(y("h")&&(b.append(a("<td>").addClass("separator")),c.append(a("<td>").addClass("separator").html(":")),e.append(a("<td>").addClass("separator"))),b.append(a("<td>").append(a("<a>").attr({href:"#",tabindex:"-1",title:d.tooltips.incrementMinute}).addClass("btn").attr("data-action","incrementMinutes").append(a("<span>").addClass(d.icons.up)))),c.append(a("<td>").append(a("<span>").addClass("timepicker-minute").attr({"data-time-component":"minutes",title:d.tooltips.pickMinute}).attr("data-action","showMinutes"))),e.append(a("<td>").append(a("<a>").attr({href:"#",tabindex:"-1",title:d.tooltips.decrementMinute}).addClass("btn").attr("data-action","decrementMinutes").append(a("<span>").addClass(d.icons.down))))),y("s")&&(y("m")&&(b.append(a("<td>").addClass("separator")),c.append(a("<td>").addClass("separator").html(":")),e.append(a("<td>").addClass("separator"))),b.append(a("<td>").append(a("<a>").attr({href:"#",tabindex:"-1",title:d.tooltips.incrementSecond}).addClass("btn").attr("data-action","incrementSeconds").append(a("<span>").addClass(d.icons.up)))),c.append(a("<td>").append(a("<span>").addClass("timepicker-second").attr({"data-time-component":"seconds",title:d.tooltips.pickSecond}).attr("data-action","showSeconds"))),e.append(a("<td>").append(a("<a>").attr({href:"#",tabindex:"-1",title:d.tooltips.decrementSecond}).addClass("btn").attr("data-action","decrementSeconds").append(a("<span>").addClass(d.icons.down))))),h||(b.append(a("<td>").addClass("separator")),c.append(a("<td>").append(a("<button>").addClass("btn btn-primary").attr({"data-action":"togglePeriod",tabindex:"-1",title:d.tooltips.togglePeriod}))),e.append(a("<td>").addClass("separator"))),a("<div>").addClass("timepicker-picker").append(a("<table>").addClass("table-condensed").append([b,c,e]))},D=function(){var b=a("<div>").addClass("timepicker-hours").append(a("<table>").addClass("table-condensed")),c=a("<div>").addClass("timepicker-minutes").append(a("<table>").addClass("table-condensed")),d=a("<div>").addClass("timepicker-seconds").append(a("<table>").addClass("table-condensed")),e=[C()];return y("h")&&e.push(b),y("m")&&e.push(c),y("s")&&e.push(d),e},E=function(){var b=[];return d.showTodayButton&&b.push(a("<td>").append(a("<a>").attr({"data-action":"today",title:d.tooltips.today}).append(a("<span>").addClass(d.icons.today)))),!d.sideBySide&&A()&&z()&&b.push(a("<td>").append(a("<a>").attr({"data-action":"togglePicker",title:d.tooltips.selectTime}).append(a("<span>").addClass(d.icons.time)))),d.showClear&&b.push(a("<td>").append(a("<a>").attr({"data-action":"clear",title:d.tooltips.clear}).append(a("<span>").addClass(d.icons.clear)))),d.showClose&&b.push(a("<td>").append(a("<a>").attr({"data-action":"close",title:d.tooltips.close}).append(a("<span>").addClass(d.icons.close)))),a("<table>").addClass("table-condensed").append(a("<tbody>").append(a("<tr>").append(b)))},F=function(){var b=a("<div>").addClass("bootstrap-datetimepicker-widget dropdown-menu"),c=a("<div>").addClass("datepicker").append(B()),e=a("<div>").addClass("timepicker").append(D()),f=a("<ul>").addClass("list-unstyled"),g=a("<li>").addClass("picker-switch"+(d.collapse?" accordion-toggle":"")).append(E());return d.inline&&b.removeClass("dropdown-menu"),h&&b.addClass("usetwentyfour"),y("s")&&!h&&b.addClass("wider"),d.sideBySide&&A()&&z()?(b.addClass("timepicker-sbs"),"top"===d.toolbarPlacement&&b.append(g),b.append(a("<div>").addClass("row").append(c.addClass("col-md-6")).append(e.addClass("col-md-6"))),"bottom"===d.toolbarPlacement&&b.append(g),b):("top"===d.toolbarPlacement&&f.append(g),A()&&f.append(a("<li>").addClass(d.collapse&&z()?"collapse in":"").append(c)),"default"===d.toolbarPlacement&&f.append(g),z()&&f.append(a("<li>").addClass(d.collapse&&A()?"collapse":"").append(e)),"bottom"===d.toolbarPlacement&&f.append(g),b.append(f))},G=function(){var b,e={};return b=c.is("input")||d.inline?c.data():c.find("input").data(),b.dateOptions&&b.dateOptions instanceof Object&&(e=a.extend(!0,e,b.dateOptions)),a.each(d,function(a){var c="date"+a.charAt(0).toUpperCase()+a.slice(1);void 0!==b[c]&&(e[a]=b[c])}),e},H=function(){var b,e=(n||c).position(),f=(n||c).offset(),g=d.widgetPositioning.vertical,h=d.widgetPositioning.horizontal;if(d.widgetParent)b=d.widgetParent.append(o);else if(c.is("input"))b=c.after(o).parent();else{if(d.inline)return void(b=c.append(o));b=c,c.children().first().after(o)}if("auto"===g&&(g=f.top+1.5*o.height()>=a(window).height()+a(window).scrollTop()&&o.height()+c.outerHeight()<f.top?"top":"bottom"),"auto"===h&&(h=b.width()<f.left+o.outerWidth()/2&&f.left+o.outerWidth()>a(window).width()?"right":"left"),"top"===g?o.addClass("top").removeClass("bottom"):o.addClass("bottom").removeClass("top"),"right"===h?o.addClass("pull-right"):o.removeClass("pull-right"),"relative"!==b.css("position")&&(b=b.parents().filter(function(){return"relative"===a(this).css("position")}).first()),0===b.length)throw new Error("datetimepicker component should be placed within a relative positioned container");o.css({top:"top"===g?"auto":e.top+c.outerHeight(),bottom:"top"===g?e.top+c.outerHeight():"auto",left:"left"===h?b===c?0:e.left:"auto",right:"left"===h?"auto":b.outerWidth()-c.outerWidth()-(b===c?0:e.left)})},I=function(a){"dp.change"===a.type&&(a.date&&a.date.isSame(a.oldDate)||!a.date&&!a.oldDate)||c.trigger(a)},J=function(a){"y"===a&&(a="YYYY"),I({type:"dp.update",change:a,viewDate:f.clone()})},K=function(a){o&&(a&&(k=Math.max(p,Math.min(3,k+a))),o.find(".datepicker > div").hide().filter(".datepicker-"+q[k].clsName).show())},L=function(){var b=a("<tr>"),c=f.clone().startOf("w").startOf("d");for(d.calendarWeeks===!0&&b.append(a("<th>").addClass("cw").text("#"));c.isBefore(f.clone().endOf("w"));)b.append(a("<th>").addClass("dow").text(c.format("dd"))),c.add(1,"d");o.find(".datepicker-days thead").append(b)},M=function(a){return d.disabledDates[a.format("YYYY-MM-DD")]===!0},N=function(a){return d.enabledDates[a.format("YYYY-MM-DD")]===!0},O=function(a){return d.disabledHours[a.format("H")]===!0},P=function(a){return d.enabledHours[a.format("H")]===!0},Q=function(b,c){if(!b.isValid())return!1;if(d.disabledDates&&"d"===c&&M(b))return!1;if(d.enabledDates&&"d"===c&&!N(b))return!1;if(d.minDate&&b.isBefore(d.minDate,c))return!1;if(d.maxDate&&b.isAfter(d.maxDate,c))return!1;if(d.daysOfWeekDisabled&&"d"===c&&-1!==d.daysOfWeekDisabled.indexOf(b.day()))return!1;if(d.disabledHours&&("h"===c||"m"===c||"s"===c)&&O(b))return!1;if(d.enabledHours&&("h"===c||"m"===c||"s"===c)&&!P(b))return!1;if(d.disabledTimeIntervals&&("h"===c||"m"===c||"s"===c)){var e=!1;if(a.each(d.disabledTimeIntervals,function(){return b.isBetween(this[0],this[1])?(e=!0,!1):void 0}),e)return!1}return!0},R=function(){for(var b=[],c=f.clone().startOf("y").startOf("d");c.isSame(f,"y");)b.push(a("<span>").attr("data-action","selectMonth").addClass("month").text(c.format("MMM"))),c.add(1,"M");o.find(".datepicker-months td").empty().append(b)},S=function(){var b=o.find(".datepicker-months"),c=b.find("th"),g=b.find("tbody").find("span");c.eq(0).find("span").attr("title",d.tooltips.prevYear),c.eq(1).attr("title",d.tooltips.selectYear),c.eq(2).find("span").attr("title",d.tooltips.nextYear),b.find(".disabled").removeClass("disabled"),Q(f.clone().subtract(1,"y"),"y")||c.eq(0).addClass("disabled"),c.eq(1).text(f.year()),Q(f.clone().add(1,"y"),"y")||c.eq(2).addClass("disabled"),g.removeClass("active"),e.isSame(f,"y")&&!m&&g.eq(e.month()).addClass("active"),g.each(function(b){Q(f.clone().month(b),"M")||a(this).addClass("disabled")})},T=function(){var a=o.find(".datepicker-years"),b=a.find("th"),c=f.clone().subtract(5,"y"),g=f.clone().add(6,"y"),h="";for(b.eq(0).find("span").attr("title",d.tooltips.prevDecade),b.eq(1).attr("title",d.tooltips.selectDecade),b.eq(2).find("span").attr("title",d.tooltips.nextDecade),a.find(".disabled").removeClass("disabled"),d.minDate&&d.minDate.isAfter(c,"y")&&b.eq(0).addClass("disabled"),b.eq(1).text(c.year()+"-"+g.year()),d.maxDate&&d.maxDate.isBefore(g,"y")&&b.eq(2).addClass("disabled");!c.isAfter(g,"y");)h+='<span data-action="selectYear" class="year'+(c.isSame(e,"y")&&!m?" active":"")+(Q(c,"y")?"":" disabled")+'">'+c.year()+"</span>",c.add(1,"y");a.find("td").html(h)},U=function(){var a=o.find(".datepicker-decades"),c=a.find("th"),g=b({y:f.year()-f.year()%100-1}),h=g.clone().add(100,"y"),i=g.clone(),j="";for(c.eq(0).find("span").attr("title",d.tooltips.prevCentury),c.eq(2).find("span").attr("title",d.tooltips.nextCentury),a.find(".disabled").removeClass("disabled"),(g.isSame(b({y:1900}))||d.minDate&&d.minDate.isAfter(g,"y"))&&c.eq(0).addClass("disabled"),c.eq(1).text(g.year()+"-"+h.year()),(g.isSame(b({y:2e3}))||d.maxDate&&d.maxDate.isBefore(h,"y"))&&c.eq(2).addClass("disabled");!g.isAfter(h,"y");)j+='<span data-action="selectDecade" class="decade'+(g.isSame(e,"y")?" active":"")+(Q(g,"y")?"":" disabled")+'" data-selection="'+(g.year()+6)+'">'+(g.year()+1)+" - "+(g.year()+12)+"</span>",g.add(12,"y");j+="<span></span><span></span><span></span>",a.find("td").html(j),c.eq(1).text(i.year()+1+"-"+g.year())},V=function(){var b,c,g,h,i=o.find(".datepicker-days"),j=i.find("th"),k=[];if(A()){for(j.eq(0).find("span").attr("title",d.tooltips.prevMonth),j.eq(1).attr("title",d.tooltips.selectMonth),j.eq(2).find("span").attr("title",d.tooltips.nextMonth),i.find(".disabled").removeClass("disabled"),j.eq(1).text(f.format(d.dayViewHeaderFormat)),Q(f.clone().subtract(1,"M"),"M")||j.eq(0).addClass("disabled"),Q(f.clone().add(1,"M"),"M")||j.eq(2).addClass("disabled"),b=f.clone().startOf("M").startOf("w").startOf("d"),h=0;42>h;h++)0===b.weekday()&&(c=a("<tr>"),d.calendarWeeks&&c.append('<td class="cw">'+b.week()+"</td>"),k.push(c)),g="",b.isBefore(f,"M")&&(g+=" old"),b.isAfter(f,"M")&&(g+=" new"),b.isSame(e,"d")&&!m&&(g+=" active"),Q(b,"d")||(g+=" disabled"),b.isSame(x(),"d")&&(g+=" today"),(0===b.day()||6===b.day())&&(g+=" weekend"),c.append('<td data-action="selectDay" data-day="'+b.format("L")+'" class="day'+g+'">'+b.date()+"</td>"),b.add(1,"d");i.find("tbody").empty().append(k),S(),T(),U()}},W=function(){var b=o.find(".timepicker-hours table"),c=f.clone().startOf("d"),d=[],e=a("<tr>");for(f.hour()>11&&!h&&c.hour(12);c.isSame(f,"d")&&(h||f.hour()<12&&c.hour()<12||f.hour()>11);)c.hour()%4===0&&(e=a("<tr>"),d.push(e)),e.append('<td data-action="selectHour" class="hour'+(Q(c,"h")?"":" disabled")+'">'+c.format(h?"HH":"hh")+"</td>"),c.add(1,"h");b.empty().append(d)},X=function(){for(var b=o.find(".timepicker-minutes table"),c=f.clone().startOf("h"),e=[],g=a("<tr>"),h=1===d.stepping?5:d.stepping;f.isSame(c,"h");)c.minute()%(4*h)===0&&(g=a("<tr>"),e.push(g)),g.append('<td data-action="selectMinute" class="minute'+(Q(c,"m")?"":" disabled")+'">'+c.format("mm")+"</td>"),c.add(h,"m");b.empty().append(e)},Y=function(){for(var b=o.find(".timepicker-seconds table"),c=f.clone().startOf("m"),d=[],e=a("<tr>");f.isSame(c,"m");)c.second()%20===0&&(e=a("<tr>"),d.push(e)),e.append('<td data-action="selectSecond" class="second'+(Q(c,"s")?"":" disabled")+'">'+c.format("ss")+"</td>"),c.add(5,"s");b.empty().append(d)},Z=function(){var a,b,c=o.find(".timepicker span[data-time-component]");h||(a=o.find(".timepicker [data-action=togglePeriod]"),b=e.clone().add(e.hours()>=12?-12:12,"h"),a.text(e.format("A")),Q(b,"h")?a.removeClass("disabled"):a.addClass("disabled")),c.filter("[data-time-component=hours]").text(e.format(h?"HH":"hh")),c.filter("[data-time-component=minutes]").text(e.format("mm")),c.filter("[data-time-component=seconds]").text(e.format("ss")),W(),X(),Y()},$=function(){o&&(V(),Z())},_=function(a){var b=m?null:e;return a?(a=a.clone().locale(d.locale),1!==d.stepping&&a.minutes(Math.round(a.minutes()/d.stepping)*d.stepping%60).seconds(0),void(Q(a)?(e=a,f=e.clone(),g.val(e.format(i)),c.data("date",e.format(i)),m=!1,$(),I({type:"dp.change",date:e.clone(),oldDate:b})):(d.keepInvalid||g.val(m?"":e.format(i)),I({type:"dp.error",date:a})))):(m=!0,g.val(""),c.data("date",""),I({type:"dp.change",date:!1,oldDate:b}),void $())},aa=function(){var b=!1;return o?(o.find(".collapse").each(function(){var c=a(this).data("collapse");return c&&c.transitioning?(b=!0,!1):!0}),b?l:(n&&n.hasClass("btn")&&n.toggleClass("active"),o.hide(),a(window).off("resize",H),o.off("click","[data-action]"),o.off("mousedown",!1),o.remove(),o=!1,I({type:"dp.hide",date:e.clone()}),g.blur(),l)):l},ba=function(){_(null)},ca={next:function(){var a=q[k].navFnc;f.add(q[k].navStep,a),V(),J(a)},previous:function(){var a=q[k].navFnc;f.subtract(q[k].navStep,a),V(),J(a)},pickerSwitch:function(){K(1)},selectMonth:function(b){var c=a(b.target).closest("tbody").find("span").index(a(b.target));f.month(c),k===p?(_(e.clone().year(f.year()).month(f.month())),d.inline||aa()):(K(-1),V()),J("M")},selectYear:function(b){var c=parseInt(a(b.target).text(),10)||0;f.year(c),k===p?(_(e.clone().year(f.year())),d.inline||aa()):(K(-1),V()),J("YYYY")},selectDecade:function(b){var c=parseInt(a(b.target).data("selection"),10)||0;f.year(c),k===p?(_(e.clone().year(f.year())),d.inline||aa()):(K(-1),V()),J("YYYY")},selectDay:function(b){var c=f.clone();a(b.target).is(".old")&&c.subtract(1,"M"),a(b.target).is(".new")&&c.add(1,"M"),_(c.date(parseInt(a(b.target).text(),10))),z()||d.keepOpen||d.inline||aa()},incrementHours:function(){var a=e.clone().add(1,"h");Q(a,"h")&&_(a)},incrementMinutes:function(){var a=e.clone().add(d.stepping,"m");Q(a,"m")&&_(a)},incrementSeconds:function(){var a=e.clone().add(1,"s");Q(a,"s")&&_(a)},decrementHours:function(){var a=e.clone().subtract(1,"h");Q(a,"h")&&_(a)},decrementMinutes:function(){var a=e.clone().subtract(d.stepping,"m");Q(a,"m")&&_(a)},decrementSeconds:function(){var a=e.clone().subtract(1,"s");Q(a,"s")&&_(a)},togglePeriod:function(){_(e.clone().add(e.hours()>=12?-12:12,"h"))},togglePicker:function(b){var c,e=a(b.target),f=e.closest("ul"),g=f.find(".in"),h=f.find(".collapse:not(.in)");if(g&&g.length){if(c=g.data("collapse"),c&&c.transitioning)return;g.collapse?(g.collapse("hide"),h.collapse("show")):(g.removeClass("in"),h.addClass("in")),e.is("span")?e.toggleClass(d.icons.time+" "+d.icons.date):e.find("span").toggleClass(d.icons.time+" "+d.icons.date)}},showPicker:function(){o.find(".timepicker > div:not(.timepicker-picker)").hide(),o.find(".timepicker .timepicker-picker").show()},showHours:function(){o.find(".timepicker .timepicker-picker").hide(),o.find(".timepicker .timepicker-hours").show()},showMinutes:function(){o.find(".timepicker .timepicker-picker").hide(),o.find(".timepicker .timepicker-minutes").show()},showSeconds:function(){o.find(".timepicker .timepicker-picker").hide(),o.find(".timepicker .timepicker-seconds").show()},selectHour:function(b){var c=parseInt(a(b.target).text(),10);h||(e.hours()>=12?12!==c&&(c+=12):12===c&&(c=0)),_(e.clone().hours(c)),ca.showPicker.call(l)},selectMinute:function(b){_(e.clone().minutes(parseInt(a(b.target).text(),10))),ca.showPicker.call(l)},selectSecond:function(b){_(e.clone().seconds(parseInt(a(b.target).text(),10))),ca.showPicker.call(l)},clear:ba,today:function(){var a=x();Q(a,"d")&&_(a)},close:aa},da=function(b){return a(b.currentTarget).is(".disabled")?!1:(ca[a(b.currentTarget).data("action")].apply(l,arguments),!1)},ea=function(){var b,c={year:function(a){return a.month(0).date(1).hours(0).seconds(0).minutes(0)},month:function(a){return a.date(1).hours(0).seconds(0).minutes(0)},day:function(a){return a.hours(0).seconds(0).minutes(0)},hour:function(a){return a.seconds(0).minutes(0)},minute:function(a){return a.seconds(0)}};return g.prop("disabled")||!d.ignoreReadonly&&g.prop("readonly")||o?l:(void 0!==g.val()&&0!==g.val().trim().length?_(ga(g.val().trim())):d.useCurrent&&m&&(g.is("input")&&0===g.val().trim().length||d.inline)&&(b=x(),"string"==typeof d.useCurrent&&(b=c[d.useCurrent](b)),_(b)),o=F(),L(),R(),o.find(".timepicker-hours").hide(),o.find(".timepicker-minutes").hide(),o.find(".timepicker-seconds").hide(),$(),K(),a(window).on("resize",H),o.on("click","[data-action]",da),o.on("mousedown",!1),n&&n.hasClass("btn")&&n.toggleClass("active"),o.show(),H(),d.focusOnShow&&!g.is(":focus")&&g.focus(),I({type:"dp.show"}),l)},fa=function(){return o?aa():ea()},ga=function(a){return a=void 0===d.parseInputDate?b.isMoment(a)||a instanceof Date?b(a):x(a):d.parseInputDate(a),a.locale(d.locale),a},ha=function(a){var b,c,e,f,g=null,h=[],i={},j=a.which,k="p";w[j]=k;for(b in w)w.hasOwnProperty(b)&&w[b]===k&&(h.push(b),parseInt(b,10)!==j&&(i[b]=!0));for(b in d.keyBinds)if(d.keyBinds.hasOwnProperty(b)&&"function"==typeof d.keyBinds[b]&&(e=b.split(" "),e.length===h.length&&v[j]===e[e.length-1])){for(f=!0,c=e.length-2;c>=0;c--)if(!(v[e[c]]in i)){f=!1;break}if(f){g=d.keyBinds[b];break}}g&&(g.call(l,o),a.stopPropagation(),a.preventDefault())},ia=function(a){w[a.which]="r",a.stopPropagation(),a.preventDefault()},ja=function(b){var c=a(b.target).val().trim(),d=c?ga(c):null;return _(d),b.stopImmediatePropagation(),!1},ka=function(){g.on({change:ja,blur:d.debug?"":aa,keydown:ha,keyup:ia,focus:d.allowInputToggle?ea:""}),c.is("input")?g.on({focus:ea}):n&&(n.on("click",fa),n.on("mousedown",!1))},la=function(){g.off({change:ja,blur:blur,keydown:ha,keyup:ia,focus:d.allowInputToggle?aa:""}),c.is("input")?g.off({focus:ea}):n&&(n.off("click",fa),n.off("mousedown",!1))},ma=function(b){var c={};return a.each(b,function(){var a=ga(this);a.isValid()&&(c[a.format("YYYY-MM-DD")]=!0)}),Object.keys(c).length?c:!1},na=function(b){var c={};return a.each(b,function(){c[this]=!0}),Object.keys(c).length?c:!1},oa=function(){var a=d.format||"L LT";i=a.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,function(a){var b=e.localeData().longDateFormat(a)||a;return b.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,function(a){return e.localeData().longDateFormat(a)||a})}),j=d.extraFormats?d.extraFormats.slice():[],j.indexOf(a)<0&&j.indexOf(i)<0&&j.push(i),h=i.toLowerCase().indexOf("a")<1&&i.replace(/\[.*?\]/g,"").indexOf("h")<1,y("y")&&(p=2),y("M")&&(p=1),y("d")&&(p=0),k=Math.max(p,k),m||_(e)};if(l.destroy=function(){aa(),la(),c.removeData("DateTimePicker"),c.removeData("date")},l.toggle=fa,l.show=ea,l.hide=aa,l.disable=function(){return aa(),n&&n.hasClass("btn")&&n.addClass("disabled"),g.prop("disabled",!0),l},l.enable=function(){return n&&n.hasClass("btn")&&n.removeClass("disabled"),g.prop("disabled",!1),l},l.ignoreReadonly=function(a){if(0===arguments.length)return d.ignoreReadonly;if("boolean"!=typeof a)throw new TypeError("ignoreReadonly () expects a boolean parameter");return d.ignoreReadonly=a,l},l.options=function(b){if(0===arguments.length)return a.extend(!0,{},d);if(!(b instanceof Object))throw new TypeError("options() options parameter should be an object");return a.extend(!0,d,b),a.each(d,function(a,b){if(void 0===l[a])throw new TypeError("option "+a+" is not recognized!");l[a](b)}),l},l.date=function(a){if(0===arguments.length)return m?null:e.clone();if(!(null===a||"string"==typeof a||b.isMoment(a)||a instanceof Date))throw new TypeError("date() parameter must be one of [null, string, moment or Date]");return _(null===a?null:ga(a)),l},l.format=function(a){if(0===arguments.length)return d.format;if("string"!=typeof a&&("boolean"!=typeof a||a!==!1))throw new TypeError("format() expects a sting or boolean:false parameter "+a);return d.format=a,i&&oa(),l},l.timeZone=function(a){return 0===arguments.length?d.timeZone:(d.timeZone=a,l)},l.dayViewHeaderFormat=function(a){if(0===arguments.length)return d.dayViewHeaderFormat;if("string"!=typeof a)throw new TypeError("dayViewHeaderFormat() expects a string parameter");return d.dayViewHeaderFormat=a,l},l.extraFormats=function(a){if(0===arguments.length)return d.extraFormats;if(a!==!1&&!(a instanceof Array))throw new TypeError("extraFormats() expects an array or false parameter");return d.extraFormats=a,j&&oa(),l},l.disabledDates=function(b){if(0===arguments.length)return d.disabledDates?a.extend({},d.disabledDates):d.disabledDates;if(!b)return d.disabledDates=!1,$(),l;if(!(b instanceof Array))throw new TypeError("disabledDates() expects an array parameter");return d.disabledDates=ma(b),d.enabledDates=!1,$(),l},l.enabledDates=function(b){if(0===arguments.length)return d.enabledDates?a.extend({},d.enabledDates):d.enabledDates;if(!b)return d.enabledDates=!1,$(),l;if(!(b instanceof Array))throw new TypeError("enabledDates() expects an array parameter");return d.enabledDates=ma(b),d.disabledDates=!1,$(),l},l.daysOfWeekDisabled=function(a){if(0===arguments.length)return d.daysOfWeekDisabled.splice(0);if("boolean"==typeof a&&!a)return d.daysOfWeekDisabled=!1,$(),l;if(!(a instanceof Array))throw new TypeError("daysOfWeekDisabled() expects an array parameter");if(d.daysOfWeekDisabled=a.reduce(function(a,b){return b=parseInt(b,10),b>6||0>b||isNaN(b)?a:(-1===a.indexOf(b)&&a.push(b),a)},[]).sort(),d.useCurrent&&!d.keepInvalid){for(var b=0;!Q(e,"d");){if(e.add(1,"d"),7===b)throw"Tried 7 times to find a valid date";b++}_(e)}return $(),l},l.maxDate=function(a){if(0===arguments.length)return d.maxDate?d.maxDate.clone():d.maxDate;if("boolean"==typeof a&&a===!1)return d.maxDate=!1,$(),l;"string"==typeof a&&("now"===a||"moment"===a)&&(a=x());var b=ga(a);if(!b.isValid())throw new TypeError("maxDate() Could not parse date parameter: "+a);if(d.minDate&&b.isBefore(d.minDate))throw new TypeError("maxDate() date parameter is before options.minDate: "+b.format(i));return d.maxDate=b,d.useCurrent&&!d.keepInvalid&&e.isAfter(a)&&_(d.maxDate),f.isAfter(b)&&(f=b.clone().subtract(d.stepping,"m")),$(),l},l.minDate=function(a){if(0===arguments.length)return d.minDate?d.minDate.clone():d.minDate;if("boolean"==typeof a&&a===!1)return d.minDate=!1,$(),l;"string"==typeof a&&("now"===a||"moment"===a)&&(a=x());var b=ga(a);if(!b.isValid())throw new TypeError("minDate() Could not parse date parameter: "+a);if(d.maxDate&&b.isAfter(d.maxDate))throw new TypeError("minDate() date parameter is after options.maxDate: "+b.format(i));return d.minDate=b,d.useCurrent&&!d.keepInvalid&&e.isBefore(a)&&_(d.minDate),f.isBefore(b)&&(f=b.clone().add(d.stepping,"m")),$(),l},l.defaultDate=function(a){if(0===arguments.length)return d.defaultDate?d.defaultDate.clone():d.defaultDate;if(!a)return d.defaultDate=!1,l;"string"==typeof a&&("now"===a||"moment"===a)&&(a=x());var b=ga(a);if(!b.isValid())throw new TypeError("defaultDate() Could not parse date parameter: "+a);if(!Q(b))throw new TypeError("defaultDate() date passed is invalid according to component setup validations");return d.defaultDate=b,(d.defaultDate&&d.inline||""===g.val().trim())&&_(d.defaultDate),l},l.locale=function(a){if(0===arguments.length)return d.locale;if(!b.localeData(a))throw new TypeError("locale() locale "+a+" is not loaded from moment locales!");return d.locale=a,e.locale(d.locale),f.locale(d.locale),i&&oa(),o&&(aa(),ea()),l},l.stepping=function(a){return 0===arguments.length?d.stepping:(a=parseInt(a,10),(isNaN(a)||1>a)&&(a=1),d.stepping=a,l)},l.useCurrent=function(a){var b=["year","month","day","hour","minute"];if(0===arguments.length)return d.useCurrent;if("boolean"!=typeof a&&"string"!=typeof a)throw new TypeError("useCurrent() expects a boolean or string parameter");if("string"==typeof a&&-1===b.indexOf(a.toLowerCase()))throw new TypeError("useCurrent() expects a string parameter of "+b.join(", "));return d.useCurrent=a,l},l.collapse=function(a){if(0===arguments.length)return d.collapse;if("boolean"!=typeof a)throw new TypeError("collapse() expects a boolean parameter");return d.collapse===a?l:(d.collapse=a,o&&(aa(),ea()),l)},l.icons=function(b){if(0===arguments.length)return a.extend({},d.icons);if(!(b instanceof Object))throw new TypeError("icons() expects parameter to be an Object");return a.extend(d.icons,b),o&&(aa(),ea()),l},l.tooltips=function(b){if(0===arguments.length)return a.extend({},d.tooltips);if(!(b instanceof Object))throw new TypeError("tooltips() expects parameter to be an Object");return a.extend(d.tooltips,b),o&&(aa(),ea()),l},l.useStrict=function(a){if(0===arguments.length)return d.useStrict;if("boolean"!=typeof a)throw new TypeError("useStrict() expects a boolean parameter");return d.useStrict=a,l},l.sideBySide=function(a){if(0===arguments.length)return d.sideBySide;if("boolean"!=typeof a)throw new TypeError("sideBySide() expects a boolean parameter");return d.sideBySide=a,o&&(aa(),ea()),l},l.viewMode=function(a){if(0===arguments.length)return d.viewMode;if("string"!=typeof a)throw new TypeError("viewMode() expects a string parameter");if(-1===r.indexOf(a))throw new TypeError("viewMode() parameter must be one of ("+r.join(", ")+") value");return d.viewMode=a,k=Math.max(r.indexOf(a),p),K(),l},l.toolbarPlacement=function(a){if(0===arguments.length)return d.toolbarPlacement;if("string"!=typeof a)throw new TypeError("toolbarPlacement() expects a string parameter");if(-1===u.indexOf(a))throw new TypeError("toolbarPlacement() parameter must be one of ("+u.join(", ")+") value");return d.toolbarPlacement=a,o&&(aa(),ea()),l},l.widgetPositioning=function(b){if(0===arguments.length)return a.extend({},d.widgetPositioning);if("[object Object]"!=={}.toString.call(b))throw new TypeError("widgetPositioning() expects an object variable");if(b.horizontal){if("string"!=typeof b.horizontal)throw new TypeError("widgetPositioning() horizontal variable must be a string");if(b.horizontal=b.horizontal.toLowerCase(),-1===t.indexOf(b.horizontal))throw new TypeError("widgetPositioning() expects horizontal parameter to be one of ("+t.join(", ")+")");d.widgetPositioning.horizontal=b.horizontal}if(b.vertical){if("string"!=typeof b.vertical)throw new TypeError("widgetPositioning() vertical variable must be a string");if(b.vertical=b.vertical.toLowerCase(),-1===s.indexOf(b.vertical))throw new TypeError("widgetPositioning() expects vertical parameter to be one of ("+s.join(", ")+")");d.widgetPositioning.vertical=b.vertical}return $(),l},l.calendarWeeks=function(a){if(0===arguments.length)return d.calendarWeeks;if("boolean"!=typeof a)throw new TypeError("calendarWeeks() expects parameter to be a boolean value");return d.calendarWeeks=a,$(),l},l.showTodayButton=function(a){if(0===arguments.length)return d.showTodayButton;if("boolean"!=typeof a)throw new TypeError("showTodayButton() expects a boolean parameter");return d.showTodayButton=a,o&&(aa(),ea()),l},l.showClear=function(a){if(0===arguments.length)return d.showClear;if("boolean"!=typeof a)throw new TypeError("showClear() expects a boolean parameter");return d.showClear=a,o&&(aa(),ea()),l},l.widgetParent=function(b){if(0===arguments.length)return d.widgetParent;if("string"==typeof b&&(b=a(b)),null!==b&&"string"!=typeof b&&!(b instanceof a))throw new TypeError("widgetParent() expects a string or a jQuery object parameter");return d.widgetParent=b,o&&(aa(),ea()),l},l.keepOpen=function(a){if(0===arguments.length)return d.keepOpen;if("boolean"!=typeof a)throw new TypeError("keepOpen() expects a boolean parameter");return d.keepOpen=a,l},l.focusOnShow=function(a){if(0===arguments.length)return d.focusOnShow;if("boolean"!=typeof a)throw new TypeError("focusOnShow() expects a boolean parameter");return d.focusOnShow=a,l},l.inline=function(a){if(0===arguments.length)return d.inline;if("boolean"!=typeof a)throw new TypeError("inline() expects a boolean parameter");return d.inline=a,l},l.clear=function(){return ba(),l},l.keyBinds=function(a){return d.keyBinds=a,l},l.getMoment=function(a){return x(a)},l.debug=function(a){if("boolean"!=typeof a)throw new TypeError("debug() expects a boolean parameter");return d.debug=a,l},l.allowInputToggle=function(a){if(0===arguments.length)return d.allowInputToggle;if("boolean"!=typeof a)throw new TypeError("allowInputToggle() expects a boolean parameter");return d.allowInputToggle=a,l},l.showClose=function(a){if(0===arguments.length)return d.showClose;if("boolean"!=typeof a)throw new TypeError("showClose() expects a boolean parameter");return d.showClose=a,l},l.keepInvalid=function(a){if(0===arguments.length)return d.keepInvalid;if("boolean"!=typeof a)throw new TypeError("keepInvalid() expects a boolean parameter");return d.keepInvalid=a,l},l.datepickerInput=function(a){if(0===arguments.length)return d.datepickerInput;if("string"!=typeof a)throw new TypeError("datepickerInput() expects a string parameter");return d.datepickerInput=a,l},l.parseInputDate=function(a){if(0===arguments.length)return d.parseInputDate;
if("function"!=typeof a)throw new TypeError("parseInputDate() sholud be as function");return d.parseInputDate=a,l},l.disabledTimeIntervals=function(b){if(0===arguments.length)return d.disabledTimeIntervals?a.extend({},d.disabledTimeIntervals):d.disabledTimeIntervals;if(!b)return d.disabledTimeIntervals=!1,$(),l;if(!(b instanceof Array))throw new TypeError("disabledTimeIntervals() expects an array parameter");return d.disabledTimeIntervals=b,$(),l},l.disabledHours=function(b){if(0===arguments.length)return d.disabledHours?a.extend({},d.disabledHours):d.disabledHours;if(!b)return d.disabledHours=!1,$(),l;if(!(b instanceof Array))throw new TypeError("disabledHours() expects an array parameter");if(d.disabledHours=na(b),d.enabledHours=!1,d.useCurrent&&!d.keepInvalid){for(var c=0;!Q(e,"h");){if(e.add(1,"h"),24===c)throw"Tried 24 times to find a valid date";c++}_(e)}return $(),l},l.enabledHours=function(b){if(0===arguments.length)return d.enabledHours?a.extend({},d.enabledHours):d.enabledHours;if(!b)return d.enabledHours=!1,$(),l;if(!(b instanceof Array))throw new TypeError("enabledHours() expects an array parameter");if(d.enabledHours=na(b),d.disabledHours=!1,d.useCurrent&&!d.keepInvalid){for(var c=0;!Q(e,"h");){if(e.add(1,"h"),24===c)throw"Tried 24 times to find a valid date";c++}_(e)}return $(),l},l.viewDate=function(a){if(0===arguments.length)return f.clone();if(!a)return f=e.clone(),l;if(!("string"==typeof a||b.isMoment(a)||a instanceof Date))throw new TypeError("viewDate() parameter must be one of [string, moment or Date]");return f=ga(a),J(),l},c.is("input"))g=c;else if(g=c.find(d.datepickerInput),0===g.size())g=c.find("input");else if(!g.is("input"))throw new Error('CSS class "'+d.datepickerInput+'" cannot be applied to non input element');if(c.hasClass("input-group")&&(n=0===c.find(".datepickerbutton").size()?c.find(".input-group-addon"):c.find(".datepickerbutton")),!d.inline&&!g.is("input"))throw new Error("Could not initialize DateTimePicker without an input element");return e=x(),f=e.clone(),a.extend(!0,d,G()),l.options(d),oa(),ka(),g.prop("disabled")&&l.disable(),g.is("input")&&0!==g.val().trim().length?_(ga(g.val().trim())):d.defaultDate&&void 0===g.attr("placeholder")&&_(d.defaultDate),d.inline&&ea(),l};a.fn.datetimepicker=function(b){return this.each(function(){var d=a(this);d.data("DateTimePicker")||(b=a.extend(!0,{},a.fn.datetimepicker.defaults,b),d.data("DateTimePicker",c(d,b)))})},a.fn.datetimepicker.defaults={timeZone:"Etc/UTC",format:!1,dayViewHeaderFormat:"MMMM YYYY",extraFormats:!1,stepping:1,minDate:!1,maxDate:!1,useCurrent:!0,collapse:!0,locale:b.locale(),defaultDate:!1,disabledDates:!1,enabledDates:!1,icons:{time:"glyphicon glyphicon-time",date:"glyphicon glyphicon-calendar",up:"glyphicon glyphicon-chevron-up",down:"glyphicon glyphicon-chevron-down",previous:"glyphicon glyphicon-chevron-left",next:"glyphicon glyphicon-chevron-right",today:"glyphicon glyphicon-screenshot",clear:"glyphicon glyphicon-trash",close:"glyphicon glyphicon-remove"},tooltips:{today:"Go to today",clear:"Clear selection",close:"Close the picker",selectMonth:"Select Month",prevMonth:"Previous Month",nextMonth:"Next Month",selectYear:"Select Year",prevYear:"Previous Year",nextYear:"Next Year",selectDecade:"Select Decade",prevDecade:"Previous Decade",nextDecade:"Next Decade",prevCentury:"Previous Century",nextCentury:"Next Century",pickHour:"Pick Hour",incrementHour:"Increment Hour",decrementHour:"Decrement Hour",pickMinute:"Pick Minute",incrementMinute:"Increment Minute",decrementMinute:"Decrement Minute",pickSecond:"Pick Second",incrementSecond:"Increment Second",decrementSecond:"Decrement Second",togglePeriod:"Toggle Period",selectTime:"Select Time"},useStrict:!1,sideBySide:!1,daysOfWeekDisabled:!1,calendarWeeks:!1,viewMode:"days",toolbarPlacement:"default",showTodayButton:!1,showClear:!1,showClose:!1,widgetPositioning:{horizontal:"auto",vertical:"auto"},widgetParent:null,ignoreReadonly:!1,keepOpen:!1,focusOnShow:!0,inline:!1,keepInvalid:!1,datepickerInput:".datepickerinput",keyBinds:{up:function(a){if(a){var b=this.date()||this.getMoment();a.find(".datepicker").is(":visible")?this.date(b.clone().subtract(7,"d")):this.date(b.clone().add(this.stepping(),"m"))}},down:function(a){if(!a)return void this.show();var b=this.date()||this.getMoment();a.find(".datepicker").is(":visible")?this.date(b.clone().add(7,"d")):this.date(b.clone().subtract(this.stepping(),"m"))},"control up":function(a){if(a){var b=this.date()||this.getMoment();a.find(".datepicker").is(":visible")?this.date(b.clone().subtract(1,"y")):this.date(b.clone().add(1,"h"))}},"control down":function(a){if(a){var b=this.date()||this.getMoment();a.find(".datepicker").is(":visible")?this.date(b.clone().add(1,"y")):this.date(b.clone().subtract(1,"h"))}},left:function(a){if(a){var b=this.date()||this.getMoment();a.find(".datepicker").is(":visible")&&this.date(b.clone().subtract(1,"d"))}},right:function(a){if(a){var b=this.date()||this.getMoment();a.find(".datepicker").is(":visible")&&this.date(b.clone().add(1,"d"))}},pageUp:function(a){if(a){var b=this.date()||this.getMoment();a.find(".datepicker").is(":visible")&&this.date(b.clone().subtract(1,"M"))}},pageDown:function(a){if(a){var b=this.date()||this.getMoment();a.find(".datepicker").is(":visible")&&this.date(b.clone().add(1,"M"))}},enter:function(){this.hide()},escape:function(){this.hide()},"control space":function(a){a.find(".timepicker").is(":visible")&&a.find('.btn[data-action="togglePeriod"]').click()},t:function(){this.date(this.getMoment())},"delete":function(){this.clear()}},debug:!1,allowInputToggle:!1,disabledTimeIntervals:!1,disabledHours:!1,enabledHours:!1,viewDate:!1}});
// source --> https://classified.maalz.com/wp-content/plugins/listingpro-plugin/assets/js/auto-places.js?ver=4fca74de5e3fa981b9659807f09e9e55 
function lpinitMapPlaces() {
    var myElem = document.getElementById('lp_listing_map');
    if (myElem === null) {} else {
        var map = new google.maps.Map(document.getElementById('lp_listing_map'), {
            center: {
                lat: -33.8688,
                lng: 151.2195
            },
            zoom: 13
        });
        var input = document.getElementById('lptitleGoogle');
        var autocomplete = new google.maps.places.Autocomplete(input);
        var service = new google.maps.places.PlacesService(map);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                window.alert("No details available for input: '" + place.name + "'");
                return
            }
            place_id = place.place_id;
            service.getDetails({
                placeId: place_id
            }, function(place, status) {
                jQuery('input[name="postTitle"]').val(place.name);

                /* console.log(place.geometry.location.lat());
                console.log(place.geometry.location.lng()); */
                /* console.log(place.name);
                console.log(place); */
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    var marker = new google.maps.Marker({
                        map: map,
                        position: place.geometry.location
                    });
                    if (!place.formatted_phone_number) {} else {
                        jQuery('input[name=phone]').val(place.formatted_phone_number)
                    }
                    var arrAddress = place.address_components;
                    var arrayLength = arrAddress.length;
                    if (arrAddress[1]) {
                        for (var i = 0; i < arrayLength; i++) {
                            if (arrAddress[i].types[0] === "locality") {
                                var city = arrAddress[i].short_name;
                                jQuery('input[name=locationn]').val(city);
                                jQuery('input[name=location]').val(city);
                                jQuery('input[name=locationn]').data('isseleted', true);
                            }
                        }
                    }
                    if (!place.formatted_address) {} else {
                        jQuery('input[name=gAddress]').val(place.formatted_address);
                        jQuery('input[name=latitude]').val(place.geometry.location.lat());
                        jQuery('input[name=longitude]').val(place.geometry.location.lng());

                    }
                    if (!place.website) {} else {
                        jQuery('input[name=website]').val(place.website)
                    }
                    if (!place.types) {} else {

                        for (var i = 0, len = place.types.length; i < len; i++) {
                            var option = document.createElement("option");
                            if (place.types[i] == "point_of_interest") {} else if (place.types[i] == "establishment") {} else {
                                option.text = place.types[i];
                                option.value = place.types[i];
                                var attSelected = document.createAttribute("selected");
                                attSelected.value = "selected";
                                option.setAttributeNode(attSelected);
                                var select = document.getElementById("inputCategory");
                                select.appendChild(option);
                                jQuery("#inputCategory").change();
                                jQuery("#inputCategory").select2();
                            }
                        }
                    }
                    if (!place.photos) {} else {
                        for (var i = 0, len = place.photos.length; i < len; i++) {
                            var imgURL = place.photos[i].getUrl({
                                'maxWidth': 500,
                                'maxHeight': 500
                            });
                            var output = document.getElementById("filediv");
                            var div = document.createElement("ul");
                            div.className = 'jFiler-items-list jFiler-items-grid grid' + i;
                            div.innerHTML = '<li class="jFiler-item">\
												<div class="jFiler-item-container">\
													<div class="jFiler-item-inner">\
														<div class="jFiler-item-thumb">\
															 <img  class="thumbnail" alt="image" src="' + imgURL + '" title="' + place.name + '"/>\
														</div>\
													</div>\
												</div><a class="icon-jfi-trash jFiler-item-trash-action"><i class="fa fa-trash"></i></a>\
											</li>';
                            //output.insertBefore(div, null)
                        }
                    }
                }
            })
        })
    }
}
lpinitMapPlaces();
// source --> https://classified.maalz.com/wp-content/plugins/cubewp-framework/cube/assets/frontend/js/cubewp-alerts.js?ver=1.1.29 
jQuery(document).ready(function () {
    jQuery(document).on("click", ".cwp-alert .cwp-alert-close", function () {
        var $this = jQuery(this),
            $parent = $this.closest('.cwp-alert');
        $parent.slideUp(200, function () {
            if ($parent.hasClass("cwp-js-alert")) {
                $parent.hide();
            } else {
                $parent.remove();
            }
        });
    });

    jQuery(document).on('click', '.cubewp-modal-trigger', function (event) {
        event.preventDefault();
        var $this = jQuery(this),
            target = jQuery($this.attr('data-cubewp-modal'));
        if (target.length > 0) {
            target.addClass('shown').fadeIn();
        }
    });
    jQuery(document).on('click', '.cubewp-modal-close', function (event) {
        event.preventDefault();
        var $this = jQuery(this),
            target = $this.closest('.cubewp-modal');
        target.removeClass('shown').fadeOut();
    });

    var view_all_child_terms = jQuery('.cwp-taxonomy-term-child-terms-see-more');
    if (view_all_child_terms.length > 0) {
        view_all_child_terms.on('click', function (e) {
            e.preventDefault();
            var $this = jQuery(this),
                more = $this.attr('data-more'),
                less = $this.attr('data-less'),
                all_child_terms = $this.closest('.cwp-taxonomy-term-child-terms').find('.cwp-taxonomy-term-child-terms-more');
            if ($this.hasClass('cwp-viewing-less')) {
                $this.text(more);
                $this.removeClass('cwp-viewing-less');
                all_child_terms.slideUp('hide');
            } else {
                $this.text(less);
                $this.addClass('cwp-viewing-less');
                all_child_terms.slideDown('show');
            }
        });
    }

});

function cwp_notification_ui(notification_type, notification_content) {
    var $cwp_alert = jQuery(".cwp-alert.cwp-js-alert"),
        $alert_class = '',
        $cwp_alert_content = $cwp_alert.find('.cwp-alert-content');

    if ($cwp_alert.is(":visible") && $cwp_alert_content.html() === notification_content) {
        return false;
    }
    if ($cwp_alert.is(":visible")) {
        $cwp_alert.find('.cwp-alert-close').trigger("click");
    }
    if (notification_type === 'success') {
        $alert_class = 'cwp-alert-success';
    } else if (notification_type === 'warning') {
        $alert_class = 'cwp-alert-warning';
    } else if (notification_type === 'info') {
        $alert_class = 'cwp-alert-info';
    } else if (notification_type === 'error') {
        $alert_class = 'cwp-alert-danger';
    }
    $cwp_alert.removeClass("cwp-alert-danger cwp-alert-success cwp-alert-warning cwp-alert-info").addClass($alert_class);
    $cwp_alert.find('.cwp-alert-heading').text(notification_type + "!");
    $cwp_alert_content.html(notification_content);
    $cwp_alert.slideDown();
    setTimeout(function () {
        $cwp_alert.find('.cwp-alert-close').trigger("click");
    }, 3000);
}

jQuery(document).on('click', '.cwp-post-confirmation-wrap .cwp-confirmation-bottom-bar', function (e) {
    jQuery('.cwp-post-confirmation').slideToggle(700);
});
jQuery(document).on('click', '.cwp-post-confirmation-wrap .cwp-confirmation-bottom-bar', function (e) {
    jQuery('.cwp-post-confirmation').slideToggle(700);
});
jQuery(document).on('click', '.cwp-save-post', function (e) {
    var thisObj = jQuery(this);
    var pid = thisObj.data('pid');
    thisObj.addClass('cubewp-active-ajax');
    jQuery.ajax({
        url: cwp_alert_ui_params.ajax_url,
        type: 'POST',
        data: 'action=cubewp_save_post&post-id=' + pid + '&nonce=' + cwp_alert_ui_params.nonce,
        dataType: "json",
        success: function (response) {
            cwp_notification_ui(response.type, response.msg);
            if (typeof response.text != 'undefined' && response.text != '') {
                thisObj.addClass('cwp-saved-post');
                thisObj.removeClass('cwp-save-post');
                thisObj.find('.cwp-saved-text').html(response.text);
                thisObj.removeClass('cubewp-active-ajax');
            }
        }
    });
});
jQuery(document).on('click', '.cwp-saved-post', function (e) {
    var thisObj = jQuery(this);
    var pid = thisObj.data('pid');
    var action = thisObj.data('action');
    thisObj.addClass('cubewp-active-ajax');
    jQuery.ajax({
        url: cwp_alert_ui_params.ajax_url,
        type: 'POST',
        data: 'action=cubewp_remove_saved_posts&post-id=' + pid + '&nonce=' + cwp_alert_ui_params.nonce,
        dataType: "json",
        success: function (response) {
            cwp_notification_ui(response.type, response.msg);
            if (typeof response.text != 'undefined' && response.text != '') {
                if (action == 'remove') {
                    thisObj.closest('tr').remove();
                }
                thisObj.addClass('cwp-save-post');
                thisObj.removeClass('cwp-saved-post');
                thisObj.find('.cwp-saved-text').html(response.text);
                thisObj.removeClass('cubewp-active-ajax');
            }
        }
    });
});

/*-------- Mega Menu and Nav Menu --------*/
// CubeWP Menus JS >>
jQuery(document).ready(function ($) {
    jQuery(document).on(
        "click",
        ".elementor-cubewp-menu-toggle__icon--open",
        function () {
            jQuery(this).next("svg").addClass("active");
            jQuery(this).removeClass("active");
            jQuery(this)
                .closest(".elementor-cubewp-menu-toggle")
                .next(".elementor-cubewp-nav-menu--dropdown")
                .addClass("active");
        }
    );
    jQuery(document).on(
        "click",
        ".elementor-cubewp-menu-toggle__icon--close",
        function () {
            jQuery(this).prev("svg").addClass("active");
            jQuery(this).removeClass("active");
            jQuery(this)
                .closest(".elementor-cubewp-menu-toggle")
                .next(".elementor-cubewp-nav-menu--dropdown")
                .removeClass("active");
        }
    );
    jQuery(document).on("click", ".cubwp-menu-desktop.mobile", function () {
        jQuery(this)
            .closest(".elementor-widget-container")
            .find(".cubewp-offcanvas-menus")
            .addClass("active");
    });
    jQuery(document).on("click", ".cubewp-menu-closed", function () {
        jQuery(this)
            .closest(".elementor-widget-container")
            .find(".cubewp-offcanvas-menus")
            .removeClass("active");
    });

    $(document).on("click", ".cubewp-mega-menu-item.hover", function (event) {
        if ($(window).width() <= 1024) {
            if (!$(event.target).closest(".cubewp-mega-menu-item-dropdown").length) {
                $(this).toggleClass("active");
                $(this).closest('.cubewp-mega-menu').toggleClass("active");
            }
        }
    });
    $(document).on("click", ".close-mega-menu-mobile", function (event) {
        if ($(window).width() <= 1024) {
            $('.cubewp-mega-menu-item , .cubewp-mega-menu').removeClass("active");
        }
    });
    jQuery(document).ready(function ($) {
        // Open the next slide when clicking the trigger
        $(document).on("click", ".container-next-triger", function () {
            $(this)
                .closest(".elementor-element")
                .next(".container-next-screen")
                .addClass("active");
        });
        // Close the slide when clicking the back button
        $(document).on("click", ".container-back-slide", function (e) {
            if ($(window).width() <= 1024) {
                e.preventDefault();
                setTimeout(() => {
                    if ($(this).closest(".container-next-screen").length > 0) {
                        $(this).closest(".container-next-screen").removeClass("active");
                    } else {
                        $(this).closest(".cubewp-mega-menu").removeClass("active");
                        $(this).closest(".cubewp-mega-menu-item").removeClass("active");
                    }
                }, 200);
            }
        });
    });

    // CubeWP Mega menus JS >>
    jQuery(document).on(
        "click",
        ".cubewp-mega-menu .cubewp-mega-menu-item.click",
        function () {
            var getID = jQuery(this).data("showid");
            jQuery(this)
                .closest(".cubewp-mega-menu")
                .find(".cubewp-mega-menu-item-dropdown")
                .removeClass("active");
            jQuery(this)
                .closest(".cubewp-mega-menu")
                .find(".cubewp-mega-menu-item-dropdown")
                .removeClass("init");
            jQuery(this)
                .closest(".cubewp-mega-menu")
                .find(".cubewp-mega-menu-item.click")
                .removeClass("active");
            jQuery("#" + getID).addClass("active");
            jQuery(document.body).trigger("cubewp_mega_menu_item_loaded");
            jQuery(this).addClass("active");
            setTimeout(function () {
                jQuery("#" + getID).addClass("init");
            }, 500);
        }
    );

    jQuery(document).on(
        "click",
        ".cubewp-mega-menu-mobile-button",
        function () {
            jQuery(this).next(".cubewp-mega-menu.cubwp-menu-desktop").slideToggle();
            jQuery(this).toggleClass("active");
        }
    );

    function adjustMegaMenuDropdown($this) {
        var dropdown = $this.find(".cubewp-mega-menu-item-dropdown");
        if (dropdown.length) {
            var bodyWidth = jQuery("body").width(); // Get the full width of the body
            var dropdownOffsetLeft = dropdown.offset().left; // Current left position of the dropdown
            var bodyOffsetLeft = jQuery("body").offset().left; // Body's left position (should be 0)
            var difference = dropdownOffsetLeft - bodyOffsetLeft;

            // Adjust the dropdown's width and position to span the entire body width
            dropdown.css({
                "left": "-" + difference + "px",
                "right": "auto",
                "width": bodyWidth + "px"
            });
        }
    }

    jQuery(document).on("mouseenter", ".cubewp-mega-menu-item", function () {
        var $this = jQuery(this);
        adjustMegaMenuDropdown($this);
    });

    jQuery(document).on("mouseleave", ".cubewp-mega-menu-item", function () {
        jQuery(this).find(".cubewp-mega-menu-item-dropdown").css({
            "left": "unset",
        });
    });

    setTimeout(function () {
        if (jQuery(".elementor-cubewp-nav-menu__container").length > 0) {
            var get_iconsInd = jQuery(".elementor-cubewp-nav-menu__container").data(
                "icons"
            );
            if (typeof get_iconsInd === "string") {
                get_iconsInd = get_iconsInd.trim().replace(/1$/, "");
            }
            jQuery(".elementor-cubewp-nav-menu__container")
                .find(".menu-item-has-children>a")
                .append(get_iconsInd);
        }
    }, 200);
});

/*------- CubeWP Post Slider ---------*/
function initPostSlider($scope, clicked) {
    var sliders = $scope.find('.cubewp-post-slider');
    if (!sliders.length) return;
    sliders.each(function () {
        var sliderElement = jQuery(this);

        if (sliderElement.hasClass('slick-initialized')) {
            if (clicked == 'clicked') {
                sliderElement.slick("unslick");
                console.log('have slider');
                sliderElement.addClass('sliderElement');
            } else {
                return;

            }

        }

        var isPrevSvg = sliderElement.data('is-prev-svg');
        var isNextSvg = sliderElement.data('is-next-svg');

        var prevArrowHtml = isPrevSvg ? sliderElement.attr('data-prev-arrow-svg') : sliderElement.data('prev-arrow');

        var nextArrowHtml = isNextSvg ? sliderElement.attr('data-next-arrow-svg') : sliderElement.data('next-arrow');

        var enable_wrapper = sliderElement.data('enable-wrapper');
        var slidesToShow = sliderElement.data('slides-to-show');
        var slidesToScroll = sliderElement.data('slides-to-scroll');
        var slidesToShowTablet = sliderElement.data('slides-to-show-tablet');
        var slidesToShowTabletPortrait = sliderElement.data('slides-show-tablet-portrait');
        var slidesToShowMobile = sliderElement.data('slides-to-show-mobile');
        var slidesToScrollTablet = sliderElement.data('slides-to-scroll-tablet');
        var slidesToScrollTabletPortrait = sliderElement.data('slides-scroll-tablet-portrait');
        var slidesToScrollMobile = sliderElement.data('slides-to-scroll-mobile');
        var autoplay = sliderElement.data('autoplay') === true || sliderElement.data('autoplay') === 'true';
        var autoplaySpeed = sliderElement.data('autoplay-speed');
        var Speed = sliderElement.data('speed');
        var infinite = sliderElement.data('infinite') === true || sliderElement.data('infinite') === 'true';
        var fade_effect = sliderElement.data('fade') === true || sliderElement.data('fade') === 'true';
        var variableWidth = sliderElement.data('variable-width') === true || sliderElement.data('variable-width') === 'true';
        var prevArrowButton, nextArrowButton;

        if (isPrevSvg) {
            prevArrowButton = '<button type="button" class="slick-prev">' + prevArrowHtml + '</button>';
        } else {
            prevArrowButton = '<button type="button" class="slick-prev"><i class="' + prevArrowHtml + '"></i></button>';
        }

        if (isNextSvg) {
            nextArrowButton = '<button type="button" class="slick-next">' + nextArrowHtml + '</button>';
        } else {
            nextArrowButton = '<button type="button" class="slick-next"><i class="' + nextArrowHtml + '"></i></button>';
        }
        var CustomArrows = sliderElement.data('custom-arrows') === true || sliderElement.data('custom-arrows') === 'true';
        var CustomDots = sliderElement.data('custom-dots') === true || sliderElement.data('custom-dots') === 'true';
        var enableProgressBar = sliderElement.data('enable-progress-bar') === true || sliderElement.data('enable-progress-bar') === 'true';
        sliderElement.slick({
            slidesToShow: slidesToShow,
            slidesToScroll: slidesToScroll,
            autoplay: autoplay,
            autoplaySpeed: autoplaySpeed,
            speed: Speed,
            infinite: infinite,
            fade: fade_effect,
            variableWidth: variableWidth,
            prevArrow: prevArrowButton,
            nextArrow: nextArrowButton,
            arrows: CustomArrows,
            dots: CustomDots,
            responsive: [{
                    breakpoint: 1025,
                    settings: {
                        slidesToShow: slidesToShowTablet,
                        slidesToScroll: slidesToScrollTablet
                    }
                },
                {
                    breakpoint: 768,
                    settings: {
                        slidesToShow: slidesToShowTabletPortrait,
                        slidesToScroll: slidesToScrollTabletPortrait
                    }
                },
                {
                    breakpoint: 481,
                    settings: {
                        slidesToShow: slidesToShowMobile,
                        slidesToScroll: slidesToScrollMobile
                    }
                }
            ]
        });

        if (enableProgressBar == true) {
            if (!sliderElement.next('.slick-progress').length) {
                sliderElement.after(
                    '<div class="slick-progress"><div class="slick-progress-bar"></div></div>'
                );
                var totalSlides = sliderElement.slick("getSlick").slideCount;
                sliderElement.on("afterChange", function (event, slick, currentSlide) {
                    var progress = ((currentSlide + 1) / totalSlides) * 100;
                    sliderElement.next('.slick-progress').find('.slick-progress-bar').css("width", progress + "%");
                });
            }
        }
        if (enable_wrapper == true) {
            sliderElement.append('<div class="slick-arrows-wrapper"></div>');
            sliderElement.find(".slick-prev").appendTo(sliderElement.find(".slick-arrows-wrapper"));
            sliderElement.find(".slick-dots").appendTo(sliderElement.find(".slick-arrows-wrapper"));
            sliderElement.find(".slick-next").appendTo(sliderElement.find(".slick-arrows-wrapper"));
        }
    });
    if (clicked == 'clicked') {
        jQuery(document).trigger("post_slider_initialized", [$scope]);
    }
}
(function ($) {
    // Expose initPostSlider to a global object if needed outside Elementor's scope
    if (typeof window.CubeWp === 'undefined') {
        window.CubeWp = {};
    }
    window.CubeWp.initPostSlider = initPostSlider;

    // Hook for Elementor frontend and editor
    jQuery(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/cubewp_posts.default', initPostSlider);
    });
})(jQuery);

var CubeWpShortcodePostsAjax = {
    loadPosts: function (containerSelector) {
        var $container = jQuery(containerSelector);
        var parameters = $container.data('parameters');
        if (parameters) {
            jQuery.ajax({
                url: cwp_alert_ui_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'cubewp_posts_output',
                    ...parameters,
                    load_via_ajax: 'yes'
                },
                success: function (response) {
                    if (response.success) {
                        $container.replaceWith(response.data.content);
                        initPostSlider(jQuery(document.body));
                        jQuery(document.body).trigger('cubewp_posts_loaded');
                    } else {
                        $container.html('<div class="cubewp-error-card">Error loading posts.</div>');
                    }
                },
                error: function () {
                    $container.html('<div class="cubewp-error-card">Failed to load posts.</div>');
                }
            });
        }
    }
};
jQuery(document).on("click", ".vpack-nested-tabs  .e-n-tab-title", function () {
    var $dataid = jQuery(this).attr('aria-controls');
    var $sliderContainer = jQuery(this).closest('.elementor-element').find('#' + $dataid);
    var clicked = 'clicked';
    if (jQuery(this).hasClass('init-clicked')) {
        return false;
    }
    initPostSlider($sliderContainer, clicked);
    jQuery(this).addClass('init-clicked');
});

/* CubeWP Term Slider */
function initTermSlider($scope, clicked) {
    var sliders = $scope.find('.cubewp-term-slider');
    if (!sliders.length) return;
    sliders.each(function () {
        var sliderElement = jQuery(this);

        if (sliderElement.hasClass('slick-initialized')) {
            if (clicked == 'clicked') {
                sliderElement.slick("unslick");
                console.log('have slider');
                sliderElement.addClass('sliderElement');
            } else {
                return;

            }

        }

        var isPrevSvg = sliderElement.data('is-prev-svg');
        var isNextSvg = sliderElement.data('is-next-svg');

        var prevArrowHtml = isPrevSvg ? sliderElement.attr('data-prev-arrow-svg') : sliderElement.data('prev-arrow');

        var nextArrowHtml = isNextSvg ? sliderElement.attr('data-next-arrow-svg') : sliderElement.data('next-arrow');

        var enable_wrapper = sliderElement.data('enable-wrapper');
        var slidesToShow = sliderElement.data('slides-to-show');
        var slidesToScroll = sliderElement.data('slides-to-scroll');
        var slidesToShowTablet = sliderElement.data('slides-to-show-tablet');
        var slidesToShowTabletPortrait = sliderElement.data('slides-show-tablet-portrait');
        var slidesToShowMobile = sliderElement.data('slides-to-show-mobile');
        var slidesToScrollTablet = sliderElement.data('slides-to-scroll-tablet');
        var slidesToScrollTabletPortrait = sliderElement.data('slides-scroll-tablet-portrait');
        var slidesToScrollMobile = sliderElement.data('slides-to-scroll-mobile');
        var autoplay = sliderElement.data('autoplay') === true || sliderElement.data('autoplay') === 'true';
        var autoplaySpeed = sliderElement.data('autoplay-speed');
        var Speed = sliderElement.data('speed');
        var infinite = sliderElement.data('infinite') === true || sliderElement.data('infinite') === 'true';
        var fade_effect = sliderElement.data('fade') === true || sliderElement.data('fade') === 'true';
        var variableWidth = sliderElement.data('variable-width') === true || sliderElement.data('variable-width') === 'true';
        var prevArrowButton, nextArrowButton;

        if (isPrevSvg) {
            prevArrowButton = '<button type="button" class="slick-prev">' + prevArrowHtml + '</button>';
        } else {
            prevArrowButton = '<button type="button" class="slick-prev"><i class="' + prevArrowHtml + '"></i></button>';
        }

        if (isNextSvg) {
            nextArrowButton = '<button type="button" class="slick-next">' + nextArrowHtml + '</button>';
        } else {
            nextArrowButton = '<button type="button" class="slick-next"><i class="' + nextArrowHtml + '"></i></button>';
        }
        var CustomArrows = sliderElement.data('custom-arrows') === true || sliderElement.data('custom-arrows') === 'true';
        var CustomDots = sliderElement.data('custom-dots') === true || sliderElement.data('custom-dots') === 'true';
        var enableProgressBar = sliderElement.data('enable-progress-bar') === true || sliderElement.data('enable-progress-bar') === 'true';
        sliderElement.slick({
            slidesToShow: slidesToShow,
            slidesToScroll: slidesToScroll,
            autoplay: autoplay,
            autoplaySpeed: autoplaySpeed,
            speed: Speed,
            infinite: infinite,
            fade: fade_effect,
            variableWidth: variableWidth,
            prevArrow: prevArrowButton,
            nextArrow: nextArrowButton,
            arrows: CustomArrows,
            dots: CustomDots,
            responsive: [{
                    breakpoint: 1025,
                    settings: {
                        slidesToShow: slidesToShowTablet,
                        slidesToScroll: slidesToScrollTablet
                    }
                },
                {
                    breakpoint: 768,
                    settings: {
                        slidesToShow: slidesToShowTabletPortrait,
                        slidesToScroll: slidesToScrollTabletPortrait
                    }
                },
                {
                    breakpoint: 481,
                    settings: {
                        slidesToShow: slidesToShowMobile,
                        slidesToScroll: slidesToScrollMobile
                    }
                }
            ]
        });

        if (enableProgressBar == true) {
            if (!sliderElement.next('.slick-progress').length) {
                sliderElement.after(
                    '<div class="slick-progress"><div class="slick-progress-bar"></div></div>'
                );
                var totalSlides = sliderElement.slick("getSlick").slideCount;
                sliderElement.on("afterChange", function (event, slick, currentSlide) {
                    var progress = ((currentSlide + 1) / totalSlides) * 100;
                    sliderElement.next('.slick-progress').find('.slick-progress-bar').css("width", progress + "%");
                });
            }
        }
        if (enable_wrapper == true) {
            sliderElement.append('<div class="slick-arrows-wrapper"></div>');
            sliderElement.find(".slick-prev").appendTo(sliderElement.find(".slick-arrows-wrapper"));
            sliderElement.find(".slick-dots").appendTo(sliderElement.find(".slick-arrows-wrapper"));
            sliderElement.find(".slick-next").appendTo(sliderElement.find(".slick-arrows-wrapper"));
        }
    });
    if (clicked == 'clicked') {
        jQuery(document).trigger("term_slider_initialized", [$scope]);
    }
}
(function ($) {
    // Expose initTermSlider to a global object if needed outside Elementor's scope
    if (typeof window.CubeWp === 'undefined') {
        window.CubeWp = {};
    }
    window.CubeWp.initTermSlider = initTermSlider;

    // Hook for Elementor frontend and editor
    jQuery(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/cubewp_taxonomy.default', initTermSlider);
    });

    // Initialize on document ready for frontend (non-Elementor contexts)
    jQuery(document).ready(function () {
        initTermSlider(jQuery(document.body));
    });

    /* CubeWP Post Cards Hover Effects */
    window.addEventListener('elementor/frontend/init', () => {

        class CubewpHoverHandler extends elementorModules.frontend.handlers.Base {

            onInit() {
                this.applyHoverStyles();
            }

            onElementChange(settingName) {
                const hoverSettings = [
                    'cwp_hover_animation_direction',
                    'cwp_hover_translate_distance',
                    'cwp_hover_transition_duration'
                ];
                if (hoverSettings.includes(settingName)) {
                    this.applyHoverStyles();
                }
            }

            applyHoverStyles() {
                const settings = this.getElementSettings();
                const direction = settings.cwp_hover_animation_direction || 'none';
                const visiblity = settings.cwp_hover_visibility || 'default';

                const $el = this.$element;
                const elementId = this.getID();
                const $card = $el.closest('.cwp-elementor-post-card, .cwp-elementor-term-card');

                if (!$card.length) return;

                // Remove previous bindings for this specific element only
                $card.off(`.cubewpHover_${elementId}`);

                if (direction === 'none') {
                    $el.css({
                        'transform': '',
                        'opacity': '',
                        'transition': ''
                    });
                    if (visiblity === 'show') {
                        $card.on(`mouseenter.cubewpHover_${elementId}`, () => {
                            $el.css({
                                'display': 'flex',
                            });
                        });
                        // Hover Out
                        $card.on(`mouseleave.cubewpHover_${elementId}`, () => {
                            $el.css({
                                'display': 'none',
                            });
                        });
                    } else if (visiblity === 'hide') {
                        $card.on(`mouseenter.cubewpHover_${elementId}`, () => {
                            $el.css({
                                'display': 'none',
                            });
                        });
                        // Hover Out
                        $card.on(`mouseleave.cubewpHover_${elementId}`, () => {
                            $el.css({
                                'display': 'flex',
                            });
                        });
                    }
                    return;
                }

                const distance = settings.cwp_hover_translate_distance ?.size || 30;
                const duration = settings.cwp_hover_transition_duration ?.size || 0.3;

                let transform = '';
                let opacity = '1';

                switch (direction) {
                    case 'top':
                        transform = `translateY(-${distance}px)`;
                        break;
                    case 'bottom':
                        transform = `translateY(${distance}px)`;
                        break;
                    case 'left':
                        transform = `translateX(-${distance}px)`;
                        break;
                    case 'right':
                        transform = `translateX(${distance}px)`;
                        break;
                    case 'fade':
                        opacity = '0';
                        break;
                    case 'fadeout':
                        opacity = '1';
                        break;
                }

                // Apply base styles
                $el.css({
                    'transition': `all ${duration}s ease`,
                    'transform': transform,
                    'opacity': opacity
                });

                // Hover In (applies only for this element)
                $card.on(`mouseenter.cubewpHover_${elementId}`, () => {
                    if (direction === 'fadeout') {
                        // Fade OUT on hover
                        $el.css({
                            'opacity': '0',
                            'transform': 'none',
                        });
                    } else {
                        // All other animations fade/slide IN
                        $el.css({
                            'transform': 'none',
                            'opacity': '1'
                        });
                    }
                });

                // Hover Out
                $card.on(`mouseleave.cubewpHover_${elementId}`, () => {
                    if (direction === 'fadeout') {
                        // Restore visibility when mouse leaves
                        $el.css({
                            'opacity': '1',
                            'transform': transform,
                        });
                    } else {
                        // Return to default (hidden or translated)
                        $el.css({
                            'transform': transform,
                            'opacity': opacity
                        });
                    }
                });
            }
        }

        // Apply to container, button, and icon widgets
        ['container', 'button.default', 'icon.default'].forEach(widget => {
            elementorFrontend.hooks.addAction(`frontend/element_ready/${widget}`, ($scope) => {
                elementorFrontend.elementsHandler.addHandler(CubewpHoverHandler, {
                    $element: $scope
                });
            });
        });
    });

    window.addEventListener('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction('frontend/element_ready/container', function ($scope) {
            if (elementorFrontend.isEditMode()) {
                class ContainerHandler extends elementorModules.frontend.handlers.Base {
                    onInit() {
                        super.onInit();
                        const settings = this.getElementSettings();
                        const cwp_click_target_remove_css_controls = settings.cwp_click_target_remove_css_controls;
                        const cwp_click_target_remove_css_transform = settings.cwp_click_target_remove_css_transform;
                        const cwp_click_target_remove_css_transform_x = settings.cwp_click_target_remove_css_transform_x;
                        const cwp_click_target_remove_css_transition = settings.cwp_click_target_remove_css_transition;
                        if (cwp_click_target_remove_css_controls === 'hide') {
                            $scope.css('display', 'none');
                        } else if (cwp_click_target_remove_css_controls === 'show') {
                            $scope.css('display', 'block');
                        } else if (cwp_click_target_remove_css_controls === 'transform') {
                            $scope.css('transform', 'translateX(' + cwp_click_target_remove_css_transform + 'px)');
                            $scope.css('transform-x', 'translateY(' + cwp_click_target_remove_css_transform_x + 'px)');
                            $scope.css('transition', 'transform ' + cwp_click_target_remove_css_transition + 'ms');
                        }

                    }
                    onElementChange(settingName) {
                        super.onElementChange ?.apply(this, arguments);
                        const sliderSettings = [
                            'cwp_click_target_remove_css_controls',
                            'cwp_click_target_remove_css_transform', 'cwp_click_target_remove_css_transform_x', 'cwp_click_target_remove_css_transform_x'
                        ];

                        if (sliderSettings.includes(settingName)) {
                            this.onInit();
                        }
                    }
                }
                elementorFrontend.elementsHandler.addHandler(ContainerHandler, {
                    $element: $scope
                });
            }
        });
    });

    jQuery(document).ready(function ($) {
        jQuery(document).on('click', '.cwp-elementor-post-card, .cwp-elementor-term-card', function (event) {
            $(this).find('.cwp-click-element[data-cwp-click-enabled="true"]').each(function () {
                const clickable = $(this);
                const targetMode = clickable.data('cwp-target-mode');
                const applyCss = clickable.data('cwp-apply-css');
                if (targetMode === 'parent' && applyCss) {
                    clickable.attr('style', function (i, oldStyle) {
                        return (oldStyle ? oldStyle + '; ' : '') + applyCss;
                    });
                }
            });
        });

        jQuery(document).on('click', '.cwp-click-element[data-cwp-click-enabled="true"]', function (event) {
            const clickable = $(this);
            const targetMode = clickable.data('cwp-target-mode');
            const applyCss = clickable.data('cwp-apply-css');
            if (targetMode === 'current' && applyCss) {
                clickable.attr('style', function (i, oldStyle) {
                    return (oldStyle ? oldStyle + '; ' : '') + applyCss;
                });
            }
        });

        jQuery(document).on('click', '.cwp-click-element[data-cwp-click-enabled="true"]', function (event) {
            const clickable = $(this);
            const targetMode = clickable.data('cwp-target-class');


            var $this_data = $('.cwp-click-element[data-cwp-apply-class="' + targetMode + '"]');
            var $this_data_remove = $('.cwp-click-element[data-cwp-remove-class="' + targetMode + '"]');
            if ($this_data.length > 0) {
                const targetModes = $this_data.data('cwp-target-mode');
                const dataID = $this_data.data('id');
                const applyClass = $this_data.data('cwp-apply-class');
                const applyCss = $this_data.data('cwp-apply-css');
                if (targetModes === 'custom' && applyClass) {
                    const card = $(this).closest('.cwp-elementor-post-card, .cwp-elementor-term-card');
                    const element = card.find('.cwp-click-element[data-id="' + dataID + '"]');
                    element.removeAttr('style');
                    element.attr('style', applyCss);

                }
            }
            if ($this_data_remove.length > 0) {
                const targetModes = $this_data_remove.data('cwp-target-mode');
                const dataID = $this_data_remove.data('id');
                const removeClass = $this_data_remove.data('cwp-remove-class');
                const removeCss = $this_data_remove.data('cwp-remove-css');
                console.log('.cwp-click-element[data-id="' + dataID + '"]');
                if (targetModes === 'custom' && removeClass && $this_data_remove.length > 0) {
                    const card = $(this).closest('.cwp-elementor-post-card, .cwp-elementor-term-card');
                    const element = card.find('.cwp-click-element[data-id="' + dataID + '"]');
                    element.removeAttr('style');
                    element.attr('style', removeCss);
                }
            }
        })
    });

    //Grid/List Switcher
    jQuery(document).on('click', '.cubewp-view-btn', function (e) {
        e.preventDefault();

        var $btn = jQuery(this);
        var view = $btn.data('view');
        var $wrapper = $btn.closest('.cubewp-view-switcher');

        // Active button
        $wrapper.find('.cubewp-view-btn').removeClass('active');
        $btn.addClass('active');

        // Apply view class to archive container
        var $archive = jQuery('.cwp-search-result-output .cwp-grids-container');
        $archive.removeClass('grid-view list-view')
            .addClass(view + '-view ');
    });

})(jQuery);
// source --> https://classified.maalz.com/wp-content/plugins/cubewp-framework/cube/assets/frontend/js/cubewp-recaptcha.js?ver=1.1.29 
var cubewpCaptchaLoaded = function() {
    (function ($) {
        'use strict';
        $.cubewp_recaptcha = $.cubewp_recaptcha || {};

        var captcha_init = $(".cubewp-form-recaptcha");
        if (captcha_init.length > 0) {
            captcha_init.each(function () {
                var captcha_init_id = $(this).attr("id");
                grecaptcha.render(captcha_init_id, {
                    'sitekey' : cubewp_recaptcha_params.site_key,
                });
            });
        }

    })(jQuery);
};
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/mapbox.js?ver=4fca74de5e3fa981b9659807f09e9e55 
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
function corslite(n,t,o){function e(n){return n>=200&&300>n||304===n}function i(){void 0===r.status||e(r.status)?t.call(r,null,r):t.call(r,r,null)}var l=!1;if("undefined"==typeof window.XMLHttpRequest)return t(Error("Browser not supported"));if("undefined"==typeof o){var u=n.match(/^\s*https?:\/\/[^\/]*/);o=u&&u[0]!==location.protocol+"//"+location.domain+(location.port?":"+location.port:"")}var r=new window.XMLHttpRequest;if(o&&!("withCredentials"in r)){r=new window.XDomainRequest;var a=t;t=function(){if(l)a.apply(this,arguments);else{var n=this,t=arguments;setTimeout(function(){a.apply(n,t)},0)}}}return"onload"in r?r.onload=i:r.onreadystatechange=function(){4===r.readyState&&i()},r.onerror=function(n){t.call(this,n||!0,null),t=function(){}},r.onprogress=function(){},r.ontimeout=function(n){t.call(this,n,null),t=function(){}},r.onabort=function(n){t.call(this,n,null),t=function(){}},r.open("GET",n,!0),r.send(null),l=!0,r}"undefined"!=typeof module&&(module.exports=corslite);
},{}],2:[function(require,module,exports){
module.exports=Array.isArray||function(r){return"[object Array]"==Object.prototype.toString.call(r)};
},{}],3:[function(require,module,exports){
!function(t,e,i){var n=t.L,o={};o.version="0.7.7","object"==typeof module&&"object"==typeof module.exports?module.exports=o:"function"==typeof define&&define.amd&&define(o),o.noConflict=function(){return t.L=n,this},t.L=o,o.Util={extend:function(t){var e,i,n,o,s=Array.prototype.slice.call(arguments,1);for(i=0,n=s.length;n>i;i++){o=s[i]||{};for(e in o)o.hasOwnProperty(e)&&(t[e]=o[e])}return t},bind:function(t,e){var i=arguments.length>2?Array.prototype.slice.call(arguments,2):null;return function(){return t.apply(e,i||arguments)}},stamp:function(){var t=0,e="_leaflet_id";return function(i){return i[e]=i[e]||++t,i[e]}}(),invokeEach:function(t,e,i){var n,o;if("object"==typeof t){o=Array.prototype.slice.call(arguments,3);for(n in t)e.apply(i,[n,t[n]].concat(o));return!0}return!1},limitExecByInterval:function(t,e,i){var n,o;return function s(){var a=arguments;return n?void(o=!0):(n=!0,setTimeout(function(){n=!1,o&&(s.apply(i,a),o=!1)},e),void t.apply(i,a))}},falseFn:function(){return!1},formatNum:function(t,e){var i=Math.pow(10,e||5);return Math.round(t*i)/i},trim:function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")},splitWords:function(t){return o.Util.trim(t).split(/\s+/)},setOptions:function(t,e){return t.options=o.extend({},t.options,e),t.options},getParamString:function(t,e,i){var n=[];for(var o in t)n.push(encodeURIComponent(i?o.toUpperCase():o)+"="+encodeURIComponent(t[o]));return(e&&-1!==e.indexOf("?")?"&":"?")+n.join("&")},template:function(t,e){return t.replace(/\{ *([\w_]+) *\}/g,function(t,n){var o=e[n];if(o===i)throw new Error("No value provided for variable "+t);return"function"==typeof o&&(o=o(e)),o})},isArray:Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},emptyImageUrl:"data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="},function(){function e(e){var i,n,o=["webkit","moz","o","ms"];for(i=0;i<o.length&&!n;i++)n=t[o[i]+e];return n}function i(e){var i=+new Date,o=Math.max(0,16-(i-n));return n=i+o,t.setTimeout(e,o)}var n=0,s=t.requestAnimationFrame||e("RequestAnimationFrame")||i,a=t.cancelAnimationFrame||e("CancelAnimationFrame")||e("CancelRequestAnimationFrame")||function(e){t.clearTimeout(e)};o.Util.requestAnimFrame=function(e,n,a,r){return e=o.bind(e,n),a&&s===i?void e():s.call(t,e,r)},o.Util.cancelAnimFrame=function(e){e&&a.call(t,e)}}(),o.extend=o.Util.extend,o.bind=o.Util.bind,o.stamp=o.Util.stamp,o.setOptions=o.Util.setOptions,o.Class=function(){},o.Class.extend=function(t){var e=function(){this.initialize&&this.initialize.apply(this,arguments),this._initHooks&&this.callInitHooks()},i=function(){};i.prototype=this.prototype;var n=new i;n.constructor=e,e.prototype=n;for(var s in this)this.hasOwnProperty(s)&&"prototype"!==s&&(e[s]=this[s]);t.statics&&(o.extend(e,t.statics),delete t.statics),t.includes&&(o.Util.extend.apply(null,[n].concat(t.includes)),delete t.includes),t.options&&n.options&&(t.options=o.extend({},n.options,t.options)),o.extend(n,t),n._initHooks=[];var a=this;return e.__super__=a.prototype,n.callInitHooks=function(){if(!this._initHooksCalled){a.prototype.callInitHooks&&a.prototype.callInitHooks.call(this),this._initHooksCalled=!0;for(var t=0,e=n._initHooks.length;e>t;t++)n._initHooks[t].call(this)}},e},o.Class.include=function(t){o.extend(this.prototype,t)},o.Class.mergeOptions=function(t){o.extend(this.prototype.options,t)},o.Class.addInitHook=function(t){var e=Array.prototype.slice.call(arguments,1),i="function"==typeof t?t:function(){this[t].apply(this,e)};this.prototype._initHooks=this.prototype._initHooks||[],this.prototype._initHooks.push(i)};var s="_leaflet_events";o.Mixin={},o.Mixin.Events={addEventListener:function(t,e,i){if(o.Util.invokeEach(t,this.addEventListener,this,e,i))return this;var n,a,r,h,l,u,c,d=this[s]=this[s]||{},p=i&&i!==this&&o.stamp(i);for(t=o.Util.splitWords(t),n=0,a=t.length;a>n;n++)r={action:e,context:i||this},h=t[n],p?(l=h+"_idx",u=l+"_len",c=d[l]=d[l]||{},c[p]||(c[p]=[],d[u]=(d[u]||0)+1),c[p].push(r)):(d[h]=d[h]||[],d[h].push(r));return this},hasEventListeners:function(t){var e=this[s];return!!e&&(t in e&&e[t].length>0||t+"_idx"in e&&e[t+"_idx_len"]>0)},removeEventListener:function(t,e,i){if(!this[s])return this;if(!t)return this.clearAllEventListeners();if(o.Util.invokeEach(t,this.removeEventListener,this,e,i))return this;var n,a,r,h,l,u,c,d,p,_=this[s],m=i&&i!==this&&o.stamp(i);for(t=o.Util.splitWords(t),n=0,a=t.length;a>n;n++)if(r=t[n],u=r+"_idx",c=u+"_len",d=_[u],e){if(h=m&&d?d[m]:_[r]){for(l=h.length-1;l>=0;l--)h[l].action!==e||i&&h[l].context!==i||(p=h.splice(l,1),p[0].action=o.Util.falseFn);i&&d&&0===h.length&&(delete d[m],_[c]--)}}else delete _[r],delete _[u],delete _[c];return this},clearAllEventListeners:function(){return delete this[s],this},fireEvent:function(t,e){if(!this.hasEventListeners(t))return this;var i,n,a,r,h,l=o.Util.extend({},e,{type:t,target:this}),u=this[s];if(u[t])for(i=u[t].slice(),n=0,a=i.length;a>n;n++)i[n].action.call(i[n].context,l);r=u[t+"_idx"];for(h in r)if(i=r[h].slice())for(n=0,a=i.length;a>n;n++)i[n].action.call(i[n].context,l);return this},addOneTimeEventListener:function(t,e,i){if(o.Util.invokeEach(t,this.addOneTimeEventListener,this,e,i))return this;var n=o.bind(function(){this.removeEventListener(t,e,i).removeEventListener(t,n,i)},this);return this.addEventListener(t,e,i).addEventListener(t,n,i)}},o.Mixin.Events.on=o.Mixin.Events.addEventListener,o.Mixin.Events.off=o.Mixin.Events.removeEventListener,o.Mixin.Events.once=o.Mixin.Events.addOneTimeEventListener,o.Mixin.Events.fire=o.Mixin.Events.fireEvent,function(){var n="ActiveXObject"in t,s=n&&!e.addEventListener,a=navigator.userAgent.toLowerCase(),r=-1!==a.indexOf("webkit"),h=-1!==a.indexOf("chrome"),l=-1!==a.indexOf("phantom"),u=-1!==a.indexOf("android"),c=-1!==a.search("android [23]"),d=-1!==a.indexOf("gecko"),p=typeof orientation!=i+"",_=!t.PointerEvent&&t.MSPointerEvent,m=t.PointerEvent&&t.navigator.pointerEnabled||_,f="devicePixelRatio"in t&&t.devicePixelRatio>1||"matchMedia"in t&&t.matchMedia("(min-resolution:144dpi)")&&t.matchMedia("(min-resolution:144dpi)").matches,g=e.documentElement,v=n&&"transition"in g.style,y="WebKitCSSMatrix"in t&&"m11"in new t.WebKitCSSMatrix&&!c,P="MozPerspective"in g.style,L="OTransition"in g.style,x=!t.L_DISABLE_3D&&(v||y||P||L)&&!l,w=!t.L_NO_TOUCH&&!l&&(m||"ontouchstart"in t||t.DocumentTouch&&e instanceof t.DocumentTouch);o.Browser={ie:n,ielt9:s,webkit:r,gecko:d&&!r&&!t.opera&&!n,android:u,android23:c,chrome:h,ie3d:v,webkit3d:y,gecko3d:P,opera3d:L,any3d:x,mobile:p,mobileWebkit:p&&r,mobileWebkit3d:p&&y,mobileOpera:p&&t.opera,touch:w,msPointer:_,pointer:m,retina:f}}(),o.Point=function(t,e,i){this.x=i?Math.round(t):t,this.y=i?Math.round(e):e},o.Point.prototype={clone:function(){return new o.Point(this.x,this.y)},add:function(t){return this.clone()._add(o.point(t))},_add:function(t){return this.x+=t.x,this.y+=t.y,this},subtract:function(t){return this.clone()._subtract(o.point(t))},_subtract:function(t){return this.x-=t.x,this.y-=t.y,this},divideBy:function(t){return this.clone()._divideBy(t)},_divideBy:function(t){return this.x/=t,this.y/=t,this},multiplyBy:function(t){return this.clone()._multiplyBy(t)},_multiplyBy:function(t){return this.x*=t,this.y*=t,this},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},distanceTo:function(t){t=o.point(t);var e=t.x-this.x,i=t.y-this.y;return Math.sqrt(e*e+i*i)},equals:function(t){return t=o.point(t),t.x===this.x&&t.y===this.y},contains:function(t){return t=o.point(t),Math.abs(t.x)<=Math.abs(this.x)&&Math.abs(t.y)<=Math.abs(this.y)},toString:function(){return"Point("+o.Util.formatNum(this.x)+", "+o.Util.formatNum(this.y)+")"}},o.point=function(t,e,n){return t instanceof o.Point?t:o.Util.isArray(t)?new o.Point(t[0],t[1]):t===i||null===t?t:new o.Point(t,e,n)},o.Bounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},o.Bounds.prototype={extend:function(t){return t=o.point(t),this.min||this.max?(this.min.x=Math.min(t.x,this.min.x),this.max.x=Math.max(t.x,this.max.x),this.min.y=Math.min(t.y,this.min.y),this.max.y=Math.max(t.y,this.max.y)):(this.min=t.clone(),this.max=t.clone()),this},getCenter:function(t){return new o.Point((this.min.x+this.max.x)/2,(this.min.y+this.max.y)/2,t)},getBottomLeft:function(){return new o.Point(this.min.x,this.max.y)},getTopRight:function(){return new o.Point(this.max.x,this.min.y)},getSize:function(){return this.max.subtract(this.min)},contains:function(t){var e,i;return t="number"==typeof t[0]||t instanceof o.Point?o.point(t):o.bounds(t),t instanceof o.Bounds?(e=t.min,i=t.max):e=i=t,e.x>=this.min.x&&i.x<=this.max.x&&e.y>=this.min.y&&i.y<=this.max.y},intersects:function(t){t=o.bounds(t);var e=this.min,i=this.max,n=t.min,s=t.max,a=s.x>=e.x&&n.x<=i.x,r=s.y>=e.y&&n.y<=i.y;return a&&r},isValid:function(){return!(!this.min||!this.max)}},o.bounds=function(t,e){return!t||t instanceof o.Bounds?t:new o.Bounds(t,e)},o.Transformation=function(t,e,i,n){this._a=t,this._b=e,this._c=i,this._d=n},o.Transformation.prototype={transform:function(t,e){return this._transform(t.clone(),e)},_transform:function(t,e){return e=e||1,t.x=e*(this._a*t.x+this._b),t.y=e*(this._c*t.y+this._d),t},untransform:function(t,e){return e=e||1,new o.Point((t.x/e-this._b)/this._a,(t.y/e-this._d)/this._c)}},o.DomUtil={get:function(t){return"string"==typeof t?e.getElementById(t):t},getStyle:function(t,i){var n=t.style[i];if(!n&&t.currentStyle&&(n=t.currentStyle[i]),(!n||"auto"===n)&&e.defaultView){var o=e.defaultView.getComputedStyle(t,null);n=o?o[i]:null}return"auto"===n?null:n},getViewportOffset:function(t){var i,n=0,s=0,a=t,r=e.body,h=e.documentElement;do{if(n+=a.offsetTop||0,s+=a.offsetLeft||0,n+=parseInt(o.DomUtil.getStyle(a,"borderTopWidth"),10)||0,s+=parseInt(o.DomUtil.getStyle(a,"borderLeftWidth"),10)||0,i=o.DomUtil.getStyle(a,"position"),a.offsetParent===r&&"absolute"===i)break;if("fixed"===i){n+=r.scrollTop||h.scrollTop||0,s+=r.scrollLeft||h.scrollLeft||0;break}if("relative"===i&&!a.offsetLeft){var l=o.DomUtil.getStyle(a,"width"),u=o.DomUtil.getStyle(a,"max-width"),c=a.getBoundingClientRect();("none"!==l||"none"!==u)&&(s+=c.left+a.clientLeft),n+=c.top+(r.scrollTop||h.scrollTop||0);break}a=a.offsetParent}while(a);a=t;do{if(a===r)break;n-=a.scrollTop||0,s-=a.scrollLeft||0,a=a.parentNode}while(a);return new o.Point(s,n)},documentIsLtr:function(){return o.DomUtil._docIsLtrCached||(o.DomUtil._docIsLtrCached=!0,o.DomUtil._docIsLtr="ltr"===o.DomUtil.getStyle(e.body,"direction")),o.DomUtil._docIsLtr},create:function(t,i,n){var o=e.createElement(t);return o.className=i,n&&n.appendChild(o),o},hasClass:function(t,e){if(t.classList!==i)return t.classList.contains(e);var n=o.DomUtil._getClass(t);return n.length>0&&new RegExp("(^|\\s)"+e+"(\\s|$)").test(n)},addClass:function(t,e){if(t.classList!==i)for(var n=o.Util.splitWords(e),s=0,a=n.length;a>s;s++)t.classList.add(n[s]);else if(!o.DomUtil.hasClass(t,e)){var r=o.DomUtil._getClass(t);o.DomUtil._setClass(t,(r?r+" ":"")+e)}},removeClass:function(t,e){t.classList!==i?t.classList.remove(e):o.DomUtil._setClass(t,o.Util.trim((" "+o.DomUtil._getClass(t)+" ").replace(" "+e+" "," ")))},_setClass:function(t,e){t.className.baseVal===i?t.className=e:t.className.baseVal=e},_getClass:function(t){return t.className.baseVal===i?t.className:t.className.baseVal},setOpacity:function(t,e){if("opacity"in t.style)t.style.opacity=e;else if("filter"in t.style){var i=!1,n="DXImageTransform.Microsoft.Alpha";try{i=t.filters.item(n)}catch(o){if(1===e)return}e=Math.round(100*e),i?(i.Enabled=100!==e,i.Opacity=e):t.style.filter+=" progid:"+n+"(opacity="+e+")"}},testProp:function(t){for(var i=e.documentElement.style,n=0;n<t.length;n++)if(t[n]in i)return t[n];return!1},getTranslateString:function(t){var e=o.Browser.webkit3d,i="translate"+(e?"3d":"")+"(",n=(e?",0":"")+")";return i+t.x+"px,"+t.y+"px"+n},getScaleString:function(t,e){var i=o.DomUtil.getTranslateString(e.add(e.multiplyBy(-1*t))),n=" scale("+t+") ";return i+n},setPosition:function(t,e,i){t._leaflet_pos=e,!i&&o.Browser.any3d?t.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(e):(t.style.left=e.x+"px",t.style.top=e.y+"px")},getPosition:function(t){return t._leaflet_pos}},o.DomUtil.TRANSFORM=o.DomUtil.testProp(["transform","WebkitTransform","OTransform","MozTransform","msTransform"]),o.DomUtil.TRANSITION=o.DomUtil.testProp(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),o.DomUtil.TRANSITION_END="webkitTransition"===o.DomUtil.TRANSITION||"OTransition"===o.DomUtil.TRANSITION?o.DomUtil.TRANSITION+"End":"transitionend",function(){if("onselectstart"in e)o.extend(o.DomUtil,{disableTextSelection:function(){o.DomEvent.on(t,"selectstart",o.DomEvent.preventDefault)},enableTextSelection:function(){o.DomEvent.off(t,"selectstart",o.DomEvent.preventDefault)}});else{var i=o.DomUtil.testProp(["userSelect","WebkitUserSelect","OUserSelect","MozUserSelect","msUserSelect"]);o.extend(o.DomUtil,{disableTextSelection:function(){if(i){var t=e.documentElement.style;this._userSelect=t[i],t[i]="none"}},enableTextSelection:function(){i&&(e.documentElement.style[i]=this._userSelect,delete this._userSelect)}})}o.extend(o.DomUtil,{disableImageDrag:function(){o.DomEvent.on(t,"dragstart",o.DomEvent.preventDefault)},enableImageDrag:function(){o.DomEvent.off(t,"dragstart",o.DomEvent.preventDefault)}})}(),o.LatLng=function(t,e,n){if(t=parseFloat(t),e=parseFloat(e),isNaN(t)||isNaN(e))throw new Error("Invalid LatLng object: ("+t+", "+e+")");this.lat=t,this.lng=e,n!==i&&(this.alt=parseFloat(n))},o.extend(o.LatLng,{DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,MAX_MARGIN:1e-9}),o.LatLng.prototype={equals:function(t){if(!t)return!1;t=o.latLng(t);var e=Math.max(Math.abs(this.lat-t.lat),Math.abs(this.lng-t.lng));return e<=o.LatLng.MAX_MARGIN},toString:function(t){return"LatLng("+o.Util.formatNum(this.lat,t)+", "+o.Util.formatNum(this.lng,t)+")"},distanceTo:function(t){t=o.latLng(t);var e=6378137,i=o.LatLng.DEG_TO_RAD,n=(t.lat-this.lat)*i,s=(t.lng-this.lng)*i,a=this.lat*i,r=t.lat*i,h=Math.sin(n/2),l=Math.sin(s/2),u=h*h+l*l*Math.cos(a)*Math.cos(r);return 2*e*Math.atan2(Math.sqrt(u),Math.sqrt(1-u))},wrap:function(t,e){var i=this.lng;return t=t||-180,e=e||180,i=(i+e)%(e-t)+(t>i||i===e?e:t),new o.LatLng(this.lat,i)}},o.latLng=function(t,e){return t instanceof o.LatLng?t:o.Util.isArray(t)?"number"==typeof t[0]||"string"==typeof t[0]?new o.LatLng(t[0],t[1],t[2]):null:t===i||null===t?t:"object"==typeof t&&"lat"in t?new o.LatLng(t.lat,"lng"in t?t.lng:t.lon):e===i?null:new o.LatLng(t,e)},o.LatLngBounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},o.LatLngBounds.prototype={extend:function(t){if(!t)return this;var e=o.latLng(t);return t=null!==e?e:o.latLngBounds(t),t instanceof o.LatLng?this._southWest||this._northEast?(this._southWest.lat=Math.min(t.lat,this._southWest.lat),this._southWest.lng=Math.min(t.lng,this._southWest.lng),this._northEast.lat=Math.max(t.lat,this._northEast.lat),this._northEast.lng=Math.max(t.lng,this._northEast.lng)):(this._southWest=new o.LatLng(t.lat,t.lng),this._northEast=new o.LatLng(t.lat,t.lng)):t instanceof o.LatLngBounds&&(this.extend(t._southWest),this.extend(t._northEast)),this},pad:function(t){var e=this._southWest,i=this._northEast,n=Math.abs(e.lat-i.lat)*t,s=Math.abs(e.lng-i.lng)*t;return new o.LatLngBounds(new o.LatLng(e.lat-n,e.lng-s),new o.LatLng(i.lat+n,i.lng+s))},getCenter:function(){return new o.LatLng((this._southWest.lat+this._northEast.lat)/2,(this._southWest.lng+this._northEast.lng)/2)},getSouthWest:function(){return this._southWest},getNorthEast:function(){return this._northEast},getNorthWest:function(){return new o.LatLng(this.getNorth(),this.getWest())},getSouthEast:function(){return new o.LatLng(this.getSouth(),this.getEast())},getWest:function(){return this._southWest.lng},getSouth:function(){return this._southWest.lat},getEast:function(){return this._northEast.lng},getNorth:function(){return this._northEast.lat},contains:function(t){t="number"==typeof t[0]||t instanceof o.LatLng?o.latLng(t):o.latLngBounds(t);var e,i,n=this._southWest,s=this._northEast;return t instanceof o.LatLngBounds?(e=t.getSouthWest(),i=t.getNorthEast()):e=i=t,e.lat>=n.lat&&i.lat<=s.lat&&e.lng>=n.lng&&i.lng<=s.lng},intersects:function(t){t=o.latLngBounds(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),s=t.getNorthEast(),a=s.lat>=e.lat&&n.lat<=i.lat,r=s.lng>=e.lng&&n.lng<=i.lng;return a&&r},toBBoxString:function(){return[this.getWest(),this.getSouth(),this.getEast(),this.getNorth()].join(",")},equals:function(t){return t?(t=o.latLngBounds(t),this._southWest.equals(t.getSouthWest())&&this._northEast.equals(t.getNorthEast())):!1},isValid:function(){return!(!this._southWest||!this._northEast)}},o.latLngBounds=function(t,e){return!t||t instanceof o.LatLngBounds?t:new o.LatLngBounds(t,e)},o.Projection={},o.Projection.SphericalMercator={MAX_LATITUDE:85.0511287798,project:function(t){var e=o.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),s=t.lng*e,a=n*e;return a=Math.log(Math.tan(Math.PI/4+a/2)),new o.Point(s,a)},unproject:function(t){var e=o.LatLng.RAD_TO_DEG,i=t.x*e,n=(2*Math.atan(Math.exp(t.y))-Math.PI/2)*e;return new o.LatLng(n,i)}},o.Projection.LonLat={project:function(t){return new o.Point(t.lng,t.lat)},unproject:function(t){return new o.LatLng(t.y,t.x)}},o.CRS={latLngToPoint:function(t,e){var i=this.projection.project(t),n=this.scale(e);return this.transformation._transform(i,n)},pointToLatLng:function(t,e){var i=this.scale(e),n=this.transformation.untransform(t,i);return this.projection.unproject(n)},project:function(t){return this.projection.project(t)},scale:function(t){return 256*Math.pow(2,t)},getSize:function(t){var e=this.scale(t);return o.point(e,e)}},o.CRS.Simple=o.extend({},o.CRS,{projection:o.Projection.LonLat,transformation:new o.Transformation(1,0,-1,0),scale:function(t){return Math.pow(2,t)}}),o.CRS.EPSG3857=o.extend({},o.CRS,{code:"EPSG:3857",projection:o.Projection.SphericalMercator,transformation:new o.Transformation(.5/Math.PI,.5,-.5/Math.PI,.5),project:function(t){var e=this.projection.project(t),i=6378137;return e.multiplyBy(i)}}),o.CRS.EPSG900913=o.extend({},o.CRS.EPSG3857,{code:"EPSG:900913"}),o.CRS.EPSG4326=o.extend({},o.CRS,{code:"EPSG:4326",projection:o.Projection.LonLat,transformation:new o.Transformation(1/360,.5,-1/360,.5)}),o.Map=o.Class.extend({includes:o.Mixin.Events,options:{crs:o.CRS.EPSG3857,fadeAnimation:o.DomUtil.TRANSITION&&!o.Browser.android23,trackResize:!0,markerZoomAnimation:o.DomUtil.TRANSITION&&o.Browser.any3d},initialize:function(t,e){e=o.setOptions(this,e),this._initContainer(t),this._initLayout(),this._onResize=o.bind(this._onResize,this),this._initEvents(),e.maxBounds&&this.setMaxBounds(e.maxBounds),e.center&&e.zoom!==i&&this.setView(o.latLng(e.center),e.zoom,{reset:!0}),this._handlers=[],this._layers={},this._zoomBoundLayers={},this._tileLayersNum=0,this.callInitHooks(),this._addLayers(e.layers)},setView:function(t,e){return e=e===i?this.getZoom():e,this._resetView(o.latLng(t),this._limitZoom(e)),this},setZoom:function(t,e){return this._loaded?this.setView(this.getCenter(),t,{zoom:e}):(this._zoom=this._limitZoom(t),this)},zoomIn:function(t,e){return this.setZoom(this._zoom+(t||1),e)},zoomOut:function(t,e){return this.setZoom(this._zoom-(t||1),e)},setZoomAround:function(t,e,i){var n=this.getZoomScale(e),s=this.getSize().divideBy(2),a=t instanceof o.Point?t:this.latLngToContainerPoint(t),r=a.subtract(s).multiplyBy(1-1/n),h=this.containerPointToLatLng(s.add(r));return this.setView(h,e,{zoom:i})},fitBounds:function(t,e){e=e||{},t=t.getBounds?t.getBounds():o.latLngBounds(t);var i=o.point(e.paddingTopLeft||e.padding||[0,0]),n=o.point(e.paddingBottomRight||e.padding||[0,0]),s=this.getBoundsZoom(t,!1,i.add(n));s=e.maxZoom?Math.min(e.maxZoom,s):s;var a=n.subtract(i).divideBy(2),r=this.project(t.getSouthWest(),s),h=this.project(t.getNorthEast(),s),l=this.unproject(r.add(h).divideBy(2).add(a),s);return this.setView(l,s,e)},fitWorld:function(t){return this.fitBounds([[-90,-180],[90,180]],t)},panTo:function(t,e){return this.setView(t,this._zoom,{pan:e})},panBy:function(t){return this.fire("movestart"),this._rawPanBy(o.point(t)),this.fire("move"),this.fire("moveend")},setMaxBounds:function(t){return t=o.latLngBounds(t),this.options.maxBounds=t,t?(this._loaded&&this._panInsideMaxBounds(),this.on("moveend",this._panInsideMaxBounds,this)):this.off("moveend",this._panInsideMaxBounds,this)},panInsideBounds:function(t,e){var i=this.getCenter(),n=this._limitCenter(i,this._zoom,t);return i.equals(n)?this:this.panTo(n,e)},addLayer:function(t){var e=o.stamp(t);return this._layers[e]?this:(this._layers[e]=t,!t.options||isNaN(t.options.maxZoom)&&isNaN(t.options.minZoom)||(this._zoomBoundLayers[e]=t,this._updateZoomLevels()),this.options.zoomAnimation&&o.TileLayer&&t instanceof o.TileLayer&&(this._tileLayersNum++,this._tileLayersToLoad++,t.on("load",this._onTileLayerLoad,this)),this._loaded&&this._layerAdd(t),this)},removeLayer:function(t){var e=o.stamp(t);return this._layers[e]?(this._loaded&&t.onRemove(this),delete this._layers[e],this._loaded&&this.fire("layerremove",{layer:t}),this._zoomBoundLayers[e]&&(delete this._zoomBoundLayers[e],this._updateZoomLevels()),this.options.zoomAnimation&&o.TileLayer&&t instanceof o.TileLayer&&(this._tileLayersNum--,this._tileLayersToLoad--,t.off("load",this._onTileLayerLoad,this)),this):this},hasLayer:function(t){return t?o.stamp(t)in this._layers:!1},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},invalidateSize:function(t){if(!this._loaded)return this;t=o.extend({animate:!1,pan:!0},t===!0?{animate:!0}:t);var e=this.getSize();this._sizeChanged=!0,this._initialCenter=null;var i=this.getSize(),n=e.divideBy(2).round(),s=i.divideBy(2).round(),a=n.subtract(s);return a.x||a.y?(t.animate&&t.pan?this.panBy(a):(t.pan&&this._rawPanBy(a),this.fire("move"),t.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(o.bind(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:e,newSize:i})):this},addHandler:function(t,e){if(!e)return this;var i=this[t]=new e(this);return this._handlers.push(i),this.options[t]&&i.enable(),this},remove:function(){this._loaded&&this.fire("unload"),this._initEvents("off");try{delete this._container._leaflet}catch(t){this._container._leaflet=i}return this._clearPanes(),this._clearControlPos&&this._clearControlPos(),this._clearHandlers(),this},getCenter:function(){return this._checkIfLoaded(),this._initialCenter&&!this._moved()?this._initialCenter:this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var t=this.getPixelBounds(),e=this.unproject(t.getBottomLeft()),i=this.unproject(t.getTopRight());return new o.LatLngBounds(e,i)},getMinZoom:function(){return this.options.minZoom===i?this._layersMinZoom===i?0:this._layersMinZoom:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===i?this._layersMaxZoom===i?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(t,e,i){t=o.latLngBounds(t);var n,s=this.getMinZoom()-(e?1:0),a=this.getMaxZoom(),r=this.getSize(),h=t.getNorthWest(),l=t.getSouthEast(),u=!0;i=o.point(i||[0,0]);do s++,n=this.project(l,s).subtract(this.project(h,s)).add(i),u=e?n.x<r.x||n.y<r.y:r.contains(n);while(u&&a>=s);return u&&e?null:e?s:s-1},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new o.Point(this._container.clientWidth,this._container.clientHeight),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(){var t=this._getTopLeftPoint();return new o.Bounds(t,t.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._initialTopLeftPoint},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(t){var e=this.options.crs;return e.scale(t)/e.scale(this._zoom)},getScaleZoom:function(t){return this._zoom+Math.log(t)/Math.LN2},project:function(t,e){return e=e===i?this._zoom:e,this.options.crs.latLngToPoint(o.latLng(t),e)},unproject:function(t,e){return e=e===i?this._zoom:e,this.options.crs.pointToLatLng(o.point(t),e)},layerPointToLatLng:function(t){var e=o.point(t).add(this.getPixelOrigin());return this.unproject(e)},latLngToLayerPoint:function(t){var e=this.project(o.latLng(t))._round();return e._subtract(this.getPixelOrigin())},containerPointToLayerPoint:function(t){return o.point(t).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(t){return o.point(t).add(this._getMapPanePos())},containerPointToLatLng:function(t){var e=this.containerPointToLayerPoint(o.point(t));return this.layerPointToLatLng(e)},latLngToContainerPoint:function(t){return this.layerPointToContainerPoint(this.latLngToLayerPoint(o.latLng(t)))},mouseEventToContainerPoint:function(t){return o.DomEvent.getMousePosition(t,this._container)},mouseEventToLayerPoint:function(t){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))},mouseEventToLatLng:function(t){return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))},_initContainer:function(t){var e=this._container=o.DomUtil.get(t);if(!e)throw new Error("Map container not found.");if(e._leaflet)throw new Error("Map container is already initialized.");e._leaflet=!0},_initLayout:function(){var t=this._container;o.DomUtil.addClass(t,"leaflet-container"+(o.Browser.touch?" leaflet-touch":"")+(o.Browser.retina?" leaflet-retina":"")+(o.Browser.ielt9?" leaflet-oldie":"")+(this.options.fadeAnimation?" leaflet-fade-anim":""));var e=o.DomUtil.getStyle(t,"position");"absolute"!==e&&"relative"!==e&&"fixed"!==e&&(t.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var t=this._panes={};this._mapPane=t.mapPane=this._createPane("leaflet-map-pane",this._container),this._tilePane=t.tilePane=this._createPane("leaflet-tile-pane",this._mapPane),t.objectsPane=this._createPane("leaflet-objects-pane",this._mapPane),t.shadowPane=this._createPane("leaflet-shadow-pane"),t.overlayPane=this._createPane("leaflet-overlay-pane"),t.markerPane=this._createPane("leaflet-marker-pane"),t.popupPane=this._createPane("leaflet-popup-pane");var e=" leaflet-zoom-hide";this.options.markerZoomAnimation||(o.DomUtil.addClass(t.markerPane,e),o.DomUtil.addClass(t.shadowPane,e),o.DomUtil.addClass(t.popupPane,e))},_createPane:function(t,e){return o.DomUtil.create("div",t,e||this._panes.objectsPane)},_clearPanes:function(){this._container.removeChild(this._mapPane)},_addLayers:function(t){t=t?o.Util.isArray(t)?t:[t]:[];for(var e=0,i=t.length;i>e;e++)this.addLayer(t[e])},_resetView:function(t,e,i,n){var s=this._zoom!==e;n||(this.fire("movestart"),s&&this.fire("zoomstart")),this._zoom=e,this._initialCenter=t,this._initialTopLeftPoint=this._getNewTopLeftPoint(t),i?this._initialTopLeftPoint._add(this._getMapPanePos()):o.DomUtil.setPosition(this._mapPane,new o.Point(0,0)),this._tileLayersToLoad=this._tileLayersNum;var a=!this._loaded;this._loaded=!0,this.fire("viewreset",{hard:!i}),a&&(this.fire("load"),this.eachLayer(this._layerAdd,this)),this.fire("move"),(s||n)&&this.fire("zoomend"),this.fire("moveend",{hard:!i})},_rawPanBy:function(t){o.DomUtil.setPosition(this._mapPane,this._getMapPanePos().subtract(t))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_updateZoomLevels:function(){var t,e=1/0,n=-(1/0),o=this._getZoomSpan();for(t in this._zoomBoundLayers){var s=this._zoomBoundLayers[t];isNaN(s.options.minZoom)||(e=Math.min(e,s.options.minZoom)),isNaN(s.options.maxZoom)||(n=Math.max(n,s.options.maxZoom))}t===i?this._layersMaxZoom=this._layersMinZoom=i:(this._layersMaxZoom=n,this._layersMinZoom=e),o!==this._getZoomSpan()&&this.fire("zoomlevelschange")},_panInsideMaxBounds:function(){this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(e){if(o.DomEvent){e=e||"on",o.DomEvent[e](this._container,"click",this._onMouseClick,this);var i,n,s=["dblclick","mousedown","mouseup","mouseenter","mouseleave","mousemove","contextmenu"];for(i=0,n=s.length;n>i;i++)o.DomEvent[e](this._container,s[i],this._fireMouseEvent,this);this.options.trackResize&&o.DomEvent[e](t,"resize",this._onResize,this)}},_onResize:function(){o.Util.cancelAnimFrame(this._resizeRequest),this._resizeRequest=o.Util.requestAnimFrame(function(){this.invalidateSize({debounceMoveend:!0})},this,!1,this._container)},_onMouseClick:function(t){!this._loaded||!t._simulated&&(this.dragging&&this.dragging.moved()||this.boxZoom&&this.boxZoom.moved())||o.DomEvent._skipped(t)||(this.fire("preclick"),this._fireMouseEvent(t))},_fireMouseEvent:function(t){if(this._loaded&&!o.DomEvent._skipped(t)){var e=t.type;if(e="mouseenter"===e?"mouseover":"mouseleave"===e?"mouseout":e,this.hasEventListeners(e)){"contextmenu"===e&&o.DomEvent.preventDefault(t);var i=this.mouseEventToContainerPoint(t),n=this.containerPointToLayerPoint(i),s=this.layerPointToLatLng(n);this.fire(e,{latlng:s,layerPoint:n,containerPoint:i,originalEvent:t})}}},_onTileLayerLoad:function(){this._tileLayersToLoad--,this._tileLayersNum&&!this._tileLayersToLoad&&this.fire("tilelayersload")},_clearHandlers:function(){for(var t=0,e=this._handlers.length;e>t;t++)this._handlers[t].disable()},whenReady:function(t,e){return this._loaded?t.call(e||this,this):this.on("load",t,e),this},_layerAdd:function(t){t.onAdd(this),this.fire("layeradd",{layer:t})},_getMapPanePos:function(){return o.DomUtil.getPosition(this._mapPane)},_moved:function(){var t=this._getMapPanePos();return t&&!t.equals([0,0])},_getTopLeftPoint:function(){return this.getPixelOrigin().subtract(this._getMapPanePos())},_getNewTopLeftPoint:function(t,e){var i=this.getSize()._divideBy(2);return this.project(t,e)._subtract(i)._round()},_latLngToNewLayerPoint:function(t,e,i){var n=this._getNewTopLeftPoint(i,e).add(this._getMapPanePos());return this.project(t,e)._subtract(n)},_getCenterLayerPoint:function(){return this.containerPointToLayerPoint(this.getSize()._divideBy(2))},_getCenterOffset:function(t){return this.latLngToLayerPoint(t).subtract(this._getCenterLayerPoint())},_limitCenter:function(t,e,i){if(!i)return t;var n=this.project(t,e),s=this.getSize().divideBy(2),a=new o.Bounds(n.subtract(s),n.add(s)),r=this._getBoundsOffset(a,i,e);return this.unproject(n.add(r),e)},_limitOffset:function(t,e){if(!e)return t;var i=this.getPixelBounds(),n=new o.Bounds(i.min.add(t),i.max.add(t));return t.add(this._getBoundsOffset(n,e))},_getBoundsOffset:function(t,e,i){var n=this.project(e.getNorthWest(),i).subtract(t.min),s=this.project(e.getSouthEast(),i).subtract(t.max),a=this._rebound(n.x,-s.x),r=this._rebound(n.y,-s.y);return new o.Point(a,r)},_rebound:function(t,e){return t+e>0?Math.round(t-e)/2:Math.max(0,Math.ceil(t))-Math.max(0,Math.floor(e))},_limitZoom:function(t){var e=this.getMinZoom(),i=this.getMaxZoom();return Math.max(e,Math.min(i,t))}}),o.map=function(t,e){return new o.Map(t,e)},o.Projection.Mercator={MAX_LATITUDE:85.0840591556,R_MINOR:6356752.314245179,R_MAJOR:6378137,project:function(t){var e=o.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),s=this.R_MAJOR,a=this.R_MINOR,r=t.lng*e*s,h=n*e,l=a/s,u=Math.sqrt(1-l*l),c=u*Math.sin(h);c=Math.pow((1-c)/(1+c),.5*u);var d=Math.tan(.5*(.5*Math.PI-h))/c;return h=-s*Math.log(d),new o.Point(r,h)},unproject:function(t){for(var e,i=o.LatLng.RAD_TO_DEG,n=this.R_MAJOR,s=this.R_MINOR,a=t.x*i/n,r=s/n,h=Math.sqrt(1-r*r),l=Math.exp(-t.y/n),u=Math.PI/2-2*Math.atan(l),c=15,d=1e-7,p=c,_=.1;Math.abs(_)>d&&--p>0;)e=h*Math.sin(u),_=Math.PI/2-2*Math.atan(l*Math.pow((1-e)/(1+e),.5*h))-u,u+=_;return new o.LatLng(u*i,a)}},o.CRS.EPSG3395=o.extend({},o.CRS,{code:"EPSG:3395",projection:o.Projection.Mercator,
transformation:function(){var t=o.Projection.Mercator,e=t.R_MAJOR,i=.5/(Math.PI*e);return new o.Transformation(i,.5,-i,.5)}()}),o.TileLayer=o.Class.extend({includes:o.Mixin.Events,options:{minZoom:0,maxZoom:18,tileSize:256,subdomains:"abc",errorTileUrl:"",attribution:"",zoomOffset:0,opacity:1,unloadInvisibleTiles:o.Browser.mobile,updateWhenIdle:o.Browser.mobile},initialize:function(t,e){e=o.setOptions(this,e),e.detectRetina&&o.Browser.retina&&e.maxZoom>0&&(e.tileSize=Math.floor(e.tileSize/2),e.zoomOffset++,e.minZoom>0&&e.minZoom--,this.options.maxZoom--),e.bounds&&(e.bounds=o.latLngBounds(e.bounds)),this._url=t;var i=this.options.subdomains;"string"==typeof i&&(this.options.subdomains=i.split(""))},onAdd:function(t){this._map=t,this._animated=t._zoomAnimated,this._initContainer(),t.on({viewreset:this._reset,moveend:this._update},this),this._animated&&t.on({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||(this._limitedUpdate=o.Util.limitExecByInterval(this._update,150,this),t.on("move",this._limitedUpdate,this)),this._reset(),this._update()},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this._container.parentNode.removeChild(this._container),t.off({viewreset:this._reset,moveend:this._update},this),this._animated&&t.off({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||t.off("move",this._limitedUpdate,this),this._container=null,this._map=null},bringToFront:function(){var t=this._map._panes.tilePane;return this._container&&(t.appendChild(this._container),this._setAutoZIndex(t,Math.max)),this},bringToBack:function(){var t=this._map._panes.tilePane;return this._container&&(t.insertBefore(this._container,t.firstChild),this._setAutoZIndex(t,Math.min)),this},getAttribution:function(){return this.options.attribution},getContainer:function(){return this._container},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},setZIndex:function(t){return this.options.zIndex=t,this._updateZIndex(),this},setUrl:function(t,e){return this._url=t,e||this.redraw(),this},redraw:function(){return this._map&&(this._reset({hard:!0}),this._update()),this},_updateZIndex:function(){this._container&&this.options.zIndex!==i&&(this._container.style.zIndex=this.options.zIndex)},_setAutoZIndex:function(t,e){var i,n,o,s=t.children,a=-e(1/0,-(1/0));for(n=0,o=s.length;o>n;n++)s[n]!==this._container&&(i=parseInt(s[n].style.zIndex,10),isNaN(i)||(a=e(a,i)));this.options.zIndex=this._container.style.zIndex=(isFinite(a)?a:0)+e(1,-1)},_updateOpacity:function(){var t,e=this._tiles;if(o.Browser.ielt9)for(t in e)o.DomUtil.setOpacity(e[t],this.options.opacity);else o.DomUtil.setOpacity(this._container,this.options.opacity)},_initContainer:function(){var t=this._map._panes.tilePane;if(!this._container){if(this._container=o.DomUtil.create("div","leaflet-layer"),this._updateZIndex(),this._animated){var e="leaflet-tile-container";this._bgBuffer=o.DomUtil.create("div",e,this._container),this._tileContainer=o.DomUtil.create("div",e,this._container)}else this._tileContainer=this._container;t.appendChild(this._container),this.options.opacity<1&&this._updateOpacity()}},_reset:function(t){for(var e in this._tiles)this.fire("tileunload",{tile:this._tiles[e]});this._tiles={},this._tilesToLoad=0,this.options.reuseTiles&&(this._unusedTiles=[]),this._tileContainer.innerHTML="",this._animated&&t&&t.hard&&this._clearBgBuffer(),this._initContainer()},_getTileSize:function(){var t=this._map,e=t.getZoom()+this.options.zoomOffset,i=this.options.maxNativeZoom,n=this.options.tileSize;return i&&e>i&&(n=Math.round(t.getZoomScale(e)/t.getZoomScale(i)*n)),n},_update:function(){if(this._map){var t=this._map,e=t.getPixelBounds(),i=t.getZoom(),n=this._getTileSize();if(!(i>this.options.maxZoom||i<this.options.minZoom)){var s=o.bounds(e.min.divideBy(n)._floor(),e.max.divideBy(n)._floor());this._addTilesFromCenterOut(s),(this.options.unloadInvisibleTiles||this.options.reuseTiles)&&this._removeOtherTiles(s)}}},_addTilesFromCenterOut:function(t){var i,n,s,a=[],r=t.getCenter();for(i=t.min.y;i<=t.max.y;i++)for(n=t.min.x;n<=t.max.x;n++)s=new o.Point(n,i),this._tileShouldBeLoaded(s)&&a.push(s);var h=a.length;if(0!==h){a.sort(function(t,e){return t.distanceTo(r)-e.distanceTo(r)});var l=e.createDocumentFragment();for(this._tilesToLoad||this.fire("loading"),this._tilesToLoad+=h,n=0;h>n;n++)this._addTile(a[n],l);this._tileContainer.appendChild(l)}},_tileShouldBeLoaded:function(t){if(t.x+":"+t.y in this._tiles)return!1;var e=this.options;if(!e.continuousWorld){var i=this._getWrapTileNum();if(e.noWrap&&(t.x<0||t.x>=i.x)||t.y<0||t.y>=i.y)return!1}if(e.bounds){var n=this._getTileSize(),o=t.multiplyBy(n),s=o.add([n,n]),a=this._map.unproject(o),r=this._map.unproject(s);if(e.continuousWorld||e.noWrap||(a=a.wrap(),r=r.wrap()),!e.bounds.intersects([a,r]))return!1}return!0},_removeOtherTiles:function(t){var e,i,n,o;for(o in this._tiles)e=o.split(":"),i=parseInt(e[0],10),n=parseInt(e[1],10),(i<t.min.x||i>t.max.x||n<t.min.y||n>t.max.y)&&this._removeTile(o)},_removeTile:function(t){var e=this._tiles[t];this.fire("tileunload",{tile:e,url:e.src}),this.options.reuseTiles?(o.DomUtil.removeClass(e,"leaflet-tile-loaded"),this._unusedTiles.push(e)):e.parentNode===this._tileContainer&&this._tileContainer.removeChild(e),o.Browser.android||(e.onload=null,e.src=o.Util.emptyImageUrl),delete this._tiles[t]},_addTile:function(t,e){var i=this._getTilePos(t),n=this._getTile();o.DomUtil.setPosition(n,i,o.Browser.chrome),this._tiles[t.x+":"+t.y]=n,this._loadTile(n,t),n.parentNode!==this._tileContainer&&e.appendChild(n)},_getZoomForUrl:function(){var t=this.options,e=this._map.getZoom();return t.zoomReverse&&(e=t.maxZoom-e),e+=t.zoomOffset,t.maxNativeZoom?Math.min(e,t.maxNativeZoom):e},_getTilePos:function(t){var e=this._map.getPixelOrigin(),i=this._getTileSize();return t.multiplyBy(i).subtract(e)},getTileUrl:function(t){return o.Util.template(this._url,o.extend({s:this._getSubdomain(t),z:t.z,x:t.x,y:t.y},this.options))},_getWrapTileNum:function(){var t=this._map.options.crs,e=t.getSize(this._map.getZoom());return e.divideBy(this._getTileSize())._floor()},_adjustTilePoint:function(t){var e=this._getWrapTileNum();this.options.continuousWorld||this.options.noWrap||(t.x=(t.x%e.x+e.x)%e.x),this.options.tms&&(t.y=e.y-t.y-1),t.z=this._getZoomForUrl()},_getSubdomain:function(t){var e=Math.abs(t.x+t.y)%this.options.subdomains.length;return this.options.subdomains[e]},_getTile:function(){if(this.options.reuseTiles&&this._unusedTiles.length>0){var t=this._unusedTiles.pop();return this._resetTile(t),t}return this._createTile()},_resetTile:function(){},_createTile:function(){var t=o.DomUtil.create("img","leaflet-tile");return t.style.width=t.style.height=this._getTileSize()+"px",t.galleryimg="no",t.onselectstart=t.onmousemove=o.Util.falseFn,o.Browser.ielt9&&this.options.opacity!==i&&o.DomUtil.setOpacity(t,this.options.opacity),o.Browser.mobileWebkit3d&&(t.style.WebkitBackfaceVisibility="hidden"),t},_loadTile:function(t,e){t._layer=this,t.onload=this._tileOnLoad,t.onerror=this._tileOnError,this._adjustTilePoint(e),t.src=this.getTileUrl(e),this.fire("tileloadstart",{tile:t,url:t.src})},_tileLoaded:function(){this._tilesToLoad--,this._animated&&o.DomUtil.addClass(this._tileContainer,"leaflet-zoom-animated"),this._tilesToLoad||(this.fire("load"),this._animated&&(clearTimeout(this._clearBgBufferTimer),this._clearBgBufferTimer=setTimeout(o.bind(this._clearBgBuffer,this),500)))},_tileOnLoad:function(){var t=this._layer;this.src!==o.Util.emptyImageUrl&&(o.DomUtil.addClass(this,"leaflet-tile-loaded"),t.fire("tileload",{tile:this,url:this.src})),t._tileLoaded()},_tileOnError:function(){var t=this._layer;t.fire("tileerror",{tile:this,url:this.src});var e=t.options.errorTileUrl;e&&(this.src=e),t._tileLoaded()}}),o.tileLayer=function(t,e){return new o.TileLayer(t,e)},o.TileLayer.WMS=o.TileLayer.extend({defaultWmsParams:{service:"WMS",request:"GetMap",version:"1.1.1",layers:"",styles:"",format:"image/jpeg",transparent:!1},initialize:function(t,e){this._url=t;var i=o.extend({},this.defaultWmsParams),n=e.tileSize||this.options.tileSize;e.detectRetina&&o.Browser.retina?i.width=i.height=2*n:i.width=i.height=n;for(var s in e)this.options.hasOwnProperty(s)||"crs"===s||(i[s]=e[s]);this.wmsParams=i,o.setOptions(this,e)},onAdd:function(t){this._crs=this.options.crs||t.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var e=this._wmsVersion>=1.3?"crs":"srs";this.wmsParams[e]=this._crs.code,o.TileLayer.prototype.onAdd.call(this,t)},getTileUrl:function(t){var e=this._map,i=this.options.tileSize,n=t.multiplyBy(i),s=n.add([i,i]),a=this._crs.project(e.unproject(n,t.z)),r=this._crs.project(e.unproject(s,t.z)),h=this._wmsVersion>=1.3&&this._crs===o.CRS.EPSG4326?[r.y,a.x,a.y,r.x].join(","):[a.x,r.y,r.x,a.y].join(","),l=o.Util.template(this._url,{s:this._getSubdomain(t)});return l+o.Util.getParamString(this.wmsParams,l,!0)+"&BBOX="+h},setParams:function(t,e){return o.extend(this.wmsParams,t),e||this.redraw(),this}}),o.tileLayer.wms=function(t,e){return new o.TileLayer.WMS(t,e)},o.TileLayer.Canvas=o.TileLayer.extend({options:{async:!1},initialize:function(t){o.setOptions(this,t)},redraw:function(){this._map&&(this._reset({hard:!0}),this._update());for(var t in this._tiles)this._redrawTile(this._tiles[t]);return this},_redrawTile:function(t){this.drawTile(t,t._tilePoint,this._map._zoom)},_createTile:function(){var t=o.DomUtil.create("canvas","leaflet-tile");return t.width=t.height=this.options.tileSize,t.onselectstart=t.onmousemove=o.Util.falseFn,t},_loadTile:function(t,e){t._layer=this,t._tilePoint=e,this._redrawTile(t),this.options.async||this.tileDrawn(t)},drawTile:function(){},tileDrawn:function(t){this._tileOnLoad.call(t)}}),o.tileLayer.canvas=function(t){return new o.TileLayer.Canvas(t)},o.ImageOverlay=o.Class.extend({includes:o.Mixin.Events,options:{opacity:1},initialize:function(t,e,i){this._url=t,this._bounds=o.latLngBounds(e),o.setOptions(this,i)},onAdd:function(t){this._map=t,this._image||this._initImage(),t._panes.overlayPane.appendChild(this._image),t.on("viewreset",this._reset,this),t.options.zoomAnimation&&o.Browser.any3d&&t.on("zoomanim",this._animateZoom,this),this._reset()},onRemove:function(t){t.getPanes().overlayPane.removeChild(this._image),t.off("viewreset",this._reset,this),t.options.zoomAnimation&&t.off("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},setOpacity:function(t){return this.options.opacity=t,this._updateOpacity(),this},bringToFront:function(){return this._image&&this._map._panes.overlayPane.appendChild(this._image),this},bringToBack:function(){var t=this._map._panes.overlayPane;return this._image&&t.insertBefore(this._image,t.firstChild),this},setUrl:function(t){this._url=t,this._image.src=this._url},getAttribution:function(){return this.options.attribution},_initImage:function(){this._image=o.DomUtil.create("img","leaflet-image-layer"),this._map.options.zoomAnimation&&o.Browser.any3d?o.DomUtil.addClass(this._image,"leaflet-zoom-animated"):o.DomUtil.addClass(this._image,"leaflet-zoom-hide"),this._updateOpacity(),o.extend(this._image,{galleryimg:"no",onselectstart:o.Util.falseFn,onmousemove:o.Util.falseFn,onload:o.bind(this._onImageLoad,this),src:this._url})},_animateZoom:function(t){var e=this._map,i=this._image,n=e.getZoomScale(t.zoom),s=this._bounds.getNorthWest(),a=this._bounds.getSouthEast(),r=e._latLngToNewLayerPoint(s,t.zoom,t.center),h=e._latLngToNewLayerPoint(a,t.zoom,t.center)._subtract(r),l=r._add(h._multiplyBy(.5*(1-1/n)));i.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(l)+" scale("+n+") "},_reset:function(){var t=this._image,e=this._map.latLngToLayerPoint(this._bounds.getNorthWest()),i=this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(e);o.DomUtil.setPosition(t,e),t.style.width=i.x+"px",t.style.height=i.y+"px"},_onImageLoad:function(){this.fire("load")},_updateOpacity:function(){o.DomUtil.setOpacity(this._image,this.options.opacity)}}),o.imageOverlay=function(t,e,i){return new o.ImageOverlay(t,e,i)},o.Icon=o.Class.extend({options:{className:""},initialize:function(t){o.setOptions(this,t)},createIcon:function(t){return this._createIcon("icon",t)},createShadow:function(t){return this._createIcon("shadow",t)},_createIcon:function(t,e){var i=this._getIconUrl(t);if(!i){if("icon"===t)throw new Error("iconUrl not set in Icon options (see the docs).");return null}var n;return n=e&&"IMG"===e.tagName?this._createImg(i,e):this._createImg(i),this._setIconStyles(n,t),n},_setIconStyles:function(t,e){var i,n=this.options,s=o.point(n[e+"Size"]);i="shadow"===e?o.point(n.shadowAnchor||n.iconAnchor):o.point(n.iconAnchor),!i&&s&&(i=s.divideBy(2,!0)),t.className="leaflet-marker-"+e+" "+n.className,i&&(t.style.marginLeft=-i.x+"px",t.style.marginTop=-i.y+"px"),s&&(t.style.width=s.x+"px",t.style.height=s.y+"px")},_createImg:function(t,i){return i=i||e.createElement("img"),i.src=t,i},_getIconUrl:function(t){return o.Browser.retina&&this.options[t+"RetinaUrl"]?this.options[t+"RetinaUrl"]:this.options[t+"Url"]}}),o.icon=function(t){return new o.Icon(t)},o.Icon.Default=o.Icon.extend({options:{iconSize:[25,41],iconAnchor:[12,41],popupAnchor:[1,-34],shadowSize:[41,41]},_getIconUrl:function(t){var e=t+"Url";if(this.options[e])return this.options[e];o.Browser.retina&&"icon"===t&&(t+="-2x");var i=o.Icon.Default.imagePath;if(!i)throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");return i+"/marker-"+t+".png"}}),o.Icon.Default.imagePath=function(){var t,i,n,o,s,a=e.getElementsByTagName("script"),r=/[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;for(t=0,i=a.length;i>t;t++)if(n=a[t].src,o=n.match(r))return s=n.split(r)[0],(s?s+"/":"")+"images"}(),o.Marker=o.Class.extend({includes:o.Mixin.Events,options:{icon:new o.Icon.Default,title:"",alt:"",clickable:!0,draggable:!1,keyboard:!0,zIndexOffset:0,opacity:1,riseOnHover:!1,riseOffset:250},initialize:function(t,e){o.setOptions(this,e),this._latlng=o.latLng(t)},onAdd:function(t){this._map=t,t.on("viewreset",this.update,this),this._initIcon(),this.update(),this.fire("add"),t.options.zoomAnimation&&t.options.markerZoomAnimation&&t.on("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this.dragging&&this.dragging.disable(),this._removeIcon(),this._removeShadow(),this.fire("remove"),t.off({viewreset:this.update,zoomanim:this._animateZoom},this),this._map=null},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=o.latLng(t),this.update(),this.fire("move",{latlng:this._latlng})},setZIndexOffset:function(t){return this.options.zIndexOffset=t,this.update(),this},setIcon:function(t){return this.options.icon=t,this._map&&(this._initIcon(),this.update()),this._popup&&this.bindPopup(this._popup),this},update:function(){return this._icon&&this._setPos(this._map.latLngToLayerPoint(this._latlng).round()),this},_initIcon:function(){var t=this.options,e=this._map,i=e.options.zoomAnimation&&e.options.markerZoomAnimation,n=i?"leaflet-zoom-animated":"leaflet-zoom-hide",s=t.icon.createIcon(this._icon),a=!1;s!==this._icon&&(this._icon&&this._removeIcon(),a=!0,t.title&&(s.title=t.title),t.alt&&(s.alt=t.alt)),o.DomUtil.addClass(s,n),t.keyboard&&(s.tabIndex="0"),this._icon=s,this._initInteraction(),t.riseOnHover&&o.DomEvent.on(s,"mouseover",this._bringToFront,this).on(s,"mouseout",this._resetZIndex,this);var r=t.icon.createShadow(this._shadow),h=!1;r!==this._shadow&&(this._removeShadow(),h=!0),r&&o.DomUtil.addClass(r,n),this._shadow=r,t.opacity<1&&this._updateOpacity();var l=this._map._panes;a&&l.markerPane.appendChild(this._icon),r&&h&&l.shadowPane.appendChild(this._shadow)},_removeIcon:function(){this.options.riseOnHover&&o.DomEvent.off(this._icon,"mouseover",this._bringToFront).off(this._icon,"mouseout",this._resetZIndex),this._map._panes.markerPane.removeChild(this._icon),this._icon=null},_removeShadow:function(){this._shadow&&this._map._panes.shadowPane.removeChild(this._shadow),this._shadow=null},_setPos:function(t){o.DomUtil.setPosition(this._icon,t),this._shadow&&o.DomUtil.setPosition(this._shadow,t),this._zIndex=t.y+this.options.zIndexOffset,this._resetZIndex()},_updateZIndex:function(t){this._icon.style.zIndex=this._zIndex+t},_animateZoom:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center).round();this._setPos(e)},_initInteraction:function(){if(this.options.clickable){var t=this._icon,e=["dblclick","mousedown","mouseover","mouseout","contextmenu"];o.DomUtil.addClass(t,"leaflet-clickable"),o.DomEvent.on(t,"click",this._onMouseClick,this),o.DomEvent.on(t,"keypress",this._onKeyPress,this);for(var i=0;i<e.length;i++)o.DomEvent.on(t,e[i],this._fireMouseEvent,this);o.Handler.MarkerDrag&&(this.dragging=new o.Handler.MarkerDrag(this),this.options.draggable&&this.dragging.enable())}},_onMouseClick:function(t){var e=this.dragging&&this.dragging.moved();(this.hasEventListeners(t.type)||e)&&o.DomEvent.stopPropagation(t),e||(this.dragging&&this.dragging._enabled||!this._map.dragging||!this._map.dragging.moved())&&this.fire(t.type,{originalEvent:t,latlng:this._latlng})},_onKeyPress:function(t){13===t.keyCode&&this.fire("click",{originalEvent:t,latlng:this._latlng})},_fireMouseEvent:function(t){this.fire(t.type,{originalEvent:t,latlng:this._latlng}),"contextmenu"===t.type&&this.hasEventListeners(t.type)&&o.DomEvent.preventDefault(t),"mousedown"!==t.type?o.DomEvent.stopPropagation(t):o.DomEvent.preventDefault(t)},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},_updateOpacity:function(){o.DomUtil.setOpacity(this._icon,this.options.opacity),this._shadow&&o.DomUtil.setOpacity(this._shadow,this.options.opacity)},_bringToFront:function(){this._updateZIndex(this.options.riseOffset)},_resetZIndex:function(){this._updateZIndex(0)}}),o.marker=function(t,e){return new o.Marker(t,e)},o.DivIcon=o.Icon.extend({options:{iconSize:[12,12],className:"leaflet-div-icon",html:!1},createIcon:function(t){var i=t&&"DIV"===t.tagName?t:e.createElement("div"),n=this.options;return n.html!==!1?i.innerHTML=n.html:i.innerHTML="",n.bgPos&&(i.style.backgroundPosition=-n.bgPos.x+"px "+-n.bgPos.y+"px"),this._setIconStyles(i,"icon"),i},createShadow:function(){return null}}),o.divIcon=function(t){return new o.DivIcon(t)},o.Map.mergeOptions({closePopupOnClick:!0}),o.Popup=o.Class.extend({includes:o.Mixin.Events,options:{minWidth:50,maxWidth:300,autoPan:!0,closeButton:!0,offset:[0,7],autoPanPadding:[5,5],keepInView:!1,className:"",zoomAnimation:!0},initialize:function(t,e){o.setOptions(this,t),this._source=e,this._animated=o.Browser.any3d&&this.options.zoomAnimation,this._isOpen=!1},onAdd:function(t){this._map=t,this._container||this._initLayout();var e=t.options.fadeAnimation;e&&o.DomUtil.setOpacity(this._container,0),t._panes.popupPane.appendChild(this._container),t.on(this._getEvents(),this),this.update(),e&&o.DomUtil.setOpacity(this._container,1),this.fire("open"),t.fire("popupopen",{popup:this}),this._source&&this._source.fire("popupopen",{popup:this})},addTo:function(t){return t.addLayer(this),this},openOn:function(t){return t.openPopup(this),this},onRemove:function(t){t._panes.popupPane.removeChild(this._container),o.Util.falseFn(this._container.offsetWidth),t.off(this._getEvents(),this),t.options.fadeAnimation&&o.DomUtil.setOpacity(this._container,0),this._map=null,this.fire("close"),t.fire("popupclose",{popup:this}),this._source&&this._source.fire("popupclose",{popup:this})},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=o.latLng(t),this._map&&(this._updatePosition(),this._adjustPan()),this},getContent:function(){return this._content},setContent:function(t){return this._content=t,this.update(),this},update:function(){this._map&&(this._container.style.visibility="hidden",this._updateContent(),this._updateLayout(),this._updatePosition(),this._container.style.visibility="",this._adjustPan())},_getEvents:function(){var t={viewreset:this._updatePosition};return this._animated&&(t.zoomanim=this._zoomAnimation),("closeOnClick"in this.options?this.options.closeOnClick:this._map.options.closePopupOnClick)&&(t.preclick=this._close),this.options.keepInView&&(t.moveend=this._adjustPan),t},_close:function(){this._map&&this._map.closePopup(this)},_initLayout:function(){var t,e="leaflet-popup",i=e+" "+this.options.className+" leaflet-zoom-"+(this._animated?"animated":"hide"),n=this._container=o.DomUtil.create("div",i);this.options.closeButton&&(t=this._closeButton=o.DomUtil.create("a",e+"-close-button",n),t.href="#close",t.innerHTML="&#215;",o.DomEvent.disableClickPropagation(t),o.DomEvent.on(t,"click",this._onCloseButtonClick,this));var s=this._wrapper=o.DomUtil.create("div",e+"-content-wrapper",n);o.DomEvent.disableClickPropagation(s),this._contentNode=o.DomUtil.create("div",e+"-content",s),o.DomEvent.disableScrollPropagation(this._contentNode),o.DomEvent.on(s,"contextmenu",o.DomEvent.stopPropagation),this._tipContainer=o.DomUtil.create("div",e+"-tip-container",n),this._tip=o.DomUtil.create("div",e+"-tip",this._tipContainer)},_updateContent:function(){if(this._content){if("string"==typeof this._content)this._contentNode.innerHTML=this._content;else{for(;this._contentNode.hasChildNodes();)this._contentNode.removeChild(this._contentNode.firstChild);this._contentNode.appendChild(this._content)}this.fire("contentupdate")}},_updateLayout:function(){var t=this._contentNode,e=t.style;e.width="",e.whiteSpace="nowrap";var i=t.offsetWidth;i=Math.min(i,this.options.maxWidth),i=Math.max(i,this.options.minWidth),e.width=i+1+"px",e.whiteSpace="",e.height="";var n=t.offsetHeight,s=this.options.maxHeight,a="leaflet-popup-scrolled";s&&n>s?(e.height=s+"px",o.DomUtil.addClass(t,a)):o.DomUtil.removeClass(t,a),this._containerWidth=this._container.offsetWidth},_updatePosition:function(){if(this._map){var t=this._map.latLngToLayerPoint(this._latlng),e=this._animated,i=o.point(this.options.offset);e&&o.DomUtil.setPosition(this._container,t),this._containerBottom=-i.y-(e?0:t.y),this._containerLeft=-Math.round(this._containerWidth/2)+i.x+(e?0:t.x),this._container.style.bottom=this._containerBottom+"px",this._container.style.left=this._containerLeft+"px"}},_zoomAnimation:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center);o.DomUtil.setPosition(this._container,e)},_adjustPan:function(){if(this.options.autoPan){var t=this._map,e=this._container.offsetHeight,i=this._containerWidth,n=new o.Point(this._containerLeft,-e-this._containerBottom);this._animated&&n._add(o.DomUtil.getPosition(this._container));var s=t.layerPointToContainerPoint(n),a=o.point(this.options.autoPanPadding),r=o.point(this.options.autoPanPaddingTopLeft||a),h=o.point(this.options.autoPanPaddingBottomRight||a),l=t.getSize(),u=0,c=0;s.x+i+h.x>l.x&&(u=s.x+i-l.x+h.x),s.x-u-r.x<0&&(u=s.x-r.x),s.y+e+h.y>l.y&&(c=s.y+e-l.y+h.y),s.y-c-r.y<0&&(c=s.y-r.y),(u||c)&&t.fire("autopanstart").panBy([u,c])}},_onCloseButtonClick:function(t){this._close(),o.DomEvent.stop(t)}}),o.popup=function(t,e){return new o.Popup(t,e)},o.Map.include({openPopup:function(t,e,i){if(this.closePopup(),!(t instanceof o.Popup)){var n=t;t=new o.Popup(i).setLatLng(e).setContent(n)}return t._isOpen=!0,this._popup=t,this.addLayer(t)},closePopup:function(t){return t&&t!==this._popup||(t=this._popup,this._popup=null),t&&(this.removeLayer(t),t._isOpen=!1),this}}),o.Marker.include({openPopup:function(){return this._popup&&this._map&&!this._map.hasLayer(this._popup)&&(this._popup.setLatLng(this._latlng),this._map.openPopup(this._popup)),this},closePopup:function(){return this._popup&&this._popup._close(),this},togglePopup:function(){return this._popup&&(this._popup._isOpen?this.closePopup():this.openPopup()),this},bindPopup:function(t,e){var i=o.point(this.options.icon.options.popupAnchor||[0,0]);return i=i.add(o.Popup.prototype.options.offset),e&&e.offset&&(i=i.add(e.offset)),e=o.extend({offset:i},e),this._popupHandlersAdded||(this.on("click",this.togglePopup,this).on("remove",this.closePopup,this).on("move",this._movePopup,this),this._popupHandlersAdded=!0),t instanceof o.Popup?(o.setOptions(t,e),this._popup=t,t._source=this):this._popup=new o.Popup(e,this).setContent(t),this},setPopupContent:function(t){return this._popup&&this._popup.setContent(t),this},unbindPopup:function(){return this._popup&&(this._popup=null,this.off("click",this.togglePopup,this).off("remove",this.closePopup,this).off("move",this._movePopup,this),this._popupHandlersAdded=!1),this},getPopup:function(){return this._popup},_movePopup:function(t){this._popup.setLatLng(t.latlng)}}),o.LayerGroup=o.Class.extend({initialize:function(t){this._layers={};var e,i;if(t)for(e=0,i=t.length;i>e;e++)this.addLayer(t[e])},addLayer:function(t){var e=this.getLayerId(t);return this._layers[e]=t,this._map&&this._map.addLayer(t),this},removeLayer:function(t){var e=t in this._layers?t:this.getLayerId(t);return this._map&&this._layers[e]&&this._map.removeLayer(this._layers[e]),delete this._layers[e],this},hasLayer:function(t){return t?t in this._layers||this.getLayerId(t)in this._layers:!1},clearLayers:function(){return this.eachLayer(this.removeLayer,this),this},invoke:function(t){var e,i,n=Array.prototype.slice.call(arguments,1);for(e in this._layers)i=this._layers[e],i[t]&&i[t].apply(i,n);return this},onAdd:function(t){this._map=t,this.eachLayer(t.addLayer,t)},onRemove:function(t){this.eachLayer(t.removeLayer,t),this._map=null},addTo:function(t){return t.addLayer(this),this},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},getLayer:function(t){return this._layers[t]},getLayers:function(){var t=[];for(var e in this._layers)t.push(this._layers[e]);return t},setZIndex:function(t){return this.invoke("setZIndex",t)},getLayerId:function(t){return o.stamp(t)}}),o.layerGroup=function(t){return new o.LayerGroup(t)},o.FeatureGroup=o.LayerGroup.extend({includes:o.Mixin.Events,statics:{EVENTS:"click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose"},addLayer:function(t){return this.hasLayer(t)?this:("on"in t&&t.on(o.FeatureGroup.EVENTS,this._propagateEvent,this),o.LayerGroup.prototype.addLayer.call(this,t),this._popupContent&&t.bindPopup&&t.bindPopup(this._popupContent,this._popupOptions),this.fire("layeradd",{layer:t}))},removeLayer:function(t){return this.hasLayer(t)?(t in this._layers&&(t=this._layers[t]),"off"in t&&t.off(o.FeatureGroup.EVENTS,this._propagateEvent,this),o.LayerGroup.prototype.removeLayer.call(this,t),this._popupContent&&this.invoke("unbindPopup"),this.fire("layerremove",{layer:t})):this},bindPopup:function(t,e){return this._popupContent=t,this._popupOptions=e,this.invoke("bindPopup",t,e)},openPopup:function(t){for(var e in this._layers){this._layers[e].openPopup(t);break}return this},setStyle:function(t){return this.invoke("setStyle",t)},bringToFront:function(){return this.invoke("bringToFront")},bringToBack:function(){return this.invoke("bringToBack")},getBounds:function(){var t=new o.LatLngBounds;return this.eachLayer(function(e){t.extend(e instanceof o.Marker?e.getLatLng():e.getBounds())}),t},_propagateEvent:function(t){t=o.extend({layer:t.target,target:this},t),this.fire(t.type,t)}}),o.featureGroup=function(t){return new o.FeatureGroup(t)},o.Path=o.Class.extend({includes:[o.Mixin.Events],statics:{CLIP_PADDING:function(){var e=o.Browser.mobile?1280:2e3,i=(e/Math.max(t.outerWidth,t.outerHeight)-1)/2;return Math.max(0,Math.min(.5,i))}()},options:{stroke:!0,color:"#0033ff",dashArray:null,lineCap:null,lineJoin:null,weight:5,opacity:.5,fill:!1,fillColor:null,fillOpacity:.2,clickable:!0},initialize:function(t){o.setOptions(this,t)},onAdd:function(t){this._map=t,this._container||(this._initElements(),this._initEvents()),this.projectLatlngs(),this._updatePath(),this._container&&this._map._pathRoot.appendChild(this._container),this.fire("add"),t.on({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){t._pathRoot.removeChild(this._container),this.fire("remove"),this._map=null,o.Browser.vml&&(this._container=null,this._stroke=null,this._fill=null),t.off({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},projectLatlngs:function(){},setStyle:function(t){return o.setOptions(this,t),this._container&&this._updateStyle(),this},redraw:function(){return this._map&&(this.projectLatlngs(),this._updatePath()),this}}),o.Map.include({_updatePathViewport:function(){var t=o.Path.CLIP_PADDING,e=this.getSize(),i=o.DomUtil.getPosition(this._mapPane),n=i.multiplyBy(-1)._subtract(e.multiplyBy(t)._round()),s=n.add(e.multiplyBy(1+2*t)._round());this._pathViewport=new o.Bounds(n,s)}}),o.Path.SVG_NS="http://www.w3.org/2000/svg",o.Browser.svg=!(!e.createElementNS||!e.createElementNS(o.Path.SVG_NS,"svg").createSVGRect),o.Path=o.Path.extend({statics:{SVG:o.Browser.svg},bringToFront:function(){var t=this._map._pathRoot,e=this._container;return e&&t.lastChild!==e&&t.appendChild(e),this},bringToBack:function(){var t=this._map._pathRoot,e=this._container,i=t.firstChild;return e&&i!==e&&t.insertBefore(e,i),this},getPathString:function(){},_createElement:function(t){return e.createElementNS(o.Path.SVG_NS,t)},_initElements:function(){this._map._initPathRoot(),this._initPath(),this._initStyle()},_initPath:function(){this._container=this._createElement("g"),this._path=this._createElement("path"),this.options.className&&o.DomUtil.addClass(this._path,this.options.className),this._container.appendChild(this._path)},_initStyle:function(){this.options.stroke&&(this._path.setAttribute("stroke-linejoin","round"),this._path.setAttribute("stroke-linecap","round")),this.options.fill&&this._path.setAttribute("fill-rule","evenodd"),this.options.pointerEvents&&this._path.setAttribute("pointer-events",this.options.pointerEvents),this.options.clickable||this.options.pointerEvents||this._path.setAttribute("pointer-events","none"),this._updateStyle()},_updateStyle:function(){this.options.stroke?(this._path.setAttribute("stroke",this.options.color),this._path.setAttribute("stroke-opacity",this.options.opacity),this._path.setAttribute("stroke-width",this.options.weight),this.options.dashArray?this._path.setAttribute("stroke-dasharray",this.options.dashArray):this._path.removeAttribute("stroke-dasharray"),this.options.lineCap&&this._path.setAttribute("stroke-linecap",this.options.lineCap),this.options.lineJoin&&this._path.setAttribute("stroke-linejoin",this.options.lineJoin)):this._path.setAttribute("stroke","none"),this.options.fill?(this._path.setAttribute("fill",this.options.fillColor||this.options.color),this._path.setAttribute("fill-opacity",this.options.fillOpacity)):this._path.setAttribute("fill","none")},_updatePath:function(){var t=this.getPathString();t||(t="M0 0"),this._path.setAttribute("d",t)},_initEvents:function(){if(this.options.clickable){(o.Browser.svg||!o.Browser.vml)&&o.DomUtil.addClass(this._path,"leaflet-clickable"),o.DomEvent.on(this._container,"click",this._onMouseClick,this);for(var t=["dblclick","mousedown","mouseover","mouseout","mousemove","contextmenu"],e=0;e<t.length;e++)o.DomEvent.on(this._container,t[e],this._fireMouseEvent,this)}},_onMouseClick:function(t){this._map.dragging&&this._map.dragging.moved()||this._fireMouseEvent(t)},_fireMouseEvent:function(t){if(this._map&&this.hasEventListeners(t.type)){var e=this._map,i=e.mouseEventToContainerPoint(t),n=e.containerPointToLayerPoint(i),s=e.layerPointToLatLng(n);this.fire(t.type,{latlng:s,layerPoint:n,containerPoint:i,originalEvent:t}),"contextmenu"===t.type&&o.DomEvent.preventDefault(t),"mousemove"!==t.type&&o.DomEvent.stopPropagation(t)}}}),o.Map.include({_initPathRoot:function(){this._pathRoot||(this._pathRoot=o.Path.prototype._createElement("svg"),this._panes.overlayPane.appendChild(this._pathRoot),this.options.zoomAnimation&&o.Browser.any3d?(o.DomUtil.addClass(this._pathRoot,"leaflet-zoom-animated"),
this.on({zoomanim:this._animatePathZoom,zoomend:this._endPathZoom})):o.DomUtil.addClass(this._pathRoot,"leaflet-zoom-hide"),this.on("moveend",this._updateSvgViewport),this._updateSvgViewport())},_animatePathZoom:function(t){var e=this.getZoomScale(t.zoom),i=this._getCenterOffset(t.center)._multiplyBy(-e)._add(this._pathViewport.min);this._pathRoot.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(i)+" scale("+e+") ",this._pathZooming=!0},_endPathZoom:function(){this._pathZooming=!1},_updateSvgViewport:function(){if(!this._pathZooming){this._updatePathViewport();var t=this._pathViewport,e=t.min,i=t.max,n=i.x-e.x,s=i.y-e.y,a=this._pathRoot,r=this._panes.overlayPane;o.Browser.mobileWebkit&&r.removeChild(a),o.DomUtil.setPosition(a,e),a.setAttribute("width",n),a.setAttribute("height",s),a.setAttribute("viewBox",[e.x,e.y,n,s].join(" ")),o.Browser.mobileWebkit&&r.appendChild(a)}}}),o.Path.include({bindPopup:function(t,e){return t instanceof o.Popup?this._popup=t:((!this._popup||e)&&(this._popup=new o.Popup(e,this)),this._popup.setContent(t)),this._popupHandlersAdded||(this.on("click",this._openPopup,this).on("remove",this.closePopup,this),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this._popup=null,this.off("click",this._openPopup).off("remove",this.closePopup),this._popupHandlersAdded=!1),this},openPopup:function(t){return this._popup&&(t=t||this._latlng||this._latlngs[Math.floor(this._latlngs.length/2)],this._openPopup({latlng:t})),this},closePopup:function(){return this._popup&&this._popup._close(),this},_openPopup:function(t){this._popup.setLatLng(t.latlng),this._map.openPopup(this._popup)}}),o.Browser.vml=!o.Browser.svg&&function(){try{var t=e.createElement("div");t.innerHTML='<v:shape adj="1"/>';var i=t.firstChild;return i.style.behavior="url(#default#VML)",i&&"object"==typeof i.adj}catch(n){return!1}}(),o.Path=o.Browser.svg||!o.Browser.vml?o.Path:o.Path.extend({statics:{VML:!0,CLIP_PADDING:.02},_createElement:function(){try{return e.namespaces.add("lvml","urn:schemas-microsoft-com:vml"),function(t){return e.createElement("<lvml:"+t+' class="lvml">')}}catch(t){return function(t){return e.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}}(),_initPath:function(){var t=this._container=this._createElement("shape");o.DomUtil.addClass(t,"leaflet-vml-shape"+(this.options.className?" "+this.options.className:"")),this.options.clickable&&o.DomUtil.addClass(t,"leaflet-clickable"),t.coordsize="1 1",this._path=this._createElement("path"),t.appendChild(this._path),this._map._pathRoot.appendChild(t)},_initStyle:function(){this._updateStyle()},_updateStyle:function(){var t=this._stroke,e=this._fill,i=this.options,n=this._container;n.stroked=i.stroke,n.filled=i.fill,i.stroke?(t||(t=this._stroke=this._createElement("stroke"),t.endcap="round",n.appendChild(t)),t.weight=i.weight+"px",t.color=i.color,t.opacity=i.opacity,i.dashArray?t.dashStyle=o.Util.isArray(i.dashArray)?i.dashArray.join(" "):i.dashArray.replace(/( *, *)/g," "):t.dashStyle="",i.lineCap&&(t.endcap=i.lineCap.replace("butt","flat")),i.lineJoin&&(t.joinstyle=i.lineJoin)):t&&(n.removeChild(t),this._stroke=null),i.fill?(e||(e=this._fill=this._createElement("fill"),n.appendChild(e)),e.color=i.fillColor||i.color,e.opacity=i.fillOpacity):e&&(n.removeChild(e),this._fill=null)},_updatePath:function(){var t=this._container.style;t.display="none",this._path.v=this.getPathString()+" ",t.display=""}}),o.Map.include(o.Browser.svg||!o.Browser.vml?{}:{_initPathRoot:function(){if(!this._pathRoot){var t=this._pathRoot=e.createElement("div");t.className="leaflet-vml-container",this._panes.overlayPane.appendChild(t),this.on("moveend",this._updatePathViewport),this._updatePathViewport()}}}),o.Browser.canvas=function(){return!!e.createElement("canvas").getContext}(),o.Path=o.Path.SVG&&!t.L_PREFER_CANVAS||!o.Browser.canvas?o.Path:o.Path.extend({statics:{CANVAS:!0,SVG:!1},redraw:function(){return this._map&&(this.projectLatlngs(),this._requestUpdate()),this},setStyle:function(t){return o.setOptions(this,t),this._map&&(this._updateStyle(),this._requestUpdate()),this},onRemove:function(t){t.off("viewreset",this.projectLatlngs,this).off("moveend",this._updatePath,this),this.options.clickable&&(this._map.off("click",this._onClick,this),this._map.off("mousemove",this._onMouseMove,this)),this._requestUpdate(),this.fire("remove"),this._map=null},_requestUpdate:function(){this._map&&!o.Path._updateRequest&&(o.Path._updateRequest=o.Util.requestAnimFrame(this._fireMapMoveEnd,this._map))},_fireMapMoveEnd:function(){o.Path._updateRequest=null,this.fire("moveend")},_initElements:function(){this._map._initPathRoot(),this._ctx=this._map._canvasCtx},_updateStyle:function(){var t=this.options;t.stroke&&(this._ctx.lineWidth=t.weight,this._ctx.strokeStyle=t.color),t.fill&&(this._ctx.fillStyle=t.fillColor||t.color),t.lineCap&&(this._ctx.lineCap=t.lineCap),t.lineJoin&&(this._ctx.lineJoin=t.lineJoin)},_drawPath:function(){var t,e,i,n,s,a;for(this._ctx.beginPath(),t=0,i=this._parts.length;i>t;t++){for(e=0,n=this._parts[t].length;n>e;e++)s=this._parts[t][e],a=(0===e?"move":"line")+"To",this._ctx[a](s.x,s.y);this instanceof o.Polygon&&this._ctx.closePath()}},_checkIfEmpty:function(){return!this._parts.length},_updatePath:function(){if(!this._checkIfEmpty()){var t=this._ctx,e=this.options;this._drawPath(),t.save(),this._updateStyle(),e.fill&&(t.globalAlpha=e.fillOpacity,t.fill(e.fillRule||"evenodd")),e.stroke&&(t.globalAlpha=e.opacity,t.stroke()),t.restore()}},_initEvents:function(){this.options.clickable&&(this._map.on("mousemove",this._onMouseMove,this),this._map.on("click dblclick contextmenu",this._fireMouseEvent,this))},_fireMouseEvent:function(t){this._containsPoint(t.layerPoint)&&this.fire(t.type,t)},_onMouseMove:function(t){this._map&&!this._map._animatingZoom&&(this._containsPoint(t.layerPoint)?(this._ctx.canvas.style.cursor="pointer",this._mouseInside=!0,this.fire("mouseover",t)):this._mouseInside&&(this._ctx.canvas.style.cursor="",this._mouseInside=!1,this.fire("mouseout",t)))}}),o.Map.include(o.Path.SVG&&!t.L_PREFER_CANVAS||!o.Browser.canvas?{}:{_initPathRoot:function(){var t,i=this._pathRoot;i||(i=this._pathRoot=e.createElement("canvas"),i.style.position="absolute",t=this._canvasCtx=i.getContext("2d"),t.lineCap="round",t.lineJoin="round",this._panes.overlayPane.appendChild(i),this.options.zoomAnimation&&(this._pathRoot.className="leaflet-zoom-animated",this.on("zoomanim",this._animatePathZoom),this.on("zoomend",this._endPathZoom)),this.on("moveend",this._updateCanvasViewport),this._updateCanvasViewport())},_updateCanvasViewport:function(){if(!this._pathZooming){this._updatePathViewport();var t=this._pathViewport,e=t.min,i=t.max.subtract(e),n=this._pathRoot;o.DomUtil.setPosition(n,e),n.width=i.x,n.height=i.y,n.getContext("2d").translate(-e.x,-e.y)}}}),o.LineUtil={simplify:function(t,e){if(!e||!t.length)return t.slice();var i=e*e;return t=this._reducePoints(t,i),t=this._simplifyDP(t,i)},pointToSegmentDistance:function(t,e,i){return Math.sqrt(this._sqClosestPointOnSegment(t,e,i,!0))},closestPointOnSegment:function(t,e,i){return this._sqClosestPointOnSegment(t,e,i)},_simplifyDP:function(t,e){var n=t.length,o=typeof Uint8Array!=i+""?Uint8Array:Array,s=new o(n);s[0]=s[n-1]=1,this._simplifyDPStep(t,s,e,0,n-1);var a,r=[];for(a=0;n>a;a++)s[a]&&r.push(t[a]);return r},_simplifyDPStep:function(t,e,i,n,o){var s,a,r,h=0;for(a=n+1;o-1>=a;a++)r=this._sqClosestPointOnSegment(t[a],t[n],t[o],!0),r>h&&(s=a,h=r);h>i&&(e[s]=1,this._simplifyDPStep(t,e,i,n,s),this._simplifyDPStep(t,e,i,s,o))},_reducePoints:function(t,e){for(var i=[t[0]],n=1,o=0,s=t.length;s>n;n++)this._sqDist(t[n],t[o])>e&&(i.push(t[n]),o=n);return s-1>o&&i.push(t[s-1]),i},clipSegment:function(t,e,i,n){var o,s,a,r=n?this._lastCode:this._getBitCode(t,i),h=this._getBitCode(e,i);for(this._lastCode=h;;){if(!(r|h))return[t,e];if(r&h)return!1;o=r||h,s=this._getEdgeIntersection(t,e,o,i),a=this._getBitCode(s,i),o===r?(t=s,r=a):(e=s,h=a)}},_getEdgeIntersection:function(t,e,i,n){var s=e.x-t.x,a=e.y-t.y,r=n.min,h=n.max;return 8&i?new o.Point(t.x+s*(h.y-t.y)/a,h.y):4&i?new o.Point(t.x+s*(r.y-t.y)/a,r.y):2&i?new o.Point(h.x,t.y+a*(h.x-t.x)/s):1&i?new o.Point(r.x,t.y+a*(r.x-t.x)/s):void 0},_getBitCode:function(t,e){var i=0;return t.x<e.min.x?i|=1:t.x>e.max.x&&(i|=2),t.y<e.min.y?i|=4:t.y>e.max.y&&(i|=8),i},_sqDist:function(t,e){var i=e.x-t.x,n=e.y-t.y;return i*i+n*n},_sqClosestPointOnSegment:function(t,e,i,n){var s,a=e.x,r=e.y,h=i.x-a,l=i.y-r,u=h*h+l*l;return u>0&&(s=((t.x-a)*h+(t.y-r)*l)/u,s>1?(a=i.x,r=i.y):s>0&&(a+=h*s,r+=l*s)),h=t.x-a,l=t.y-r,n?h*h+l*l:new o.Point(a,r)}},o.Polyline=o.Path.extend({initialize:function(t,e){o.Path.prototype.initialize.call(this,e),this._latlngs=this._convertLatLngs(t)},options:{smoothFactor:1,noClip:!1},projectLatlngs:function(){this._originalPoints=[];for(var t=0,e=this._latlngs.length;e>t;t++)this._originalPoints[t]=this._map.latLngToLayerPoint(this._latlngs[t])},getPathString:function(){for(var t=0,e=this._parts.length,i="";e>t;t++)i+=this._getPathPartStr(this._parts[t]);return i},getLatLngs:function(){return this._latlngs},setLatLngs:function(t){return this._latlngs=this._convertLatLngs(t),this.redraw()},addLatLng:function(t){return this._latlngs.push(o.latLng(t)),this.redraw()},spliceLatLngs:function(){var t=[].splice.apply(this._latlngs,arguments);return this._convertLatLngs(this._latlngs,!0),this.redraw(),t},closestLayerPoint:function(t){for(var e,i,n=1/0,s=this._parts,a=null,r=0,h=s.length;h>r;r++)for(var l=s[r],u=1,c=l.length;c>u;u++){e=l[u-1],i=l[u];var d=o.LineUtil._sqClosestPointOnSegment(t,e,i,!0);n>d&&(n=d,a=o.LineUtil._sqClosestPointOnSegment(t,e,i))}return a&&(a.distance=Math.sqrt(n)),a},getBounds:function(){return new o.LatLngBounds(this.getLatLngs())},_convertLatLngs:function(t,e){var i,n,s=e?t:[];for(i=0,n=t.length;n>i;i++){if(o.Util.isArray(t[i])&&"number"!=typeof t[i][0])return;s[i]=o.latLng(t[i])}return s},_initEvents:function(){o.Path.prototype._initEvents.call(this)},_getPathPartStr:function(t){for(var e,i=o.Path.VML,n=0,s=t.length,a="";s>n;n++)e=t[n],i&&e._round(),a+=(n?"L":"M")+e.x+" "+e.y;return a},_clipPoints:function(){var t,e,i,n=this._originalPoints,s=n.length;if(this.options.noClip)return void(this._parts=[n]);this._parts=[];var a=this._parts,r=this._map._pathViewport,h=o.LineUtil;for(t=0,e=0;s-1>t;t++)i=h.clipSegment(n[t],n[t+1],r,t),i&&(a[e]=a[e]||[],a[e].push(i[0]),(i[1]!==n[t+1]||t===s-2)&&(a[e].push(i[1]),e++))},_simplifyPoints:function(){for(var t=this._parts,e=o.LineUtil,i=0,n=t.length;n>i;i++)t[i]=e.simplify(t[i],this.options.smoothFactor)},_updatePath:function(){this._map&&(this._clipPoints(),this._simplifyPoints(),o.Path.prototype._updatePath.call(this))}}),o.polyline=function(t,e){return new o.Polyline(t,e)},o.PolyUtil={},o.PolyUtil.clipPolygon=function(t,e){var i,n,s,a,r,h,l,u,c,d=[1,4,2,8],p=o.LineUtil;for(n=0,l=t.length;l>n;n++)t[n]._code=p._getBitCode(t[n],e);for(a=0;4>a;a++){for(u=d[a],i=[],n=0,l=t.length,s=l-1;l>n;s=n++)r=t[n],h=t[s],r._code&u?h._code&u||(c=p._getEdgeIntersection(h,r,u,e),c._code=p._getBitCode(c,e),i.push(c)):(h._code&u&&(c=p._getEdgeIntersection(h,r,u,e),c._code=p._getBitCode(c,e),i.push(c)),i.push(r));t=i}return t},o.Polygon=o.Polyline.extend({options:{fill:!0},initialize:function(t,e){o.Polyline.prototype.initialize.call(this,t,e),this._initWithHoles(t)},_initWithHoles:function(t){var e,i,n;if(t&&o.Util.isArray(t[0])&&"number"!=typeof t[0][0])for(this._latlngs=this._convertLatLngs(t[0]),this._holes=t.slice(1),e=0,i=this._holes.length;i>e;e++)n=this._holes[e]=this._convertLatLngs(this._holes[e]),n[0].equals(n[n.length-1])&&n.pop();t=this._latlngs,t.length>=2&&t[0].equals(t[t.length-1])&&t.pop()},projectLatlngs:function(){if(o.Polyline.prototype.projectLatlngs.call(this),this._holePoints=[],this._holes){var t,e,i,n;for(t=0,i=this._holes.length;i>t;t++)for(this._holePoints[t]=[],e=0,n=this._holes[t].length;n>e;e++)this._holePoints[t][e]=this._map.latLngToLayerPoint(this._holes[t][e])}},setLatLngs:function(t){return t&&o.Util.isArray(t[0])&&"number"!=typeof t[0][0]?(this._initWithHoles(t),this.redraw()):o.Polyline.prototype.setLatLngs.call(this,t)},_clipPoints:function(){var t=this._originalPoints,e=[];if(this._parts=[t].concat(this._holePoints),!this.options.noClip){for(var i=0,n=this._parts.length;n>i;i++){var s=o.PolyUtil.clipPolygon(this._parts[i],this._map._pathViewport);s.length&&e.push(s)}this._parts=e}},_getPathPartStr:function(t){var e=o.Polyline.prototype._getPathPartStr.call(this,t);return e+(o.Browser.svg?"z":"x")}}),o.polygon=function(t,e){return new o.Polygon(t,e)},function(){function t(t){return o.FeatureGroup.extend({initialize:function(t,e){this._layers={},this._options=e,this.setLatLngs(t)},setLatLngs:function(e){var i=0,n=e.length;for(this.eachLayer(function(t){n>i?t.setLatLngs(e[i++]):this.removeLayer(t)},this);n>i;)this.addLayer(new t(e[i++],this._options));return this},getLatLngs:function(){var t=[];return this.eachLayer(function(e){t.push(e.getLatLngs())}),t}})}o.MultiPolyline=t(o.Polyline),o.MultiPolygon=t(o.Polygon),o.multiPolyline=function(t,e){return new o.MultiPolyline(t,e)},o.multiPolygon=function(t,e){return new o.MultiPolygon(t,e)}}(),o.Rectangle=o.Polygon.extend({initialize:function(t,e){o.Polygon.prototype.initialize.call(this,this._boundsToLatLngs(t),e)},setBounds:function(t){this.setLatLngs(this._boundsToLatLngs(t))},_boundsToLatLngs:function(t){return t=o.latLngBounds(t),[t.getSouthWest(),t.getNorthWest(),t.getNorthEast(),t.getSouthEast()]}}),o.rectangle=function(t,e){return new o.Rectangle(t,e)},o.Circle=o.Path.extend({initialize:function(t,e,i){o.Path.prototype.initialize.call(this,i),this._latlng=o.latLng(t),this._mRadius=e},options:{fill:!0},setLatLng:function(t){return this._latlng=o.latLng(t),this.redraw()},setRadius:function(t){return this._mRadius=t,this.redraw()},projectLatlngs:function(){var t=this._getLngRadius(),e=this._latlng,i=this._map.latLngToLayerPoint([e.lat,e.lng-t]);this._point=this._map.latLngToLayerPoint(e),this._radius=Math.max(this._point.x-i.x,1)},getBounds:function(){var t=this._getLngRadius(),e=this._mRadius/40075017*360,i=this._latlng;return new o.LatLngBounds([i.lat-e,i.lng-t],[i.lat+e,i.lng+t])},getLatLng:function(){return this._latlng},getPathString:function(){var t=this._point,e=this._radius;return this._checkIfEmpty()?"":o.Browser.svg?"M"+t.x+","+(t.y-e)+"A"+e+","+e+",0,1,1,"+(t.x-.1)+","+(t.y-e)+" z":(t._round(),e=Math.round(e),"AL "+t.x+","+t.y+" "+e+","+e+" 0,23592600")},getRadius:function(){return this._mRadius},_getLatRadius:function(){return this._mRadius/40075017*360},_getLngRadius:function(){return this._getLatRadius()/Math.cos(o.LatLng.DEG_TO_RAD*this._latlng.lat)},_checkIfEmpty:function(){if(!this._map)return!1;var t=this._map._pathViewport,e=this._radius,i=this._point;return i.x-e>t.max.x||i.y-e>t.max.y||i.x+e<t.min.x||i.y+e<t.min.y}}),o.circle=function(t,e,i){return new o.Circle(t,e,i)},o.CircleMarker=o.Circle.extend({options:{radius:10,weight:2},initialize:function(t,e){o.Circle.prototype.initialize.call(this,t,null,e),this._radius=this.options.radius},projectLatlngs:function(){this._point=this._map.latLngToLayerPoint(this._latlng)},_updateStyle:function(){o.Circle.prototype._updateStyle.call(this),this.setRadius(this.options.radius)},setLatLng:function(t){return o.Circle.prototype.setLatLng.call(this,t),this._popup&&this._popup._isOpen&&this._popup.setLatLng(t),this},setRadius:function(t){return this.options.radius=this._radius=t,this.redraw()},getRadius:function(){return this._radius}}),o.circleMarker=function(t,e){return new o.CircleMarker(t,e)},o.Polyline.include(o.Path.CANVAS?{_containsPoint:function(t,e){var i,n,s,a,r,h,l,u=this.options.weight/2;for(o.Browser.touch&&(u+=10),i=0,a=this._parts.length;a>i;i++)for(l=this._parts[i],n=0,r=l.length,s=r-1;r>n;s=n++)if((e||0!==n)&&(h=o.LineUtil.pointToSegmentDistance(t,l[s],l[n]),u>=h))return!0;return!1}}:{}),o.Polygon.include(o.Path.CANVAS?{_containsPoint:function(t){var e,i,n,s,a,r,h,l,u=!1;if(o.Polyline.prototype._containsPoint.call(this,t,!0))return!0;for(s=0,h=this._parts.length;h>s;s++)for(e=this._parts[s],a=0,l=e.length,r=l-1;l>a;r=a++)i=e[a],n=e[r],i.y>t.y!=n.y>t.y&&t.x<(n.x-i.x)*(t.y-i.y)/(n.y-i.y)+i.x&&(u=!u);return u}}:{}),o.Circle.include(o.Path.CANVAS?{_drawPath:function(){var t=this._point;this._ctx.beginPath(),this._ctx.arc(t.x,t.y,this._radius,0,2*Math.PI,!1)},_containsPoint:function(t){var e=this._point,i=this.options.stroke?this.options.weight/2:0;return t.distanceTo(e)<=this._radius+i}}:{}),o.CircleMarker.include(o.Path.CANVAS?{_updateStyle:function(){o.Path.prototype._updateStyle.call(this)}}:{}),o.GeoJSON=o.FeatureGroup.extend({initialize:function(t,e){o.setOptions(this,e),this._layers={},t&&this.addData(t)},addData:function(t){var e,i,n,s=o.Util.isArray(t)?t:t.features;if(s){for(e=0,i=s.length;i>e;e++)n=s[e],(n.geometries||n.geometry||n.features||n.coordinates)&&this.addData(s[e]);return this}var a=this.options;if(!a.filter||a.filter(t)){var r=o.GeoJSON.geometryToLayer(t,a.pointToLayer,a.coordsToLatLng,a);return r.feature=o.GeoJSON.asFeature(t),r.defaultOptions=r.options,this.resetStyle(r),a.onEachFeature&&a.onEachFeature(t,r),this.addLayer(r)}},resetStyle:function(t){var e=this.options.style;e&&(o.Util.extend(t.options,t.defaultOptions),this._setLayerStyle(t,e))},setStyle:function(t){this.eachLayer(function(e){this._setLayerStyle(e,t)},this)},_setLayerStyle:function(t,e){"function"==typeof e&&(e=e(t.feature)),t.setStyle&&t.setStyle(e)}}),o.extend(o.GeoJSON,{geometryToLayer:function(t,e,i,n){var s,a,r,h,l="Feature"===t.type?t.geometry:t,u=l.coordinates,c=[];switch(i=i||this.coordsToLatLng,l.type){case"Point":return s=i(u),e?e(t,s):new o.Marker(s);case"MultiPoint":for(r=0,h=u.length;h>r;r++)s=i(u[r]),c.push(e?e(t,s):new o.Marker(s));return new o.FeatureGroup(c);case"LineString":return a=this.coordsToLatLngs(u,0,i),new o.Polyline(a,n);case"Polygon":if(2===u.length&&!u[1].length)throw new Error("Invalid GeoJSON object.");return a=this.coordsToLatLngs(u,1,i),new o.Polygon(a,n);case"MultiLineString":return a=this.coordsToLatLngs(u,1,i),new o.MultiPolyline(a,n);case"MultiPolygon":return a=this.coordsToLatLngs(u,2,i),new o.MultiPolygon(a,n);case"GeometryCollection":for(r=0,h=l.geometries.length;h>r;r++)c.push(this.geometryToLayer({geometry:l.geometries[r],type:"Feature",properties:t.properties},e,i,n));return new o.FeatureGroup(c);default:throw new Error("Invalid GeoJSON object.")}},coordsToLatLng:function(t){return new o.LatLng(t[1],t[0],t[2])},coordsToLatLngs:function(t,e,i){var n,o,s,a=[];for(o=0,s=t.length;s>o;o++)n=e?this.coordsToLatLngs(t[o],e-1,i):(i||this.coordsToLatLng)(t[o]),a.push(n);return a},latLngToCoords:function(t){var e=[t.lng,t.lat];return t.alt!==i&&e.push(t.alt),e},latLngsToCoords:function(t){for(var e=[],i=0,n=t.length;n>i;i++)e.push(o.GeoJSON.latLngToCoords(t[i]));return e},getFeature:function(t,e){return t.feature?o.extend({},t.feature,{geometry:e}):o.GeoJSON.asFeature(e)},asFeature:function(t){return"Feature"===t.type?t:{type:"Feature",properties:{},geometry:t}}});var a={toGeoJSON:function(){return o.GeoJSON.getFeature(this,{type:"Point",coordinates:o.GeoJSON.latLngToCoords(this.getLatLng())})}};o.Marker.include(a),o.Circle.include(a),o.CircleMarker.include(a),o.Polyline.include({toGeoJSON:function(){return o.GeoJSON.getFeature(this,{type:"LineString",coordinates:o.GeoJSON.latLngsToCoords(this.getLatLngs())})}}),o.Polygon.include({toGeoJSON:function(){var t,e,i,n=[o.GeoJSON.latLngsToCoords(this.getLatLngs())];if(n[0].push(n[0][0]),this._holes)for(t=0,e=this._holes.length;e>t;t++)i=o.GeoJSON.latLngsToCoords(this._holes[t]),i.push(i[0]),n.push(i);return o.GeoJSON.getFeature(this,{type:"Polygon",coordinates:n})}}),function(){function t(t){return function(){var e=[];return this.eachLayer(function(t){e.push(t.toGeoJSON().geometry.coordinates)}),o.GeoJSON.getFeature(this,{type:t,coordinates:e})}}o.MultiPolyline.include({toGeoJSON:t("MultiLineString")}),o.MultiPolygon.include({toGeoJSON:t("MultiPolygon")}),o.LayerGroup.include({toGeoJSON:function(){var e,i=this.feature&&this.feature.geometry,n=[];if(i&&"MultiPoint"===i.type)return t("MultiPoint").call(this);var s=i&&"GeometryCollection"===i.type;return this.eachLayer(function(t){t.toGeoJSON&&(e=t.toGeoJSON(),n.push(s?e.geometry:o.GeoJSON.asFeature(e)))}),s?o.GeoJSON.getFeature(this,{geometries:n,type:"GeometryCollection"}):{type:"FeatureCollection",features:n}}})}(),o.geoJson=function(t,e){return new o.GeoJSON(t,e)},o.DomEvent={addListener:function(t,e,i,n){var s,a,r,h=o.stamp(i),l="_leaflet_"+e+h;return t[l]?this:(s=function(e){return i.call(n||t,e||o.DomEvent._getEvent())},o.Browser.pointer&&0===e.indexOf("touch")?this.addPointerListener(t,e,s,h):(o.Browser.touch&&"dblclick"===e&&this.addDoubleTapListener&&this.addDoubleTapListener(t,s,h),"addEventListener"in t?"mousewheel"===e?(t.addEventListener("DOMMouseScroll",s,!1),t.addEventListener(e,s,!1)):"mouseenter"===e||"mouseleave"===e?(a=s,r="mouseenter"===e?"mouseover":"mouseout",s=function(e){return o.DomEvent._checkMouse(t,e)?a(e):void 0},t.addEventListener(r,s,!1)):"click"===e&&o.Browser.android?(a=s,s=function(t){return o.DomEvent._filterClick(t,a)},t.addEventListener(e,s,!1)):t.addEventListener(e,s,!1):"attachEvent"in t&&t.attachEvent("on"+e,s),t[l]=s,this))},removeListener:function(t,e,i){var n=o.stamp(i),s="_leaflet_"+e+n,a=t[s];return a?(o.Browser.pointer&&0===e.indexOf("touch")?this.removePointerListener(t,e,n):o.Browser.touch&&"dblclick"===e&&this.removeDoubleTapListener?this.removeDoubleTapListener(t,n):"removeEventListener"in t?"mousewheel"===e?(t.removeEventListener("DOMMouseScroll",a,!1),t.removeEventListener(e,a,!1)):"mouseenter"===e||"mouseleave"===e?t.removeEventListener("mouseenter"===e?"mouseover":"mouseout",a,!1):t.removeEventListener(e,a,!1):"detachEvent"in t&&t.detachEvent("on"+e,a),t[s]=null,this):this},stopPropagation:function(t){return t.stopPropagation?t.stopPropagation():t.cancelBubble=!0,o.DomEvent._skipped(t),this},disableScrollPropagation:function(t){var e=o.DomEvent.stopPropagation;return o.DomEvent.on(t,"mousewheel",e).on(t,"MozMousePixelScroll",e)},disableClickPropagation:function(t){for(var e=o.DomEvent.stopPropagation,i=o.Draggable.START.length-1;i>=0;i--)o.DomEvent.on(t,o.Draggable.START[i],e);return o.DomEvent.on(t,"click",o.DomEvent._fakeStop).on(t,"dblclick",e)},preventDefault:function(t){return t.preventDefault?t.preventDefault():t.returnValue=!1,this},stop:function(t){return o.DomEvent.preventDefault(t).stopPropagation(t)},getMousePosition:function(t,e){if(!e)return new o.Point(t.clientX,t.clientY);var i=e.getBoundingClientRect();return new o.Point(t.clientX-i.left-e.clientLeft,t.clientY-i.top-e.clientTop)},getWheelDelta:function(t){var e=0;return t.wheelDelta&&(e=t.wheelDelta/120),t.detail&&(e=-t.detail/3),e},_skipEvents:{},_fakeStop:function(t){o.DomEvent._skipEvents[t.type]=!0},_skipped:function(t){var e=this._skipEvents[t.type];return this._skipEvents[t.type]=!1,e},_checkMouse:function(t,e){var i=e.relatedTarget;if(!i)return!0;try{for(;i&&i!==t;)i=i.parentNode}catch(n){return!1}return i!==t},_getEvent:function(){var e=t.event;if(!e)for(var i=arguments.callee.caller;i&&(e=i.arguments[0],!e||t.Event!==e.constructor);)i=i.caller;return e},_filterClick:function(t,e){var i=t.timeStamp||t.originalEvent.timeStamp,n=o.DomEvent._lastClick&&i-o.DomEvent._lastClick;return n&&n>100&&500>n||t.target._simulatedClick&&!t._simulated?void o.DomEvent.stop(t):(o.DomEvent._lastClick=i,e(t))}},o.DomEvent.on=o.DomEvent.addListener,o.DomEvent.off=o.DomEvent.removeListener,o.Draggable=o.Class.extend({includes:o.Mixin.Events,statics:{START:o.Browser.touch?["touchstart","mousedown"]:["mousedown"],END:{mousedown:"mouseup",touchstart:"touchend",pointerdown:"touchend",MSPointerDown:"touchend"},MOVE:{mousedown:"mousemove",touchstart:"touchmove",pointerdown:"touchmove",MSPointerDown:"touchmove"}},initialize:function(t,e){this._element=t,this._dragStartTarget=e||t},enable:function(){if(!this._enabled){for(var t=o.Draggable.START.length-1;t>=0;t--)o.DomEvent.on(this._dragStartTarget,o.Draggable.START[t],this._onDown,this);this._enabled=!0}},disable:function(){if(this._enabled){for(var t=o.Draggable.START.length-1;t>=0;t--)o.DomEvent.off(this._dragStartTarget,o.Draggable.START[t],this._onDown,this);this._enabled=!1,this._moved=!1}},_onDown:function(t){if(this._moved=!1,!t.shiftKey&&(1===t.which||1===t.button||t.touches)&&(o.DomEvent.stopPropagation(t),!o.Draggable._disabled&&(o.DomUtil.disableImageDrag(),o.DomUtil.disableTextSelection(),!this._moving))){var i=t.touches?t.touches[0]:t;this._startPoint=new o.Point(i.clientX,i.clientY),this._startPos=this._newPos=o.DomUtil.getPosition(this._element),o.DomEvent.on(e,o.Draggable.MOVE[t.type],this._onMove,this).on(e,o.Draggable.END[t.type],this._onUp,this)}},_onMove:function(t){if(t.touches&&t.touches.length>1)return void(this._moved=!0);var i=t.touches&&1===t.touches.length?t.touches[0]:t,n=new o.Point(i.clientX,i.clientY),s=n.subtract(this._startPoint);(s.x||s.y)&&(o.Browser.touch&&Math.abs(s.x)+Math.abs(s.y)<3||(o.DomEvent.preventDefault(t),this._moved||(this.fire("dragstart"),this._moved=!0,this._startPos=o.DomUtil.getPosition(this._element).subtract(s),o.DomUtil.addClass(e.body,"leaflet-dragging"),this._lastTarget=t.target||t.srcElement,o.DomUtil.addClass(this._lastTarget,"leaflet-drag-target")),this._newPos=this._startPos.add(s),this._moving=!0,o.Util.cancelAnimFrame(this._animRequest),this._animRequest=o.Util.requestAnimFrame(this._updatePosition,this,!0,this._dragStartTarget)))},_updatePosition:function(){this.fire("predrag"),o.DomUtil.setPosition(this._element,this._newPos),this.fire("drag")},_onUp:function(){o.DomUtil.removeClass(e.body,"leaflet-dragging"),this._lastTarget&&(o.DomUtil.removeClass(this._lastTarget,"leaflet-drag-target"),this._lastTarget=null);for(var t in o.Draggable.MOVE)o.DomEvent.off(e,o.Draggable.MOVE[t],this._onMove).off(e,o.Draggable.END[t],this._onUp);o.DomUtil.enableImageDrag(),o.DomUtil.enableTextSelection(),this._moved&&this._moving&&(o.Util.cancelAnimFrame(this._animRequest),this.fire("dragend",{distance:this._newPos.distanceTo(this._startPos)})),this._moving=!1}}),o.Handler=o.Class.extend({initialize:function(t){this._map=t},enable:function(){this._enabled||(this._enabled=!0,this.addHooks())},disable:function(){this._enabled&&(this._enabled=!1,this.removeHooks())},enabled:function(){return!!this._enabled}}),o.Map.mergeOptions({dragging:!0,inertia:!o.Browser.android23,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,inertiaThreshold:o.Browser.touch?32:18,easeLinearity:.25,worldCopyJump:!1}),o.Map.Drag=o.Handler.extend({addHooks:function(){if(!this._draggable){var t=this._map;this._draggable=new o.Draggable(t._mapPane,t._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),t.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDrag,this),t.on("viewreset",this._onViewReset,this),t.whenReady(this._onViewReset,this))}this._draggable.enable()},removeHooks:function(){this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){var t=this._map;t._panAnim&&t._panAnim.stop(),t.fire("movestart").fire("dragstart"),t.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(){if(this._map.options.inertia){var t=this._lastTime=+new Date,e=this._lastPos=this._draggable._newPos;this._positions.push(e),this._times.push(t),t-this._times[0]>200&&(this._positions.shift(),this._times.shift())}this._map.fire("move").fire("drag")},_onViewReset:function(){var t=this._map.getSize()._divideBy(2),e=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=e.subtract(t).x,this._worldWidth=this._map.project([0,180]).x},_onPreDrag:function(){var t=this._worldWidth,e=Math.round(t/2),i=this._initialWorldOffset,n=this._draggable._newPos.x,o=(n-e+i)%t+e-i,s=(n+e+i)%t-e-i,a=Math.abs(o+i)<Math.abs(s+i)?o:s;this._draggable._newPos.x=a},_onDragEnd:function(t){var e=this._map,i=e.options,n=+new Date-this._lastTime,s=!i.inertia||n>i.inertiaThreshold||!this._positions[0];if(e.fire("dragend",t),s)e.fire("moveend");else{var a=this._lastPos.subtract(this._positions[0]),r=(this._lastTime+n-this._times[0])/1e3,h=i.easeLinearity,l=a.multiplyBy(h/r),u=l.distanceTo([0,0]),c=Math.min(i.inertiaMaxSpeed,u),d=l.multiplyBy(c/u),p=c/(i.inertiaDeceleration*h),_=d.multiplyBy(-p/2).round();_.x&&_.y?(_=e._limitOffset(_,e.options.maxBounds),o.Util.requestAnimFrame(function(){e.panBy(_,{duration:p,easeLinearity:h,noMoveStart:!0})})):e.fire("moveend")}}}),o.Map.addInitHook("addHandler","dragging",o.Map.Drag),o.Map.mergeOptions({doubleClickZoom:!0}),o.Map.DoubleClickZoom=o.Handler.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(t){var e=this._map,i=e.getZoom()+(t.originalEvent.shiftKey?-1:1);"center"===e.options.doubleClickZoom?e.setZoom(i):e.setZoomAround(t.containerPoint,i)}}),o.Map.addInitHook("addHandler","doubleClickZoom",o.Map.DoubleClickZoom),o.Map.mergeOptions({scrollWheelZoom:!0}),o.Map.ScrollWheelZoom=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"mousewheel",this._onWheelScroll,this),o.DomEvent.on(this._map._container,"MozMousePixelScroll",o.DomEvent.preventDefault),this._delta=0},removeHooks:function(){o.DomEvent.off(this._map._container,"mousewheel",this._onWheelScroll),o.DomEvent.off(this._map._container,"MozMousePixelScroll",o.DomEvent.preventDefault)},_onWheelScroll:function(t){var e=o.DomEvent.getWheelDelta(t);this._delta+=e,this._lastMousePos=this._map.mouseEventToContainerPoint(t),this._startTime||(this._startTime=+new Date);var i=Math.max(40-(+new Date-this._startTime),0);clearTimeout(this._timer),this._timer=setTimeout(o.bind(this._performZoom,this),i),o.DomEvent.preventDefault(t),o.DomEvent.stopPropagation(t)},_performZoom:function(){var t=this._map,e=this._delta,i=t.getZoom();e=e>0?Math.ceil(e):Math.floor(e),e=Math.max(Math.min(e,4),-4),e=t._limitZoom(i+e)-i,this._delta=0,this._startTime=null,e&&("center"===t.options.scrollWheelZoom?t.setZoom(i+e):t.setZoomAround(this._lastMousePos,i+e))}}),o.Map.addInitHook("addHandler","scrollWheelZoom",o.Map.ScrollWheelZoom),o.extend(o.DomEvent,{_touchstart:o.Browser.msPointer?"MSPointerDown":o.Browser.pointer?"pointerdown":"touchstart",_touchend:o.Browser.msPointer?"MSPointerUp":o.Browser.pointer?"pointerup":"touchend",addDoubleTapListener:function(t,i,n){function s(t){var e;if(o.Browser.pointer?(_.push(t.pointerId),e=_.length):e=t.touches.length,!(e>1)){var i=Date.now(),n=i-(r||i);h=t.touches?t.touches[0]:t,l=n>0&&u>=n,r=i}}function a(t){if(o.Browser.pointer){var e=_.indexOf(t.pointerId);if(-1===e)return;_.splice(e,1)}if(l){if(o.Browser.pointer){var n,s={};for(var a in h)n=h[a],"function"==typeof n?s[a]=n.bind(h):s[a]=n;h=s}h.type="dblclick",i(h),r=null}}var r,h,l=!1,u=250,c="_leaflet_",d=this._touchstart,p=this._touchend,_=[];t[c+d+n]=s,t[c+p+n]=a;var m=o.Browser.pointer?e.documentElement:t;return t.addEventListener(d,s,!1),m.addEventListener(p,a,!1),o.Browser.pointer&&m.addEventListener(o.DomEvent.POINTER_CANCEL,a,!1),this},removeDoubleTapListener:function(t,i){var n="_leaflet_";return t.removeEventListener(this._touchstart,t[n+this._touchstart+i],!1),(o.Browser.pointer?e.documentElement:t).removeEventListener(this._touchend,t[n+this._touchend+i],!1),o.Browser.pointer&&e.documentElement.removeEventListener(o.DomEvent.POINTER_CANCEL,t[n+this._touchend+i],!1),this}}),o.extend(o.DomEvent,{POINTER_DOWN:o.Browser.msPointer?"MSPointerDown":"pointerdown",POINTER_MOVE:o.Browser.msPointer?"MSPointerMove":"pointermove",POINTER_UP:o.Browser.msPointer?"MSPointerUp":"pointerup",POINTER_CANCEL:o.Browser.msPointer?"MSPointerCancel":"pointercancel",_pointers:[],_pointerDocumentListener:!1,addPointerListener:function(t,e,i,n){switch(e){case"touchstart":return this.addPointerListenerStart(t,e,i,n);
case"touchend":return this.addPointerListenerEnd(t,e,i,n);case"touchmove":return this.addPointerListenerMove(t,e,i,n);default:throw"Unknown touch event type"}},addPointerListenerStart:function(t,i,n,s){var a="_leaflet_",r=this._pointers,h=function(t){"mouse"!==t.pointerType&&t.pointerType!==t.MSPOINTER_TYPE_MOUSE&&o.DomEvent.preventDefault(t);for(var e=!1,i=0;i<r.length;i++)if(r[i].pointerId===t.pointerId){e=!0;break}e||r.push(t),t.touches=r.slice(),t.changedTouches=[t],n(t)};if(t[a+"touchstart"+s]=h,t.addEventListener(this.POINTER_DOWN,h,!1),!this._pointerDocumentListener){var l=function(t){for(var e=0;e<r.length;e++)if(r[e].pointerId===t.pointerId){r.splice(e,1);break}};e.documentElement.addEventListener(this.POINTER_UP,l,!1),e.documentElement.addEventListener(this.POINTER_CANCEL,l,!1),this._pointerDocumentListener=!0}return this},addPointerListenerMove:function(t,e,i,n){function o(t){if(t.pointerType!==t.MSPOINTER_TYPE_MOUSE&&"mouse"!==t.pointerType||0!==t.buttons){for(var e=0;e<a.length;e++)if(a[e].pointerId===t.pointerId){a[e]=t;break}t.touches=a.slice(),t.changedTouches=[t],i(t)}}var s="_leaflet_",a=this._pointers;return t[s+"touchmove"+n]=o,t.addEventListener(this.POINTER_MOVE,o,!1),this},addPointerListenerEnd:function(t,e,i,n){var o="_leaflet_",s=this._pointers,a=function(t){for(var e=0;e<s.length;e++)if(s[e].pointerId===t.pointerId){s.splice(e,1);break}t.touches=s.slice(),t.changedTouches=[t],i(t)};return t[o+"touchend"+n]=a,t.addEventListener(this.POINTER_UP,a,!1),t.addEventListener(this.POINTER_CANCEL,a,!1),this},removePointerListener:function(t,e,i){var n="_leaflet_",o=t[n+e+i];switch(e){case"touchstart":t.removeEventListener(this.POINTER_DOWN,o,!1);break;case"touchmove":t.removeEventListener(this.POINTER_MOVE,o,!1);break;case"touchend":t.removeEventListener(this.POINTER_UP,o,!1),t.removeEventListener(this.POINTER_CANCEL,o,!1)}return this}}),o.Map.mergeOptions({touchZoom:o.Browser.touch&&!o.Browser.android23,bounceAtZoomLimits:!0}),o.Map.TouchZoom=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"touchstart",this._onTouchStart,this)},removeHooks:function(){o.DomEvent.off(this._map._container,"touchstart",this._onTouchStart,this)},_onTouchStart:function(t){var i=this._map;if(t.touches&&2===t.touches.length&&!i._animatingZoom&&!this._zooming){var n=i.mouseEventToLayerPoint(t.touches[0]),s=i.mouseEventToLayerPoint(t.touches[1]),a=i._getCenterLayerPoint();this._startCenter=n.add(s)._divideBy(2),this._startDist=n.distanceTo(s),this._moved=!1,this._zooming=!0,this._centerOffset=a.subtract(this._startCenter),i._panAnim&&i._panAnim.stop(),o.DomEvent.on(e,"touchmove",this._onTouchMove,this).on(e,"touchend",this._onTouchEnd,this),o.DomEvent.preventDefault(t)}},_onTouchMove:function(t){var e=this._map;if(t.touches&&2===t.touches.length&&this._zooming){var i=e.mouseEventToLayerPoint(t.touches[0]),n=e.mouseEventToLayerPoint(t.touches[1]);this._scale=i.distanceTo(n)/this._startDist,this._delta=i._add(n)._divideBy(2)._subtract(this._startCenter),1!==this._scale&&(e.options.bounceAtZoomLimits||!(e.getZoom()===e.getMinZoom()&&this._scale<1||e.getZoom()===e.getMaxZoom()&&this._scale>1))&&(this._moved||(o.DomUtil.addClass(e._mapPane,"leaflet-touching"),e.fire("movestart").fire("zoomstart"),this._moved=!0),o.Util.cancelAnimFrame(this._animRequest),this._animRequest=o.Util.requestAnimFrame(this._updateOnMove,this,!0,this._map._container),o.DomEvent.preventDefault(t))}},_updateOnMove:function(){var t=this._map,e=this._getScaleOrigin(),i=t.layerPointToLatLng(e),n=t.getScaleZoom(this._scale);t._animateZoom(i,n,this._startCenter,this._scale,this._delta,!1,!0)},_onTouchEnd:function(){if(!this._moved||!this._zooming)return void(this._zooming=!1);var t=this._map;this._zooming=!1,o.DomUtil.removeClass(t._mapPane,"leaflet-touching"),o.Util.cancelAnimFrame(this._animRequest),o.DomEvent.off(e,"touchmove",this._onTouchMove).off(e,"touchend",this._onTouchEnd);var i=this._getScaleOrigin(),n=t.layerPointToLatLng(i),s=t.getZoom(),a=t.getScaleZoom(this._scale)-s,r=a>0?Math.ceil(a):Math.floor(a),h=t._limitZoom(s+r),l=t.getZoomScale(h)/this._scale;t._animateZoom(n,h,i,l)},_getScaleOrigin:function(){var t=this._centerOffset.subtract(this._delta).divideBy(this._scale);return this._startCenter.add(t)}}),o.Map.addInitHook("addHandler","touchZoom",o.Map.TouchZoom),o.Map.mergeOptions({tap:!0,tapTolerance:15}),o.Map.Tap=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){o.DomEvent.off(this._map._container,"touchstart",this._onDown,this)},_onDown:function(t){if(t.touches){if(o.DomEvent.preventDefault(t),this._fireClick=!0,t.touches.length>1)return this._fireClick=!1,void clearTimeout(this._holdTimeout);var i=t.touches[0],n=i.target;this._startPos=this._newPos=new o.Point(i.clientX,i.clientY),n.tagName&&"a"===n.tagName.toLowerCase()&&o.DomUtil.addClass(n,"leaflet-active"),this._holdTimeout=setTimeout(o.bind(function(){this._isTapValid()&&(this._fireClick=!1,this._onUp(),this._simulateEvent("contextmenu",i))},this),1e3),o.DomEvent.on(e,"touchmove",this._onMove,this).on(e,"touchend",this._onUp,this)}},_onUp:function(t){if(clearTimeout(this._holdTimeout),o.DomEvent.off(e,"touchmove",this._onMove,this).off(e,"touchend",this._onUp,this),this._fireClick&&t&&t.changedTouches){var i=t.changedTouches[0],n=i.target;n&&n.tagName&&"a"===n.tagName.toLowerCase()&&o.DomUtil.removeClass(n,"leaflet-active"),this._isTapValid()&&this._simulateEvent("click",i)}},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_onMove:function(t){var e=t.touches[0];this._newPos=new o.Point(e.clientX,e.clientY)},_simulateEvent:function(i,n){var o=e.createEvent("MouseEvents");o._simulated=!0,n.target._simulatedClick=!0,o.initMouseEvent(i,!0,!0,t,1,n.screenX,n.screenY,n.clientX,n.clientY,!1,!1,!1,!1,0,null),n.target.dispatchEvent(o)}}),o.Browser.touch&&!o.Browser.pointer&&o.Map.addInitHook("addHandler","tap",o.Map.Tap),o.Map.mergeOptions({boxZoom:!0}),o.Map.BoxZoom=o.Handler.extend({initialize:function(t){this._map=t,this._container=t._container,this._pane=t._panes.overlayPane,this._moved=!1},addHooks:function(){o.DomEvent.on(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){o.DomEvent.off(this._container,"mousedown",this._onMouseDown),this._moved=!1},moved:function(){return this._moved},_onMouseDown:function(t){return this._moved=!1,!t.shiftKey||1!==t.which&&1!==t.button?!1:(o.DomUtil.disableTextSelection(),o.DomUtil.disableImageDrag(),this._startLayerPoint=this._map.mouseEventToLayerPoint(t),void o.DomEvent.on(e,"mousemove",this._onMouseMove,this).on(e,"mouseup",this._onMouseUp,this).on(e,"keydown",this._onKeyDown,this))},_onMouseMove:function(t){this._moved||(this._box=o.DomUtil.create("div","leaflet-zoom-box",this._pane),o.DomUtil.setPosition(this._box,this._startLayerPoint),this._container.style.cursor="crosshair",this._map.fire("boxzoomstart"));var e=this._startLayerPoint,i=this._box,n=this._map.mouseEventToLayerPoint(t),s=n.subtract(e),a=new o.Point(Math.min(n.x,e.x),Math.min(n.y,e.y));o.DomUtil.setPosition(i,a),this._moved=!0,i.style.width=Math.max(0,Math.abs(s.x)-4)+"px",i.style.height=Math.max(0,Math.abs(s.y)-4)+"px"},_finish:function(){this._moved&&(this._pane.removeChild(this._box),this._container.style.cursor=""),o.DomUtil.enableTextSelection(),o.DomUtil.enableImageDrag(),o.DomEvent.off(e,"mousemove",this._onMouseMove).off(e,"mouseup",this._onMouseUp).off(e,"keydown",this._onKeyDown)},_onMouseUp:function(t){this._finish();var e=this._map,i=e.mouseEventToLayerPoint(t);if(!this._startLayerPoint.equals(i)){var n=new o.LatLngBounds(e.layerPointToLatLng(this._startLayerPoint),e.layerPointToLatLng(i));e.fitBounds(n),e.fire("boxzoomend",{boxZoomBounds:n})}},_onKeyDown:function(t){27===t.keyCode&&this._finish()}}),o.Map.addInitHook("addHandler","boxZoom",o.Map.BoxZoom),o.Map.mergeOptions({keyboard:!0,keyboardPanOffset:80,keyboardZoomOffset:1}),o.Map.Keyboard=o.Handler.extend({keyCodes:{left:[37],right:[39],down:[40],up:[38],zoomIn:[187,107,61,171],zoomOut:[189,109,173]},initialize:function(t){this._map=t,this._setPanOffset(t.options.keyboardPanOffset),this._setZoomOffset(t.options.keyboardZoomOffset)},addHooks:function(){var t=this._map._container;-1===t.tabIndex&&(t.tabIndex="0"),o.DomEvent.on(t,"focus",this._onFocus,this).on(t,"blur",this._onBlur,this).on(t,"mousedown",this._onMouseDown,this),this._map.on("focus",this._addHooks,this).on("blur",this._removeHooks,this)},removeHooks:function(){this._removeHooks();var t=this._map._container;o.DomEvent.off(t,"focus",this._onFocus,this).off(t,"blur",this._onBlur,this).off(t,"mousedown",this._onMouseDown,this),this._map.off("focus",this._addHooks,this).off("blur",this._removeHooks,this)},_onMouseDown:function(){if(!this._focused){var i=e.body,n=e.documentElement,o=i.scrollTop||n.scrollTop,s=i.scrollLeft||n.scrollLeft;this._map._container.focus(),t.scrollTo(s,o)}},_onFocus:function(){this._focused=!0,this._map.fire("focus")},_onBlur:function(){this._focused=!1,this._map.fire("blur")},_setPanOffset:function(t){var e,i,n=this._panKeys={},o=this.keyCodes;for(e=0,i=o.left.length;i>e;e++)n[o.left[e]]=[-1*t,0];for(e=0,i=o.right.length;i>e;e++)n[o.right[e]]=[t,0];for(e=0,i=o.down.length;i>e;e++)n[o.down[e]]=[0,t];for(e=0,i=o.up.length;i>e;e++)n[o.up[e]]=[0,-1*t]},_setZoomOffset:function(t){var e,i,n=this._zoomKeys={},o=this.keyCodes;for(e=0,i=o.zoomIn.length;i>e;e++)n[o.zoomIn[e]]=t;for(e=0,i=o.zoomOut.length;i>e;e++)n[o.zoomOut[e]]=-t},_addHooks:function(){o.DomEvent.on(e,"keydown",this._onKeyDown,this)},_removeHooks:function(){o.DomEvent.off(e,"keydown",this._onKeyDown,this)},_onKeyDown:function(t){var e=t.keyCode,i=this._map;if(e in this._panKeys){if(i._panAnim&&i._panAnim._inProgress)return;i.panBy(this._panKeys[e]),i.options.maxBounds&&i.panInsideBounds(i.options.maxBounds)}else{if(!(e in this._zoomKeys))return;i.setZoom(i.getZoom()+this._zoomKeys[e])}o.DomEvent.stop(t)}}),o.Map.addInitHook("addHandler","keyboard",o.Map.Keyboard),o.Handler.MarkerDrag=o.Handler.extend({initialize:function(t){this._marker=t},addHooks:function(){var t=this._marker._icon;this._draggable||(this._draggable=new o.Draggable(t,t)),this._draggable.on("dragstart",this._onDragStart,this).on("drag",this._onDrag,this).on("dragend",this._onDragEnd,this),this._draggable.enable(),o.DomUtil.addClass(this._marker._icon,"leaflet-marker-draggable")},removeHooks:function(){this._draggable.off("dragstart",this._onDragStart,this).off("drag",this._onDrag,this).off("dragend",this._onDragEnd,this),this._draggable.disable(),o.DomUtil.removeClass(this._marker._icon,"leaflet-marker-draggable")},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){this._marker.closePopup().fire("movestart").fire("dragstart")},_onDrag:function(){var t=this._marker,e=t._shadow,i=o.DomUtil.getPosition(t._icon),n=t._map.layerPointToLatLng(i);e&&o.DomUtil.setPosition(e,i),t._latlng=n,t.fire("move",{latlng:n}).fire("drag")},_onDragEnd:function(t){this._marker.fire("moveend").fire("dragend",t)}}),o.Control=o.Class.extend({options:{position:"topright"},initialize:function(t){o.setOptions(this,t)},getPosition:function(){return this.options.position},setPosition:function(t){var e=this._map;return e&&e.removeControl(this),this.options.position=t,e&&e.addControl(this),this},getContainer:function(){return this._container},addTo:function(t){this._map=t;var e=this._container=this.onAdd(t),i=this.getPosition(),n=t._controlCorners[i];return o.DomUtil.addClass(e,"leaflet-control"),-1!==i.indexOf("bottom")?n.insertBefore(e,n.firstChild):n.appendChild(e),this},removeFrom:function(t){var e=this.getPosition(),i=t._controlCorners[e];return i.removeChild(this._container),this._map=null,this.onRemove&&this.onRemove(t),this},_refocusOnMap:function(){this._map&&this._map.getContainer().focus()}}),o.control=function(t){return new o.Control(t)},o.Map.include({addControl:function(t){return t.addTo(this),this},removeControl:function(t){return t.removeFrom(this),this},_initControlPos:function(){function t(t,s){var a=i+t+" "+i+s;e[t+s]=o.DomUtil.create("div",a,n)}var e=this._controlCorners={},i="leaflet-",n=this._controlContainer=o.DomUtil.create("div",i+"control-container",this._container);t("top","left"),t("top","right"),t("bottom","left"),t("bottom","right")},_clearControlPos:function(){this._container.removeChild(this._controlContainer)}}),o.Control.Zoom=o.Control.extend({options:{position:"topleft",zoomInText:"+",zoomInTitle:"Zoom in",zoomOutText:"-",zoomOutTitle:"Zoom out"},onAdd:function(t){var e="leaflet-control-zoom",i=o.DomUtil.create("div",e+" leaflet-bar");return this._map=t,this._zoomInButton=this._createButton(this.options.zoomInText,this.options.zoomInTitle,e+"-in",i,this._zoomIn,this),this._zoomOutButton=this._createButton(this.options.zoomOutText,this.options.zoomOutTitle,e+"-out",i,this._zoomOut,this),this._updateDisabled(),t.on("zoomend zoomlevelschange",this._updateDisabled,this),i},onRemove:function(t){t.off("zoomend zoomlevelschange",this._updateDisabled,this)},_zoomIn:function(t){this._map.zoomIn(t.shiftKey?3:1)},_zoomOut:function(t){this._map.zoomOut(t.shiftKey?3:1)},_createButton:function(t,e,i,n,s,a){var r=o.DomUtil.create("a",i,n);r.innerHTML=t,r.href="#",r.title=e;var h=o.DomEvent.stopPropagation;return o.DomEvent.on(r,"click",h).on(r,"mousedown",h).on(r,"dblclick",h).on(r,"click",o.DomEvent.preventDefault).on(r,"click",s,a).on(r,"click",this._refocusOnMap,a),r},_updateDisabled:function(){var t=this._map,e="leaflet-disabled";o.DomUtil.removeClass(this._zoomInButton,e),o.DomUtil.removeClass(this._zoomOutButton,e),t._zoom===t.getMinZoom()&&o.DomUtil.addClass(this._zoomOutButton,e),t._zoom===t.getMaxZoom()&&o.DomUtil.addClass(this._zoomInButton,e)}}),o.Map.mergeOptions({zoomControl:!0}),o.Map.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new o.Control.Zoom,this.addControl(this.zoomControl))}),o.control.zoom=function(t){return new o.Control.Zoom(t)},o.Control.Attribution=o.Control.extend({options:{position:"bottomright",prefix:'<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'},initialize:function(t){o.setOptions(this,t),this._attributions={}},onAdd:function(t){this._container=o.DomUtil.create("div","leaflet-control-attribution"),o.DomEvent.disableClickPropagation(this._container);for(var e in t._layers)t._layers[e].getAttribution&&this.addAttribution(t._layers[e].getAttribution());return t.on("layeradd",this._onLayerAdd,this).on("layerremove",this._onLayerRemove,this),this._update(),this._container},onRemove:function(t){t.off("layeradd",this._onLayerAdd).off("layerremove",this._onLayerRemove)},setPrefix:function(t){return this.options.prefix=t,this._update(),this},addAttribution:function(t){return t?(this._attributions[t]||(this._attributions[t]=0),this._attributions[t]++,this._update(),this):void 0},removeAttribution:function(t){return t?(this._attributions[t]&&(this._attributions[t]--,this._update()),this):void 0},_update:function(){if(this._map){var t=[];for(var e in this._attributions)this._attributions[e]&&t.push(e);var i=[];this.options.prefix&&i.push(this.options.prefix),t.length&&i.push(t.join(", ")),this._container.innerHTML=i.join(" | ")}},_onLayerAdd:function(t){t.layer.getAttribution&&this.addAttribution(t.layer.getAttribution())},_onLayerRemove:function(t){t.layer.getAttribution&&this.removeAttribution(t.layer.getAttribution())}}),o.Map.mergeOptions({attributionControl:!0}),o.Map.addInitHook(function(){this.options.attributionControl&&(this.attributionControl=(new o.Control.Attribution).addTo(this))}),o.control.attribution=function(t){return new o.Control.Attribution(t)},o.Control.Scale=o.Control.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0,updateWhenIdle:!1},onAdd:function(t){this._map=t;var e="leaflet-control-scale",i=o.DomUtil.create("div",e),n=this.options;return this._addScales(n,e,i),t.on(n.updateWhenIdle?"moveend":"move",this._update,this),t.whenReady(this._update,this),i},onRemove:function(t){t.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(t,e,i){t.metric&&(this._mScale=o.DomUtil.create("div",e+"-line",i)),t.imperial&&(this._iScale=o.DomUtil.create("div",e+"-line",i))},_update:function(){var t=this._map.getBounds(),e=t.getCenter().lat,i=6378137*Math.PI*Math.cos(e*Math.PI/180),n=i*(t.getNorthEast().lng-t.getSouthWest().lng)/180,o=this._map.getSize(),s=this.options,a=0;o.x>0&&(a=n*(s.maxWidth/o.x)),this._updateScales(s,a)},_updateScales:function(t,e){t.metric&&e&&this._updateMetric(e),t.imperial&&e&&this._updateImperial(e)},_updateMetric:function(t){var e=this._getRoundNum(t);this._mScale.style.width=this._getScaleWidth(e/t)+"px",this._mScale.innerHTML=1e3>e?e+" m":e/1e3+" km"},_updateImperial:function(t){var e,i,n,o=3.2808399*t,s=this._iScale;o>5280?(e=o/5280,i=this._getRoundNum(e),s.style.width=this._getScaleWidth(i/e)+"px",s.innerHTML=i+" mi"):(n=this._getRoundNum(o),s.style.width=this._getScaleWidth(n/o)+"px",s.innerHTML=n+" ft")},_getScaleWidth:function(t){return Math.round(this.options.maxWidth*t)-10},_getRoundNum:function(t){var e=Math.pow(10,(Math.floor(t)+"").length-1),i=t/e;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:1,e*i}}),o.control.scale=function(t){return new o.Control.Scale(t)},o.Control.Layers=o.Control.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0},initialize:function(t,e,i){o.setOptions(this,i),this._layers={},this._lastZIndex=0,this._handlingClick=!1;for(var n in t)this._addLayer(t[n],n);for(n in e)this._addLayer(e[n],n,!0)},onAdd:function(t){return this._initLayout(),this._update(),t.on("layeradd",this._onLayerChange,this).on("layerremove",this._onLayerChange,this),this._container},onRemove:function(t){t.off("layeradd",this._onLayerChange,this).off("layerremove",this._onLayerChange,this)},addBaseLayer:function(t,e){return this._addLayer(t,e),this._update(),this},addOverlay:function(t,e){return this._addLayer(t,e,!0),this._update(),this},removeLayer:function(t){var e=o.stamp(t);return delete this._layers[e],this._update(),this},_initLayout:function(){var t="leaflet-control-layers",e=this._container=o.DomUtil.create("div",t);e.setAttribute("aria-haspopup",!0),o.Browser.touch?o.DomEvent.on(e,"click",o.DomEvent.stopPropagation):o.DomEvent.disableClickPropagation(e).disableScrollPropagation(e);var i=this._form=o.DomUtil.create("form",t+"-list");if(this.options.collapsed){o.Browser.android||o.DomEvent.on(e,"mouseover",this._expand,this).on(e,"mouseout",this._collapse,this);var n=this._layersLink=o.DomUtil.create("a",t+"-toggle",e);n.href="#",n.title="Layers",o.Browser.touch?o.DomEvent.on(n,"click",o.DomEvent.stop).on(n,"click",this._expand,this):o.DomEvent.on(n,"focus",this._expand,this),o.DomEvent.on(i,"click",function(){setTimeout(o.bind(this._onInputClick,this),0)},this),this._map.on("click",this._collapse,this)}else this._expand();this._baseLayersList=o.DomUtil.create("div",t+"-base",i),this._separator=o.DomUtil.create("div",t+"-separator",i),this._overlaysList=o.DomUtil.create("div",t+"-overlays",i),e.appendChild(i)},_addLayer:function(t,e,i){var n=o.stamp(t);this._layers[n]={layer:t,name:e,overlay:i},this.options.autoZIndex&&t.setZIndex&&(this._lastZIndex++,t.setZIndex(this._lastZIndex))},_update:function(){if(this._container){this._baseLayersList.innerHTML="",this._overlaysList.innerHTML="";var t,e,i=!1,n=!1;for(t in this._layers)e=this._layers[t],this._addItem(e),n=n||e.overlay,i=i||!e.overlay;this._separator.style.display=n&&i?"":"none"}},_onLayerChange:function(t){var e=this._layers[o.stamp(t.layer)];if(e){this._handlingClick||this._update();var i=e.overlay?"layeradd"===t.type?"overlayadd":"overlayremove":"layeradd"===t.type?"baselayerchange":null;i&&this._map.fire(i,e)}},_createRadioElement:function(t,i){var n='<input type="radio" class="leaflet-control-layers-selector" name="'+t+'"';i&&(n+=' checked="checked"'),n+="/>";var o=e.createElement("div");return o.innerHTML=n,o.firstChild},_addItem:function(t){var i,n=e.createElement("label"),s=this._map.hasLayer(t.layer);t.overlay?(i=e.createElement("input"),i.type="checkbox",i.className="leaflet-control-layers-selector",i.defaultChecked=s):i=this._createRadioElement("leaflet-base-layers",s),i.layerId=o.stamp(t.layer),o.DomEvent.on(i,"click",this._onInputClick,this);var a=e.createElement("span");a.innerHTML=" "+t.name,n.appendChild(i),n.appendChild(a);var r=t.overlay?this._overlaysList:this._baseLayersList;return r.appendChild(n),n},_onInputClick:function(){var t,e,i,n=this._form.getElementsByTagName("input"),o=n.length;for(this._handlingClick=!0,t=0;o>t;t++)e=n[t],i=this._layers[e.layerId],e.checked&&!this._map.hasLayer(i.layer)?this._map.addLayer(i.layer):!e.checked&&this._map.hasLayer(i.layer)&&this._map.removeLayer(i.layer);this._handlingClick=!1,this._refocusOnMap()},_expand:function(){o.DomUtil.addClass(this._container,"leaflet-control-layers-expanded")},_collapse:function(){this._container.className=this._container.className.replace(" leaflet-control-layers-expanded","")}}),o.control.layers=function(t,e,i){return new o.Control.Layers(t,e,i)},o.PosAnimation=o.Class.extend({includes:o.Mixin.Events,run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._newPos=e,this.fire("start"),t.style[o.DomUtil.TRANSITION]="all "+(i||.25)+"s cubic-bezier(0,0,"+(n||.5)+",1)",o.DomEvent.on(t,o.DomUtil.TRANSITION_END,this._onTransitionEnd,this),o.DomUtil.setPosition(t,e),o.Util.falseFn(t.offsetWidth),this._stepTimer=setInterval(o.bind(this._onStep,this),50)},stop:function(){this._inProgress&&(o.DomUtil.setPosition(this._el,this._getPos()),this._onTransitionEnd(),o.Util.falseFn(this._el.offsetWidth))},_onStep:function(){var t=this._getPos();return t?(this._el._leaflet_pos=t,void this.fire("step")):void this._onTransitionEnd()},_transformRe:/([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,_getPos:function(){var e,i,n,s=this._el,a=t.getComputedStyle(s);if(o.Browser.any3d){if(n=a[o.DomUtil.TRANSFORM].match(this._transformRe),!n)return;e=parseFloat(n[1]),i=parseFloat(n[2])}else e=parseFloat(a.left),i=parseFloat(a.top);return new o.Point(e,i,!0)},_onTransitionEnd:function(){o.DomEvent.off(this._el,o.DomUtil.TRANSITION_END,this._onTransitionEnd,this),this._inProgress&&(this._inProgress=!1,this._el.style[o.DomUtil.TRANSITION]="",this._el._leaflet_pos=this._newPos,clearInterval(this._stepTimer),this.fire("step").fire("end"))}}),o.Map.include({setView:function(t,e,n){if(e=e===i?this._zoom:this._limitZoom(e),t=this._limitCenter(o.latLng(t),e,this.options.maxBounds),n=n||{},this._panAnim&&this._panAnim.stop(),this._loaded&&!n.reset&&n!==!0){n.animate!==i&&(n.zoom=o.extend({animate:n.animate},n.zoom),n.pan=o.extend({animate:n.animate},n.pan));var s=this._zoom!==e?this._tryAnimatedZoom&&this._tryAnimatedZoom(t,e,n.zoom):this._tryAnimatedPan(t,n.pan);if(s)return clearTimeout(this._sizeTimer),this}return this._resetView(t,e),this},panBy:function(t,e){if(t=o.point(t).round(),e=e||{},!t.x&&!t.y)return this;if(this._panAnim||(this._panAnim=new o.PosAnimation,this._panAnim.on({step:this._onPanTransitionStep,end:this._onPanTransitionEnd},this)),e.noMoveStart||this.fire("movestart"),e.animate!==!1){o.DomUtil.addClass(this._mapPane,"leaflet-pan-anim");var i=this._getMapPanePos().subtract(t);this._panAnim.run(this._mapPane,i,e.duration||.25,e.easeLinearity)}else this._rawPanBy(t),this.fire("move").fire("moveend");return this},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){o.DomUtil.removeClass(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(t,e){var i=this._getCenterOffset(t)._floor();return(e&&e.animate)===!0||this.getSize().contains(i)?(this.panBy(i,e),!0):!1}}),o.PosAnimation=o.DomUtil.TRANSITION?o.PosAnimation:o.PosAnimation.extend({run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._duration=i||.25,this._easeOutPower=1/Math.max(n||.5,.2),this._startPos=o.DomUtil.getPosition(t),this._offset=e.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){this._inProgress&&(this._step(),this._complete())},_animate:function(){this._animId=o.Util.requestAnimFrame(this._animate,this),this._step()},_step:function(){var t=+new Date-this._startTime,e=1e3*this._duration;e>t?this._runFrame(this._easeOut(t/e)):(this._runFrame(1),this._complete())},_runFrame:function(t){var e=this._startPos.add(this._offset.multiplyBy(t));o.DomUtil.setPosition(this._el,e),this.fire("step")},_complete:function(){o.Util.cancelAnimFrame(this._animId),this._inProgress=!1,this.fire("end")},_easeOut:function(t){return 1-Math.pow(1-t,this._easeOutPower)}}),o.Map.mergeOptions({zoomAnimation:!0,zoomAnimationThreshold:4}),o.DomUtil.TRANSITION&&o.Map.addInitHook(function(){this._zoomAnimated=this.options.zoomAnimation&&o.DomUtil.TRANSITION&&o.Browser.any3d&&!o.Browser.android23&&!o.Browser.mobileOpera,this._zoomAnimated&&o.DomEvent.on(this._mapPane,o.DomUtil.TRANSITION_END,this._catchTransitionEnd,this)}),o.Map.include(o.DomUtil.TRANSITION?{_catchTransitionEnd:function(t){this._animatingZoom&&t.propertyName.indexOf("transform")>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(t,e,i){if(this._animatingZoom)return!0;if(i=i||{},!this._zoomAnimated||i.animate===!1||this._nothingToAnimate()||Math.abs(e-this._zoom)>this.options.zoomAnimationThreshold)return!1;var n=this.getZoomScale(e),o=this._getCenterOffset(t)._divideBy(1-1/n),s=this._getCenterLayerPoint()._add(o);return i.animate===!0||this.getSize().contains(o)?(this.fire("movestart").fire("zoomstart"),this._animateZoom(t,e,s,n,null,!0),!0):!1},_animateZoom:function(t,e,i,n,s,a,r){r||(this._animatingZoom=!0),o.DomUtil.addClass(this._mapPane,"leaflet-zoom-anim"),this._animateToCenter=t,this._animateToZoom=e,o.Draggable&&(o.Draggable._disabled=!0),o.Util.requestAnimFrame(function(){this.fire("zoomanim",{center:t,zoom:e,origin:i,scale:n,delta:s,backwards:a}),setTimeout(o.bind(this._onZoomTransitionEnd,this),250)},this)},_onZoomTransitionEnd:function(){this._animatingZoom&&(this._animatingZoom=!1,o.DomUtil.removeClass(this._mapPane,"leaflet-zoom-anim"),o.Util.requestAnimFrame(function(){this._resetView(this._animateToCenter,this._animateToZoom,!0,!0),o.Draggable&&(o.Draggable._disabled=!1)},this))}}:{}),o.TileLayer.include({_animateZoom:function(t){this._animating||(this._animating=!0,this._prepareBgBuffer());var e=this._bgBuffer,i=o.DomUtil.TRANSFORM,n=t.delta?o.DomUtil.getTranslateString(t.delta):e.style[i],s=o.DomUtil.getScaleString(t.scale,t.origin);e.style[i]=t.backwards?s+" "+n:n+" "+s},_endZoomAnim:function(){var t=this._tileContainer,e=this._bgBuffer;t.style.visibility="",t.parentNode.appendChild(t),o.Util.falseFn(e.offsetWidth);var i=this._map.getZoom();(i>this.options.maxZoom||i<this.options.minZoom)&&this._clearBgBuffer(),this._animating=!1},_clearBgBuffer:function(){var t=this._map;!t||t._animatingZoom||t.touchZoom._zooming||(this._bgBuffer.innerHTML="",this._bgBuffer.style[o.DomUtil.TRANSFORM]="")},_prepareBgBuffer:function(){var t=this._tileContainer,e=this._bgBuffer,i=this._getLoadedTilesPercentage(e),n=this._getLoadedTilesPercentage(t);return e&&i>.5&&.5>n?(t.style.visibility="hidden",void this._stopLoadingImages(t)):(e.style.visibility="hidden",e.style[o.DomUtil.TRANSFORM]="",this._tileContainer=e,e=this._bgBuffer=t,this._stopLoadingImages(e),void clearTimeout(this._clearBgBufferTimer))},_getLoadedTilesPercentage:function(t){var e,i,n=t.getElementsByTagName("img"),o=0;for(e=0,i=n.length;i>e;e++)n[e].complete&&o++;return o/i},_stopLoadingImages:function(t){var e,i,n,s=Array.prototype.slice.call(t.getElementsByTagName("img"));for(e=0,i=s.length;i>e;e++)n=s[e],n.complete||(n.onload=o.Util.falseFn,n.onerror=o.Util.falseFn,n.src=o.Util.emptyImageUrl,n.parentNode.removeChild(n))}}),o.Map.include({_defaultLocateOptions:{watch:!1,setView:!1,maxZoom:1/0,timeout:1e4,maximumAge:0,enableHighAccuracy:!1},locate:function(t){if(t=this._locateOptions=o.extend(this._defaultLocateOptions,t),!navigator.geolocation)return this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this;var e=o.bind(this._handleGeolocationResponse,this),i=o.bind(this._handleGeolocationError,this);return t.watch?this._locationWatchId=navigator.geolocation.watchPosition(e,i,t):navigator.geolocation.getCurrentPosition(e,i,t),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(t){var e=t.code,i=t.message||(1===e?"permission denied":2===e?"position unavailable":"timeout");this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:e,message:"Geolocation error: "+i+"."})},_handleGeolocationResponse:function(t){var e=t.coords.latitude,i=t.coords.longitude,n=new o.LatLng(e,i),s=180*t.coords.accuracy/40075017,a=s/Math.cos(o.LatLng.DEG_TO_RAD*e),r=o.latLngBounds([e-s,i-a],[e+s,i+a]),h=this._locateOptions;if(h.setView){var l=Math.min(this.getBoundsZoom(r),h.maxZoom);this.setView(n,l)}var u={latlng:n,bounds:r,timestamp:t.timestamp};for(var c in t.coords)"number"==typeof t.coords[c]&&(u[c]=t.coords[c]);this.fire("locationfound",u)}})}(window,document);
},{}],4:[function(require,module,exports){
!function(e,t){"object"==typeof exports&&exports&&"string"!=typeof exports.nodeName?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):(e.Mustache={},t(e.Mustache))}(this,function(e){function t(e){return"function"==typeof e}function n(e){return g(e)?"array":typeof e}function r(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function i(e,t){return null!=e&&"object"==typeof e&&t in e}function o(e,t){return v.call(e,t)}function s(e){return!o(w,e)}function a(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return y[e]})}function u(t,n){function i(){if(w&&!y)for(;v.length;)delete d[v.pop()];else v=[];w=!1,y=!1}function o(e){if("string"==typeof e&&(e=e.split(k,2)),!g(e)||2!==e.length)throw new Error("Invalid tags: "+e);a=new RegExp(r(e[0])+"\\s*"),u=new RegExp("\\s*"+r(e[1])),h=new RegExp("\\s*"+r("}"+e[1]))}if(!t)return[];var a,u,h,f=[],d=[],v=[],w=!1,y=!1;o(n||e.tags);for(var U,T,j,S,V,C,A=new l(t);!A.eos();){if(U=A.pos,j=A.scanUntil(a))for(var I=0,R=j.length;R>I;++I)S=j.charAt(I),s(S)?v.push(d.length):y=!0,d.push(["text",S,U,U+1]),U+=1,"\n"===S&&i();if(!A.scan(a))break;if(w=!0,T=A.scan(E)||"name",A.scan(x),"="===T?(j=A.scanUntil(b),A.scan(b),A.scanUntil(u)):"{"===T?(j=A.scanUntil(h),A.scan(m),A.scanUntil(u),T="&"):j=A.scanUntil(u),!A.scan(u))throw new Error("Unclosed tag at "+A.pos);if(V=[T,j,U,A.pos],d.push(V),"#"===T||"^"===T)f.push(V);else if("/"===T){if(C=f.pop(),!C)throw new Error('Unopened section "'+j+'" at '+U);if(C[1]!==j)throw new Error('Unclosed section "'+C[1]+'" at '+U)}else"name"===T||"{"===T||"&"===T?y=!0:"="===T&&o(j)}if(C=f.pop())throw new Error('Unclosed section "'+C[1]+'" at '+A.pos);return p(c(d))}function c(e){for(var t,n,r=[],i=0,o=e.length;o>i;++i)t=e[i],t&&("text"===t[0]&&n&&"text"===n[0]?(n[1]+=t[1],n[3]=t[3]):(r.push(t),n=t));return r}function p(e){for(var t,n,r=[],i=r,o=[],s=0,a=e.length;a>s;++s)switch(t=e[s],t[0]){case"#":case"^":i.push(t),o.push(t),i=t[4]=[];break;case"/":n=o.pop(),n[5]=t[2],i=o.length>0?o[o.length-1][4]:r;break;default:i.push(t)}return r}function l(e){this.string=e,this.tail=e,this.pos=0}function h(e,t){this.view=e,this.cache={".":this.view},this.parent=t}function f(){this.cache={}}var d=Object.prototype.toString,g=Array.isArray||function(e){return"[object Array]"===d.call(e)},v=RegExp.prototype.test,w=/\S/,y={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"},x=/\s*/,k=/\s+/,b=/\s*=/,m=/\s*\}/,E=/#|\^|\/|>|\{|&|=|!/;l.prototype.eos=function(){return""===this.tail},l.prototype.scan=function(e){var t=this.tail.match(e);if(!t||0!==t.index)return"";var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n},l.prototype.scanUntil=function(e){var t,n=this.tail.search(e);switch(n){case-1:t=this.tail,this.tail="";break;case 0:t="";break;default:t=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=t.length,t},h.prototype.push=function(e){return new h(e,this)},h.prototype.lookup=function(e){var n,r=this.cache;if(r.hasOwnProperty(e))n=r[e];else{for(var o,s,a=this,u=!1;a;){if(e.indexOf(".")>0)for(n=a.view,o=e.split("."),s=0;null!=n&&s<o.length;)s===o.length-1&&(u=i(n,o[s])),n=n[o[s++]];else n=a.view[e],u=i(a.view,e);if(u)break;a=a.parent}r[e]=n}return t(n)&&(n=n.call(this.view)),n},f.prototype.clearCache=function(){this.cache={}},f.prototype.parse=function(e,t){var n=this.cache,r=n[e];return null==r&&(r=n[e]=u(e,t)),r},f.prototype.render=function(e,t,n){var r=this.parse(e),i=t instanceof h?t:new h(t);return this.renderTokens(r,i,n,e)},f.prototype.renderTokens=function(e,t,n,r){for(var i,o,s,a="",u=0,c=e.length;c>u;++u)s=void 0,i=e[u],o=i[0],"#"===o?s=this.renderSection(i,t,n,r):"^"===o?s=this.renderInverted(i,t,n,r):">"===o?s=this.renderPartial(i,t,n,r):"&"===o?s=this.unescapedValue(i,t):"name"===o?s=this.escapedValue(i,t):"text"===o&&(s=this.rawValue(i)),void 0!==s&&(a+=s);return a},f.prototype.renderSection=function(e,n,r,i){function o(e){return s.render(e,n,r)}var s=this,a="",u=n.lookup(e[1]);if(u){if(g(u))for(var c=0,p=u.length;p>c;++c)a+=this.renderTokens(e[4],n.push(u[c]),r,i);else if("object"==typeof u||"string"==typeof u||"number"==typeof u)a+=this.renderTokens(e[4],n.push(u),r,i);else if(t(u)){if("string"!=typeof i)throw new Error("Cannot use higher-order sections without the original template");u=u.call(n.view,i.slice(e[3],e[5]),o),null!=u&&(a+=u)}else a+=this.renderTokens(e[4],n,r,i);return a}},f.prototype.renderInverted=function(e,t,n,r){var i=t.lookup(e[1]);return!i||g(i)&&0===i.length?this.renderTokens(e[4],t,n,r):void 0},f.prototype.renderPartial=function(e,n,r){if(r){var i=t(r)?r(e[1]):r[e[1]];return null!=i?this.renderTokens(this.parse(i),n,r,i):void 0}},f.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);return null!=n?n:void 0},f.prototype.escapedValue=function(t,n){var r=n.lookup(t[1]);return null!=r?e.escape(r):void 0},f.prototype.rawValue=function(e){return e[1]},e.name="mustache.js",e.version="2.2.1",e.tags=["{{","}}"];var U=new f;e.clearCache=function(){return U.clearCache()},e.parse=function(e,t){return U.parse(e,t)},e.render=function(e,t,r){if("string"!=typeof e)throw new TypeError('Invalid template! Template should be a "string" but "'+n(e)+'" was given as the first argument for mustache#render(template, view, partials)');return U.render(e,t,r)},e.to_html=function(n,r,i,o){var s=e.render(n,r,i);return t(o)?void o(s):s},e.escape=a,e.Scanner=l,e.Context=h,e.Writer=f});
},{}],5:[function(require,module,exports){
function cleanUrl(t){"use strict";return/^https?/.test(t.getScheme())?t.toString():/^mailto?/.test(t.getScheme())?t.toString():"data"==t.getScheme()&&/^image/.test(t.getPath())?t.toString():void 0}function cleanId(t){return t}var html_sanitize=require("./sanitizer-bundle.js");module.exports=function(t){return t?html_sanitize(t,cleanUrl,cleanId):""};
},{"./sanitizer-bundle.js":6}],6:[function(require,module,exports){
var URI=function(){function e(e){var t=(""+e).match(p);return t?new s(c(t[1]),c(t[2]),c(t[3]),c(t[4]),c(t[5]),c(t[6]),c(t[7])):null}function t(e,t,o,i,l,c,m){var u=new s(n(e,d),n(t,d),a(o),i>0?i.toString():null,n(l,f),null,a(m));return c&&("string"==typeof c?u.setRawQuery(c.replace(/[^?&=0-9A-Za-z_\-~.%]/g,r)):u.setAllParameters(c)),u}function a(e){return"string"==typeof e?encodeURIComponent(e):null}function n(e,t){return"string"==typeof e?encodeURI(e).replace(t,r):null}function r(e){var t=e.charCodeAt(0);return"%"+"0123456789ABCDEF".charAt(t>>4&15)+"0123456789ABCDEF".charAt(15&t)}function o(e){return e.replace(/(^|\/)\.(?:\/|$)/g,"$1").replace(/\/{2,}/g,"/")}function i(e){if(null===e)return null;for(var t,a=o(e),n=u;(t=a.replace(n,"$1"))!=a;a=t);return a}function l(e,t){var a=e.clone(),n=t.hasScheme();n?a.setRawScheme(t.getRawScheme()):n=t.hasCredentials(),n?a.setRawCredentials(t.getRawCredentials()):n=t.hasDomain(),n?a.setRawDomain(t.getRawDomain()):n=t.hasPort();var r=t.getRawPath(),o=i(r);if(n)a.setPort(t.getPort()),o=o&&o.replace(h,"");else if(n=!!r){if(47!==o.charCodeAt(0)){var l=i(a.getRawPath()||"").replace(h,""),s=l.lastIndexOf("/")+1;o=i((s?l.substring(0,s):"")+i(r)).replace(h,"")}}else o=o&&o.replace(h,""),o!==r&&a.setRawPath(o);return n?a.setRawPath(o):n=t.hasQuery(),n?a.setRawQuery(t.getRawQuery()):n=t.hasFragment(),n&&a.setRawFragment(t.getRawFragment()),a}function s(e,t,a,n,r,o,i){this.scheme_=e,this.credentials_=t,this.domain_=a,this.port_=n,this.path_=r,this.query_=o,this.fragment_=i,this.paramCache_=null}function c(e){return"string"==typeof e&&e.length>0?e:null}var m=new RegExp("(/|^)(?:[^./][^/]*|\\.{2,}(?:[^./][^/]*)|\\.{3,}[^/]*)/\\.\\.(?:/|$)"),u=new RegExp(m),h=/^(?:\.\.\/)*(?:\.\.$)?/;s.prototype.toString=function(){var e=[];return null!==this.scheme_&&e.push(this.scheme_,":"),null!==this.domain_&&(e.push("//"),null!==this.credentials_&&e.push(this.credentials_,"@"),e.push(this.domain_),null!==this.port_&&e.push(":",this.port_.toString())),null!==this.path_&&e.push(this.path_),null!==this.query_&&e.push("?",this.query_),null!==this.fragment_&&e.push("#",this.fragment_),e.join("")},s.prototype.clone=function(){return new s(this.scheme_,this.credentials_,this.domain_,this.port_,this.path_,this.query_,this.fragment_)},s.prototype.getScheme=function(){return this.scheme_&&decodeURIComponent(this.scheme_).toLowerCase()},s.prototype.getRawScheme=function(){return this.scheme_},s.prototype.setScheme=function(e){return this.scheme_=n(e,d),this},s.prototype.setRawScheme=function(e){return this.scheme_=e?e:null,this},s.prototype.hasScheme=function(){return null!==this.scheme_},s.prototype.getCredentials=function(){return this.credentials_&&decodeURIComponent(this.credentials_)},s.prototype.getRawCredentials=function(){return this.credentials_},s.prototype.setCredentials=function(e){return this.credentials_=n(e,d),this},s.prototype.setRawCredentials=function(e){return this.credentials_=e?e:null,this},s.prototype.hasCredentials=function(){return null!==this.credentials_},s.prototype.getDomain=function(){return this.domain_&&decodeURIComponent(this.domain_)},s.prototype.getRawDomain=function(){return this.domain_},s.prototype.setDomain=function(e){return this.setRawDomain(e&&encodeURIComponent(e))},s.prototype.setRawDomain=function(e){return this.domain_=e?e:null,this.setRawPath(this.path_)},s.prototype.hasDomain=function(){return null!==this.domain_},s.prototype.getPort=function(){return this.port_&&decodeURIComponent(this.port_)},s.prototype.setPort=function(e){if(e){if(e=Number(e),e!==(65535&e))throw new Error("Bad port number "+e);this.port_=""+e}else this.port_=null;return this},s.prototype.hasPort=function(){return null!==this.port_},s.prototype.getPath=function(){return this.path_&&decodeURIComponent(this.path_)},s.prototype.getRawPath=function(){return this.path_},s.prototype.setPath=function(e){return this.setRawPath(n(e,f))},s.prototype.setRawPath=function(e){return e?(e=String(e),this.path_=!this.domain_||/^\//.test(e)?e:"/"+e):this.path_=null,this},s.prototype.hasPath=function(){return null!==this.path_},s.prototype.getQuery=function(){return this.query_&&decodeURIComponent(this.query_).replace(/\+/g," ")},s.prototype.getRawQuery=function(){return this.query_},s.prototype.setQuery=function(e){return this.paramCache_=null,this.query_=a(e),this},s.prototype.setRawQuery=function(e){return this.paramCache_=null,this.query_=e?e:null,this},s.prototype.hasQuery=function(){return null!==this.query_},s.prototype.setAllParameters=function(e){if("object"==typeof e&&!(e instanceof Array)&&(e instanceof Object||"[object Array]"!==Object.prototype.toString.call(e))){var t=[],a=-1;for(var n in e){var r=e[n];"string"==typeof r&&(t[++a]=n,t[++a]=r)}e=t}this.paramCache_=null;for(var o=[],i="",l=0;l<e.length;){var n=e[l++],r=e[l++];o.push(i,encodeURIComponent(n.toString())),i="&",r&&o.push("=",encodeURIComponent(r.toString()))}return this.query_=o.join(""),this},s.prototype.checkParameterCache_=function(){if(!this.paramCache_){var e=this.query_;if(e){for(var t=e.split(/[&\?]/),a=[],n=-1,r=0;r<t.length;++r){var o=t[r].match(/^([^=]*)(?:=(.*))?$/);a[++n]=decodeURIComponent(o[1]).replace(/\+/g," "),a[++n]=decodeURIComponent(o[2]||"").replace(/\+/g," ")}this.paramCache_=a}else this.paramCache_=[]}},s.prototype.setParameterValues=function(e,t){"string"==typeof t&&(t=[t]),this.checkParameterCache_();for(var a=0,n=this.paramCache_,r=[],o=0;o<n.length;o+=2)e===n[o]?a<t.length&&r.push(e,t[a++]):r.push(n[o],n[o+1]);for(;a<t.length;)r.push(e,t[a++]);return this.setAllParameters(r),this},s.prototype.removeParameter=function(e){return this.setParameterValues(e,[])},s.prototype.getAllParameters=function(){return this.checkParameterCache_(),this.paramCache_.slice(0,this.paramCache_.length)},s.prototype.getParameterValues=function(e){this.checkParameterCache_();for(var t=[],a=0;a<this.paramCache_.length;a+=2)e===this.paramCache_[a]&&t.push(this.paramCache_[a+1]);return t},s.prototype.getParameterMap=function(e){this.checkParameterCache_();for(var t={},a=0;a<this.paramCache_.length;a+=2){var n=this.paramCache_[a++],r=this.paramCache_[a++];n in t?t[n].push(r):t[n]=[r]}return t},s.prototype.getParameterValue=function(e){this.checkParameterCache_();for(var t=0;t<this.paramCache_.length;t+=2)if(e===this.paramCache_[t])return this.paramCache_[t+1];return null},s.prototype.getFragment=function(){return this.fragment_&&decodeURIComponent(this.fragment_)},s.prototype.getRawFragment=function(){return this.fragment_},s.prototype.setFragment=function(e){return this.fragment_=e?encodeURIComponent(e):null,this},s.prototype.setRawFragment=function(e){return this.fragment_=e?e:null,this},s.prototype.hasFragment=function(){return null!==this.fragment_};var p=new RegExp("^(?:([^:/?#]+):)?(?://(?:([^/?#]*)@)?([^/?#:@]*)(?::([0-9]+))?)?([^?#]+)?(?:\\?([^#]*))?(?:#(.*))?$"),d=/[#\/\?@]/g,f=/[\#\?]/g;return s.parse=e,s.create=t,s.resolve=l,s.collapse_dots=i,s.utils={mimeTypeOf:function(t){var a=e(t);return/\.html$/.test(a.getPath())?"text/html":"application/javascript"},resolve:function(t,a){return t?l(e(t),e(a)).toString():""+a}},s}(),html4={};if(html4.atype={NONE:0,URI:1,URI_FRAGMENT:11,SCRIPT:2,STYLE:3,HTML:12,ID:4,IDREF:5,IDREFS:6,GLOBAL_NAME:7,LOCAL_NAME:8,CLASSES:9,FRAME_TARGET:10,MEDIA_QUERY:13},html4.atype=html4.atype,html4.ATTRIBS={"*::class":9,"*::dir":0,"*::draggable":0,"*::hidden":0,"*::id":4,"*::inert":0,"*::itemprop":0,"*::itemref":6,"*::itemscope":0,"*::lang":0,"*::onblur":2,"*::onchange":2,"*::onclick":2,"*::ondblclick":2,"*::onfocus":2,"*::onkeydown":2,"*::onkeypress":2,"*::onkeyup":2,"*::onload":2,"*::onmousedown":2,"*::onmousemove":2,"*::onmouseout":2,"*::onmouseover":2,"*::onmouseup":2,"*::onreset":2,"*::onscroll":2,"*::onselect":2,"*::onsubmit":2,"*::onunload":2,"*::spellcheck":0,"*::style":3,"*::title":0,"*::translate":0,"a::accesskey":0,"a::coords":0,"a::href":1,"a::hreflang":0,"a::name":7,"a::onblur":2,"a::onfocus":2,"a::shape":0,"a::tabindex":0,"a::target":10,"a::type":0,"area::accesskey":0,"area::alt":0,"area::coords":0,"area::href":1,"area::nohref":0,"area::onblur":2,"area::onfocus":2,"area::shape":0,"area::tabindex":0,"area::target":10,"audio::controls":0,"audio::loop":0,"audio::mediagroup":5,"audio::muted":0,"audio::preload":0,"bdo::dir":0,"blockquote::cite":1,"br::clear":0,"button::accesskey":0,"button::disabled":0,"button::name":8,"button::onblur":2,"button::onfocus":2,"button::tabindex":0,"button::type":0,"button::value":0,"canvas::height":0,"canvas::width":0,"caption::align":0,"col::align":0,"col::char":0,"col::charoff":0,"col::span":0,"col::valign":0,"col::width":0,"colgroup::align":0,"colgroup::char":0,"colgroup::charoff":0,"colgroup::span":0,"colgroup::valign":0,"colgroup::width":0,"command::checked":0,"command::command":5,"command::disabled":0,"command::icon":1,"command::label":0,"command::radiogroup":0,"command::type":0,"data::value":0,"del::cite":1,"del::datetime":0,"details::open":0,"dir::compact":0,"div::align":0,"dl::compact":0,"fieldset::disabled":0,"font::color":0,"font::face":0,"font::size":0,"form::accept":0,"form::action":1,"form::autocomplete":0,"form::enctype":0,"form::method":0,"form::name":7,"form::novalidate":0,"form::onreset":2,"form::onsubmit":2,"form::target":10,"h1::align":0,"h2::align":0,"h3::align":0,"h4::align":0,"h5::align":0,"h6::align":0,"hr::align":0,"hr::noshade":0,"hr::size":0,"hr::width":0,"iframe::align":0,"iframe::frameborder":0,"iframe::height":0,"iframe::marginheight":0,"iframe::marginwidth":0,"iframe::width":0,"img::align":0,"img::alt":0,"img::border":0,"img::height":0,"img::hspace":0,"img::ismap":0,"img::name":7,"img::src":1,"img::usemap":11,"img::vspace":0,"img::width":0,"input::accept":0,"input::accesskey":0,"input::align":0,"input::alt":0,"input::autocomplete":0,"input::checked":0,"input::disabled":0,"input::inputmode":0,"input::ismap":0,"input::list":5,"input::max":0,"input::maxlength":0,"input::min":0,"input::multiple":0,"input::name":8,"input::onblur":2,"input::onchange":2,"input::onfocus":2,"input::onselect":2,"input::placeholder":0,"input::readonly":0,"input::required":0,"input::size":0,"input::src":1,"input::step":0,"input::tabindex":0,"input::type":0,"input::usemap":11,"input::value":0,"ins::cite":1,"ins::datetime":0,"label::accesskey":0,"label::for":5,"label::onblur":2,"label::onfocus":2,"legend::accesskey":0,"legend::align":0,"li::type":0,"li::value":0,"map::name":7,"menu::compact":0,"menu::label":0,"menu::type":0,"meter::high":0,"meter::low":0,"meter::max":0,"meter::min":0,"meter::value":0,"ol::compact":0,"ol::reversed":0,"ol::start":0,"ol::type":0,"optgroup::disabled":0,"optgroup::label":0,"option::disabled":0,"option::label":0,"option::selected":0,"option::value":0,"output::for":6,"output::name":8,"p::align":0,"pre::width":0,"progress::max":0,"progress::min":0,"progress::value":0,"q::cite":1,"select::autocomplete":0,"select::disabled":0,"select::multiple":0,"select::name":8,"select::onblur":2,"select::onchange":2,"select::onfocus":2,"select::required":0,"select::size":0,"select::tabindex":0,"source::type":0,"table::align":0,"table::bgcolor":0,"table::border":0,"table::cellpadding":0,"table::cellspacing":0,"table::frame":0,"table::rules":0,"table::summary":0,"table::width":0,"tbody::align":0,"tbody::char":0,"tbody::charoff":0,"tbody::valign":0,"td::abbr":0,"td::align":0,"td::axis":0,"td::bgcolor":0,"td::char":0,"td::charoff":0,"td::colspan":0,"td::headers":6,"td::height":0,"td::nowrap":0,"td::rowspan":0,"td::scope":0,"td::valign":0,"td::width":0,"textarea::accesskey":0,"textarea::autocomplete":0,"textarea::cols":0,"textarea::disabled":0,"textarea::inputmode":0,"textarea::name":8,"textarea::onblur":2,"textarea::onchange":2,"textarea::onfocus":2,"textarea::onselect":2,"textarea::placeholder":0,"textarea::readonly":0,"textarea::required":0,"textarea::rows":0,"textarea::tabindex":0,"textarea::wrap":0,"tfoot::align":0,"tfoot::char":0,"tfoot::charoff":0,"tfoot::valign":0,"th::abbr":0,"th::align":0,"th::axis":0,"th::bgcolor":0,"th::char":0,"th::charoff":0,"th::colspan":0,"th::headers":6,"th::height":0,"th::nowrap":0,"th::rowspan":0,"th::scope":0,"th::valign":0,"th::width":0,"thead::align":0,"thead::char":0,"thead::charoff":0,"thead::valign":0,"tr::align":0,"tr::bgcolor":0,"tr::char":0,"tr::charoff":0,"tr::valign":0,"track::default":0,"track::kind":0,"track::label":0,"track::srclang":0,"ul::compact":0,"ul::type":0,"video::controls":0,"video::height":0,"video::loop":0,"video::mediagroup":5,"video::muted":0,"video::poster":1,"video::preload":0,"video::width":0},html4.ATTRIBS=html4.ATTRIBS,html4.eflags={OPTIONAL_ENDTAG:1,EMPTY:2,CDATA:4,RCDATA:8,UNSAFE:16,FOLDABLE:32,SCRIPT:64,STYLE:128,VIRTUALIZED:256},html4.eflags=html4.eflags,html4.ELEMENTS={a:0,abbr:0,acronym:0,address:0,applet:272,area:2,article:0,aside:0,audio:0,b:0,base:274,basefont:274,bdi:0,bdo:0,big:0,blockquote:0,body:305,br:2,button:0,canvas:0,caption:0,center:0,cite:0,code:0,col:2,colgroup:1,command:2,data:0,datalist:0,dd:1,del:0,details:0,dfn:0,dialog:272,dir:0,div:0,dl:0,dt:1,em:0,fieldset:0,figcaption:0,figure:0,font:0,footer:0,form:0,frame:274,frameset:272,h1:0,h2:0,h3:0,h4:0,h5:0,h6:0,head:305,header:0,hgroup:0,hr:2,html:305,i:0,iframe:16,img:2,input:2,ins:0,isindex:274,kbd:0,keygen:274,label:0,legend:0,li:1,link:274,map:0,mark:0,menu:0,meta:274,meter:0,nav:0,nobr:0,noembed:276,noframes:276,noscript:276,object:272,ol:0,optgroup:0,option:1,output:0,p:1,param:274,pre:0,progress:0,q:0,s:0,samp:0,script:84,section:0,select:0,small:0,source:2,span:0,strike:0,strong:0,style:148,sub:0,summary:0,sup:0,table:0,tbody:1,td:1,textarea:8,tfoot:1,th:1,thead:1,time:0,title:280,tr:1,track:2,tt:0,u:0,ul:0,"var":0,video:0,wbr:2},html4.ELEMENTS=html4.ELEMENTS,html4.ELEMENT_DOM_INTERFACES={a:"HTMLAnchorElement",abbr:"HTMLElement",acronym:"HTMLElement",address:"HTMLElement",applet:"HTMLAppletElement",area:"HTMLAreaElement",article:"HTMLElement",aside:"HTMLElement",audio:"HTMLAudioElement",b:"HTMLElement",base:"HTMLBaseElement",basefont:"HTMLBaseFontElement",bdi:"HTMLElement",bdo:"HTMLElement",big:"HTMLElement",blockquote:"HTMLQuoteElement",body:"HTMLBodyElement",br:"HTMLBRElement",button:"HTMLButtonElement",canvas:"HTMLCanvasElement",caption:"HTMLTableCaptionElement",center:"HTMLElement",cite:"HTMLElement",code:"HTMLElement",col:"HTMLTableColElement",colgroup:"HTMLTableColElement",command:"HTMLCommandElement",data:"HTMLElement",datalist:"HTMLDataListElement",dd:"HTMLElement",del:"HTMLModElement",details:"HTMLDetailsElement",dfn:"HTMLElement",dialog:"HTMLDialogElement",dir:"HTMLDirectoryElement",div:"HTMLDivElement",dl:"HTMLDListElement",dt:"HTMLElement",em:"HTMLElement",fieldset:"HTMLFieldSetElement",figcaption:"HTMLElement",figure:"HTMLElement",font:"HTMLFontElement",footer:"HTMLElement",form:"HTMLFormElement",frame:"HTMLFrameElement",frameset:"HTMLFrameSetElement",h1:"HTMLHeadingElement",h2:"HTMLHeadingElement",h3:"HTMLHeadingElement",h4:"HTMLHeadingElement",h5:"HTMLHeadingElement",h6:"HTMLHeadingElement",head:"HTMLHeadElement",header:"HTMLElement",hgroup:"HTMLElement",hr:"HTMLHRElement",html:"HTMLHtmlElement",i:"HTMLElement",iframe:"HTMLIFrameElement",img:"HTMLImageElement",input:"HTMLInputElement",ins:"HTMLModElement",isindex:"HTMLUnknownElement",kbd:"HTMLElement",keygen:"HTMLKeygenElement",label:"HTMLLabelElement",legend:"HTMLLegendElement",li:"HTMLLIElement",link:"HTMLLinkElement",map:"HTMLMapElement",mark:"HTMLElement",menu:"HTMLMenuElement",meta:"HTMLMetaElement",meter:"HTMLMeterElement",nav:"HTMLElement",nobr:"HTMLElement",noembed:"HTMLElement",noframes:"HTMLElement",noscript:"HTMLElement",object:"HTMLObjectElement",ol:"HTMLOListElement",optgroup:"HTMLOptGroupElement",option:"HTMLOptionElement",output:"HTMLOutputElement",p:"HTMLParagraphElement",param:"HTMLParamElement",pre:"HTMLPreElement",progress:"HTMLProgressElement",q:"HTMLQuoteElement",s:"HTMLElement",samp:"HTMLElement",script:"HTMLScriptElement",section:"HTMLElement",select:"HTMLSelectElement",small:"HTMLElement",source:"HTMLSourceElement",span:"HTMLSpanElement",strike:"HTMLElement",strong:"HTMLElement",style:"HTMLStyleElement",sub:"HTMLElement",summary:"HTMLElement",sup:"HTMLElement",table:"HTMLTableElement",tbody:"HTMLTableSectionElement",td:"HTMLTableDataCellElement",textarea:"HTMLTextAreaElement",tfoot:"HTMLTableSectionElement",th:"HTMLTableHeaderCellElement",thead:"HTMLTableSectionElement",time:"HTMLTimeElement",title:"HTMLTitleElement",tr:"HTMLTableRowElement",track:"HTMLTrackElement",tt:"HTMLElement",u:"HTMLElement",ul:"HTMLUListElement","var":"HTMLElement",video:"HTMLVideoElement",wbr:"HTMLElement"},html4.ELEMENT_DOM_INTERFACES=html4.ELEMENT_DOM_INTERFACES,html4.ueffects={NOT_LOADED:0,SAME_DOCUMENT:1,NEW_DOCUMENT:2},html4.ueffects=html4.ueffects,html4.URIEFFECTS={"a::href":2,"area::href":2,"blockquote::cite":0,"command::icon":1,"del::cite":0,"form::action":2,"img::src":1,"input::src":1,"ins::cite":0,"q::cite":0,"video::poster":1},html4.URIEFFECTS=html4.URIEFFECTS,html4.ltypes={UNSANDBOXED:2,SANDBOXED:1,DATA:0},html4.ltypes=html4.ltypes,html4.LOADERTYPES={"a::href":2,"area::href":2,"blockquote::cite":2,"command::icon":1,"del::cite":2,"form::action":2,"img::src":1,"input::src":1,"ins::cite":2,"q::cite":2,"video::poster":1},html4.LOADERTYPES=html4.LOADERTYPES,"i"!=="I".toLowerCase())throw"I/i problem";var html=function(e){function t(e){if(S.hasOwnProperty(e))return S[e];var t=e.match(P);if(t)return String.fromCharCode(parseInt(t[1],10));if(t=e.match(D))return String.fromCharCode(parseInt(t[1],16));if(I&&k.test(e)){I.innerHTML="&"+e+";";var a=I.textContent;return S[e]=a,a}return"&"+e+";"}function a(e,a){return t(a)}function n(e){return e.replace(x,"")}function r(e){return e.replace(N,a)}function o(e){return(""+e).replace(F,"&amp;").replace(B,"&lt;").replace(q,"&gt;").replace(z,"&#34;")}function i(e){return e.replace(U,"&amp;$1").replace(B,"&lt;").replace(q,"&gt;")}function l(e){var t={cdata:e.cdata||e.cdata,comment:e.comment||e.comment,endDoc:e.endDoc||e.endDoc,endTag:e.endTag||e.endTag,pcdata:e.pcdata||e.pcdata,rcdata:e.rcdata||e.rcdata,startDoc:e.startDoc||e.startDoc,startTag:e.startTag||e.startTag};return function(e,a){return s(e,t,a)}}function s(e,t,a){var n=u(e),r={noMoreGT:!1,noMoreEndComments:!1};m(t,n,0,r,a)}function c(e,t,a,n,r){return function(){m(e,t,a,n,r)}}function m(t,a,n,r,o){try{t.startDoc&&0==n&&t.startDoc(o);for(var i,l,s,m=n,u=a.length;u>m;){var f=a[m++],g=a[m];switch(f){case"&":O.test(g)?(t.pcdata&&t.pcdata("&"+g,o,Y,c(t,a,m,r,o)),m++):t.pcdata&&t.pcdata("&amp;",o,Y,c(t,a,m,r,o));break;case"</":(i=/^([-\w:]+)[^\'\"]*/.exec(g))?i[0].length===g.length&&">"===a[m+1]?(m+=2,s=i[1].toLowerCase(),t.endTag&&t.endTag(s,o,Y,c(t,a,m,r,o))):m=h(a,m,t,o,Y,r):t.pcdata&&t.pcdata("&lt;/",o,Y,c(t,a,m,r,o));break;case"<":if(i=/^([-\w:]+)\s*\/?/.exec(g))if(i[0].length===g.length&&">"===a[m+1]){m+=2,s=i[1].toLowerCase(),t.startTag&&t.startTag(s,[],o,Y,c(t,a,m,r,o));var E=e.ELEMENTS[s];if(E&j){var T={name:s,next:m,eflags:E};m=d(a,T,t,o,Y,r)}}else m=p(a,m,t,o,Y,r);else t.pcdata&&t.pcdata("&lt;",o,Y,c(t,a,m,r,o));break;case"<!--":if(!r.noMoreEndComments){for(l=m+1;u>l&&(">"!==a[l]||!/--$/.test(a[l-1]));l++);if(u>l){if(t.comment){var L=a.slice(m,l).join("");t.comment(L.substr(0,L.length-2),o,Y,c(t,a,l+1,r,o))}m=l+1}else r.noMoreEndComments=!0}r.noMoreEndComments&&t.pcdata&&t.pcdata("&lt;!--",o,Y,c(t,a,m,r,o));break;case"<!":if(/^\w/.test(g)){if(!r.noMoreGT){for(l=m+1;u>l&&">"!==a[l];l++);u>l?m=l+1:r.noMoreGT=!0}r.noMoreGT&&t.pcdata&&t.pcdata("&lt;!",o,Y,c(t,a,m,r,o))}else t.pcdata&&t.pcdata("&lt;!",o,Y,c(t,a,m,r,o));break;case"<?":if(!r.noMoreGT){for(l=m+1;u>l&&">"!==a[l];l++);u>l?m=l+1:r.noMoreGT=!0}r.noMoreGT&&t.pcdata&&t.pcdata("&lt;?",o,Y,c(t,a,m,r,o));break;case">":t.pcdata&&t.pcdata("&gt;",o,Y,c(t,a,m,r,o));break;case"":break;default:t.pcdata&&t.pcdata(f,o,Y,c(t,a,m,r,o))}}t.endDoc&&t.endDoc(o)}catch(M){if(M!==Y)throw M}}function u(e){var t=/(<\/|<\!--|<[!?]|[&<>])/g;if(e+="",$)return e.split(t);for(var a,n=[],r=0;null!==(a=t.exec(e));)n.push(e.substring(r,a.index)),n.push(a[0]),r=a.index+a[0].length;return n.push(e.substring(r)),n}function h(e,t,a,n,r,o){var i=f(e,t);return i?(a.endTag&&a.endTag(i.name,n,r,c(a,e,t,o,n)),i.next):e.length}function p(e,t,a,n,r,o){var i=f(e,t);return i?(a.startTag&&a.startTag(i.name,i.attrs,n,r,c(a,e,i.next,o,n)),i.eflags&j?d(e,i,a,n,r,o):i.next):e.length}function d(t,a,n,r,o,l){var s=t.length;Q.hasOwnProperty(a.name)||(Q[a.name]=new RegExp("^"+a.name+"(?:[\\s\\/]|$)","i"));for(var m=Q[a.name],u=a.next,h=a.next+1;s>h&&("</"!==t[h-1]||!m.test(t[h]));h++);s>h&&(h-=1);var p=t.slice(u,h).join("");if(a.eflags&e.eflags.CDATA)n.cdata&&n.cdata(p,r,o,c(n,t,h,l,r));else{if(!(a.eflags&e.eflags.RCDATA))throw new Error("bug");n.rcdata&&n.rcdata(i(p),r,o,c(n,t,h,l,r))}return h}function f(t,a){var n=/^([-\w:]+)/.exec(t[a]),r={};r.name=n[1].toLowerCase(),r.eflags=e.ELEMENTS[r.name];for(var o=t[a].substr(n[0].length),i=a+1,l=t.length;l>i&&">"!==t[i];i++)o+=t[i];if(!(i>=l)){for(var s=[];""!==o;)if(n=G.exec(o)){if(n[4]&&!n[5]||n[6]&&!n[7]){for(var c=n[4]||n[6],m=!1,u=[o,t[i++]];l>i;i++){if(m){if(">"===t[i])break}else 0<=t[i].indexOf(c)&&(m=!0);u.push(t[i])}if(i>=l)break;o=u.join("");continue}var h=n[1].toLowerCase(),p=n[2]?g(n[3]):"";s.push(h,p),o=o.substr(n[0].length)}else o=o.replace(/^[\s\S][^a-z\s]*/,"");return r.attrs=s,r.next=i+1,r}}function g(e){var t=e.charCodeAt(0);return(34===t||39===t)&&(e=e.substr(1,e.length-2)),r(n(e))}function E(t){var a,n,r=function(e,t){n||t.push(e)};return l({startDoc:function(e){a=[],n=!1},startTag:function(r,i,l){if(!n&&e.ELEMENTS.hasOwnProperty(r)){var s=e.ELEMENTS[r];if(!(s&e.eflags.FOLDABLE)){var c=t(r,i);if(!c)return void(n=!(s&e.eflags.EMPTY));if("object"!=typeof c)throw new Error("tagPolicy did not return object (old API?)");if(!("attribs"in c))throw new Error("tagPolicy gave no attribs");i=c.attribs;var m,u;if("tagName"in c?(u=c.tagName,m=e.ELEMENTS[u]):(u=r,m=s),s&e.eflags.OPTIONAL_ENDTAG){var h=a[a.length-1];!h||h.orig!==r||h.rep===u&&r===u||l.push("</",h.rep,">")}s&e.eflags.EMPTY||a.push({orig:r,rep:u}),l.push("<",u);for(var p=0,d=i.length;d>p;p+=2){var f=i[p],g=i[p+1];null!==g&&void 0!==g&&l.push(" ",f,'="',o(g),'"')}l.push(">"),s&e.eflags.EMPTY&&!(m&e.eflags.EMPTY)&&l.push("</",u,">")}}},endTag:function(t,r){if(n)return void(n=!1);if(e.ELEMENTS.hasOwnProperty(t)){var o=e.ELEMENTS[t];if(!(o&(e.eflags.EMPTY|e.eflags.FOLDABLE))){var i;if(o&e.eflags.OPTIONAL_ENDTAG)for(i=a.length;--i>=0;){var l=a[i].orig;if(l===t)break;if(!(e.ELEMENTS[l]&e.eflags.OPTIONAL_ENDTAG))return}else for(i=a.length;--i>=0&&a[i].orig!==t;);if(0>i)return;for(var s=a.length;--s>i;){var c=a[s].rep;e.ELEMENTS[c]&e.eflags.OPTIONAL_ENDTAG||r.push("</",c,">")}i<a.length&&(t=a[i].rep),a.length=i,r.push("</",t,">")}}},pcdata:r,rcdata:r,cdata:r,endDoc:function(e){for(;a.length;a.length--)e.push("</",a[a.length-1].rep,">")}})}function T(e,t,a,n,r){if(!r)return null;try{var o=URI.parse(""+e);if(o&&(!o.hasScheme()||V.test(o.getScheme()))){var i=r(o,t,a,n);return i?i.toString():null}}catch(l){return null}return null}function L(e,t,a,n,r){if(a||e(t+" removed",{change:"removed",tagName:t}),n!==r){var o="changed";n&&!r?o="removed":!n&&r&&(o="added"),e(t+"."+a+" "+o,{change:o,tagName:t,attribName:a,oldValue:n,newValue:r})}}function M(e,t,a){var n;return n=t+"::"+a,e.hasOwnProperty(n)?e[n]:(n="*::"+a,e.hasOwnProperty(n)?e[n]:void 0)}function b(t,a){return M(e.LOADERTYPES,t,a)}function y(t,a){return M(e.URIEFFECTS,t,a)}function v(t,a,n,r,o){for(var i=0;i<a.length;i+=2){var l,s=a[i],c=a[i+1],m=c,u=null;if(l=t+"::"+s,(e.ATTRIBS.hasOwnProperty(l)||(l="*::"+s,e.ATTRIBS.hasOwnProperty(l)))&&(u=e.ATTRIBS[l]),null!==u)switch(u){case e.atype.NONE:break;case e.atype.SCRIPT:c=null,o&&L(o,t,s,m,c);break;case e.atype.STYLE:if("undefined"==typeof A){c=null,o&&L(o,t,s,m,c);break}var h=[];A(c,{declaration:function(t,a){var r=t.toLowerCase(),o=C[r];o&&(R(r,o,a,n?function(t){return T(t,e.ueffects.SAME_DOCUMENT,e.ltypes.SANDBOXED,{TYPE:"CSS",CSS_PROP:r},n)}:null),h.push(t+": "+a.join(" ")))}}),c=h.length>0?h.join(" ; "):null,o&&L(o,t,s,m,c);break;case e.atype.ID:case e.atype.IDREF:case e.atype.IDREFS:case e.atype.GLOBAL_NAME:case e.atype.LOCAL_NAME:case e.atype.CLASSES:c=r?r(c):c,o&&L(o,t,s,m,c);break;case e.atype.URI:c=T(c,y(t,s),b(t,s),{TYPE:"MARKUP",XML_ATTR:s,XML_TAG:t},n),o&&L(o,t,s,m,c);break;case e.atype.URI_FRAGMENT:c&&"#"===c.charAt(0)?(c=c.substring(1),c=r?r(c):c,null!==c&&void 0!==c&&(c="#"+c)):c=null,o&&L(o,t,s,m,c);break;default:c=null,o&&L(o,t,s,m,c)}else c=null,o&&L(o,t,s,m,c);a[i+1]=c}return a}function H(t,a,n){return function(r,o){return e.ELEMENTS[r]&e.eflags.UNSAFE?void(n&&L(n,r,void 0,void 0,void 0)):{attribs:v(r,o,t,a,n)}}}function _(e,t){var a=[];return E(t)(e,a),a.join("")}function w(e,t,a,n){var r=H(t,a,n);return _(e,r)}var A,R,C;"undefined"!=typeof window&&(A=window.parseCssDeclarations,R=window.sanitizeCssProperty,C=window.cssSchema);var S={lt:"<",LT:"<",gt:">",GT:">",amp:"&",AMP:"&",quot:'"',apos:"'",nbsp:" "},P=/^#(\d+)$/,D=/^#x([0-9A-Fa-f]+)$/,k=/^[A-Za-z][A-za-z0-9]+$/,I="undefined"!=typeof window&&window.document?window.document.createElement("textarea"):null,x=/\0/g,N=/&(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/g,O=/^(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/,F=/&/g,U=/&([^a-z#]|#(?:[^0-9x]|x(?:[^0-9a-f]|$)|$)|$)/gi,B=/[<]/g,q=/>/g,z=/\"/g,G=new RegExp("^\\s*([-.:\\w]+)(?:\\s*(=)\\s*((\")[^\"]*(\"|$)|(')[^']*('|$)|(?=[a-z][-\\w]*\\s*=)|[^\"'\\s]*))?","i"),$=3==="a,b".split(/(,)/).length,j=e.eflags.CDATA|e.eflags.RCDATA,Y={},Q={},V=/^(?:https?|mailto|data)$/i,X={};return X.escapeAttrib=X.escapeAttrib=o,X.makeHtmlSanitizer=X.makeHtmlSanitizer=E,X.makeSaxParser=X.makeSaxParser=l,X.makeTagPolicy=X.makeTagPolicy=H,X.normalizeRCData=X.normalizeRCData=i,X.sanitize=X.sanitize=w,X.sanitizeAttribs=X.sanitizeAttribs=v,X.sanitizeWithPolicy=X.sanitizeWithPolicy=_,X.unescapeEntities=X.unescapeEntities=r,X}(html4),html_sanitize=html.sanitize;html4.ATTRIBS["*::style"]=0,html4.ELEMENTS.style=0,html4.ATTRIBS["a::target"]=0,html4.ELEMENTS.video=0,html4.ATTRIBS["video::src"]=0,html4.ATTRIBS["video::poster"]=0,html4.ATTRIBS["video::controls"]=0,html4.ELEMENTS.audio=0,html4.ATTRIBS["audio::src"]=0,html4.ATTRIBS["video::autoplay"]=0,html4.ATTRIBS["video::controls"]=0,"undefined"!=typeof module&&(module.exports=html_sanitize);
},{}],7:[function(require,module,exports){
module.exports={"author":"Mapbox","name":"mapbox.js","description":"mapbox javascript api","version":"2.3.0","homepage":"http://mapbox.com/","repository":{"type":"git","url":"git://github.com/mapbox/mapbox.js.git"},"main":"src/index.js","dependencies":{"corslite":"0.0.6","isarray":"0.0.1","leaflet":"0.7.7","mustache":"2.2.1","sanitize-caja":"0.1.3"},"scripts":{"test":"eslint --no-eslintrc -c .eslintrc src && mocha-phantomjs test/index.html"},"license":"BSD-3-Clause","devDependencies":{"browserify":"^6.3.2","clean-css":"~2.0.7","eslint":"^0.23.0","expect.js":"0.3.1","happen":"0.1.3","leaflet-fullscreen":"0.0.4","leaflet-hash":"0.2.1","marked":"~0.3.0","minifyify":"^6.1.0","minimist":"0.0.5","mocha":"1.17.1","mocha-phantomjs":"3.1.6","sinon":"1.10.2"},"optionalDependencies":{},"engines":{"node":"*"}}
},{}],8:[function(require,module,exports){
"use strict";module.exports={HTTP_URL:"http://a.tiles.mapbox.com/v4",HTTPS_URL:"https://a.tiles.mapbox.com/v4",FORCE_HTTPS:!1,REQUIRE_ACCESS_TOKEN:!0};
},{}],9:[function(require,module,exports){
"use strict";var util=require("./util"),format_url=require("./format_url"),request=require("./request"),marker=require("./marker"),simplestyle=require("./simplestyle"),FeatureLayer=L.FeatureGroup.extend({options:{filter:function(){return!0},sanitizer:require("sanitize-caja"),style:simplestyle.style,popupOptions:{closeButton:!1}},initialize:function(e,t){L.setOptions(this,t),this._layers={},"string"==typeof e?util.idUrl(e,this):e&&"object"==typeof e&&this.setGeoJSON(e)},setGeoJSON:function(e){return this._geojson=e,this.clearLayers(),this._initialize(e),this},getGeoJSON:function(){return this._geojson},loadURL:function(e){return this._request&&"abort"in this._request&&this._request.abort(),this._request=request(e,L.bind(function(t,i){this._request=null,t&&"abort"!==t.type?(util.log("could not load features at "+e),this.fire("error",{error:t})):i&&(this.setGeoJSON(i),this.fire("ready"))},this)),this},loadID:function(e){return this.loadURL(format_url("/v4/"+e+"/features.json",this.options.accessToken))},setFilter:function(e){return this.options.filter=e,this._geojson&&(this.clearLayers(),this._initialize(this._geojson)),this},getFilter:function(){return this.options.filter},_initialize:function(e){var t,i,r=L.Util.isArray(e)?e:e.features;if(r)for(t=0,i=r.length;i>t;t++)(r[t].geometries||r[t].geometry||r[t].features)&&this._initialize(r[t]);else if(this.options.filter(e)){var s={accessToken:this.options.accessToken},o=this.options.pointToLayer||function(e,t){return marker.style(e,t,s)},n=L.GeoJSON.geometryToLayer(e,o),u=marker.createPopup(e,this.options.sanitizer),a=this.options.style,l=a===simplestyle.style;!(a&&"setStyle"in n)||l&&(n instanceof L.Circle||n instanceof L.CircleMarker)||("function"==typeof a&&(a=a(e)),n.setStyle(a)),n.feature=e,u&&n.bindPopup(u,this.options.popupOptions),this.addLayer(n)}}});module.exports.FeatureLayer=FeatureLayer,module.exports.featureLayer=function(e,t){return new FeatureLayer(e,t)};
},{"./format_url":11,"./marker":25,"./request":26,"./simplestyle":28,"./util":31,"sanitize-caja":5}],10:[function(require,module,exports){
"use strict";var Feedback=L.Class.extend({includes:L.Mixin.Events,data:{},record:function(e){L.extend(this.data,e),this.fire("change")}});module.exports=new Feedback;
},{}],11:[function(require,module,exports){
"use strict";var config=require("./config"),version=require("../package.json").version;module.exports=function(e,o){if(o=o||L.mapbox.accessToken,!o&&config.REQUIRE_ACCESS_TOKEN)throw new Error("An API access token is required to use Mapbox.js. See https://www.mapbox.com/mapbox.js/api/v"+version+"/api-access-tokens/");var s="https:"===document.location.protocol||config.FORCE_HTTPS?config.HTTPS_URL:config.HTTP_URL;if(s=s.replace(/\/v4$/,""),s+=e,config.REQUIRE_ACCESS_TOKEN){if("s"===o[0])throw new Error("Use a public access token (pk.*) with Mapbox.js, not a secret access token (sk.*). See https://www.mapbox.com/mapbox.js/api/v"+version+"/api-access-tokens/");s+=-1!==s.indexOf("?")?"&access_token=":"?access_token=",s+=o}return s},module.exports.tileJSON=function(e,o){if(-1!==e.indexOf("/"))return e;var s=module.exports("/v4/"+e+".json",o);return 0===s.indexOf("https")&&(s+="&secure"),s},module.exports.style=function(e,o){if(-1===e.indexOf("mapbox://styles/"))throw new Error("Incorrectly formatted Mapbox style at "+e);var s=e.split("mapbox://styles/")[1],t=module.exports("/styles/v1/"+s,o).replace("http://","https://");return t};
},{"../package.json":7,"./config":8}],12:[function(require,module,exports){
"use strict";var isArray=require("isarray"),util=require("./util"),format_url=require("./format_url"),feedback=require("./feedback"),request=require("./request");module.exports=function(e,r){function t(e,r){var t=Math.pow(10,r);return e.lat=Math.round(e.lat*t)/t,e.lng=Math.round(e.lng*t)/t,e}r||(r={});var n={};return util.strict(e,"string"),-1===e.indexOf("/")&&(e=format_url("/geocoding/v5/"+e+"/{query}.json",r.accessToken,5)),n.getURL=function(){return e},n.queryURL=function(e){var r=!(isArray(e)||"string"==typeof e),u=r?e.query:e;if(isArray(u)){for(var o=[],i=0;i<u.length;i++)o[i]=encodeURIComponent(u[i]);u=o.join(";")}else u=encodeURIComponent(u);feedback.record({geocoding:u});var a=L.Util.template(n.getURL(),{query:u});if(r&&e.types&&(a+=isArray(e.types)?"&types="+e.types.join():"&types="+e.types),r&&e.proximity){var l=t(L.latLng(e.proximity),3);a+="&proximity="+l.lng+","+l.lat}return a},n.query=function(e,r){return util.strict(r,"function"),request(n.queryURL(e),function(e,t){if(t&&(t.length||t.features)){var n={results:t};t.features&&t.features.length&&(n.latlng=[t.features[0].center[1],t.features[0].center[0]],t.features[0].bbox&&(n.bounds=t.features[0].bbox,n.lbounds=util.lbounds(n.bounds))),r(null,n)}else r(e||!0)}),n},n.reverseQuery=function(e,r){function u(e){var r;return r=void 0!==e.lat&&void 0!==e.lng?L.latLng(e.lat,e.lng):void 0!==e.lat&&void 0!==e.lon?L.latLng(e.lat,e.lon):L.latLng(e[1],e[0]),r=t(r,5),r.lng+","+r.lat}var o="";if(e.length&&e[0].length){for(var i=0,a=[];i<e.length;i++)a.push(u(e[i]));o=a.join(";")}else o=u(e);return request(n.queryURL(o),function(e,t){r(e,t)}),n},n};
},{"./feedback":10,"./format_url":11,"./request":26,"./util":31,"isarray":2}],13:[function(require,module,exports){
"use strict";var geocoder=require("./geocoder"),util=require("./util"),GeocoderControl=L.Control.extend({includes:L.Mixin.Events,options:{proximity:!0,position:"topleft",pointZoom:16,keepOpen:!1,autocomplete:!1},initialize:function(t,e){L.Util.setOptions(this,e),this.setURL(t),this._updateSubmit=L.bind(this._updateSubmit,this),this._updateAutocomplete=L.bind(this._updateAutocomplete,this),this._chooseResult=L.bind(this._chooseResult,this)},setURL:function(t){return this.geocoder=geocoder(t,{accessToken:this.options.accessToken}),this},getURL:function(){return this.geocoder.getURL()},setID:function(t){return this.setURL(t)},setTileJSON:function(t){return this.setURL(t.geocoder)},_toggle:function(t){t&&L.DomEvent.stop(t),L.DomUtil.hasClass(this._container,"active")?(L.DomUtil.removeClass(this._container,"active"),this._results.innerHTML="",this._input.blur()):(L.DomUtil.addClass(this._container,"active"),this._input.focus(),this._input.select())},_closeIfOpen:function(){L.DomUtil.hasClass(this._container,"active")&&!this.options.keepOpen&&(L.DomUtil.removeClass(this._container,"active"),this._results.innerHTML="",this._input.blur())},onAdd:function(t){var e=L.DomUtil.create("div","leaflet-control-mapbox-geocoder leaflet-bar leaflet-control"),i=L.DomUtil.create("a","leaflet-control-mapbox-geocoder-toggle mapbox-icon mapbox-icon-geocoder",e),o=L.DomUtil.create("div","leaflet-control-mapbox-geocoder-results",e),s=L.DomUtil.create("div","leaflet-control-mapbox-geocoder-wrap",e),n=L.DomUtil.create("form","leaflet-control-mapbox-geocoder-form",s),r=L.DomUtil.create("input","",n);return i.href="#",i.innerHTML="&nbsp;",r.type="text",r.setAttribute("placeholder","Search"),L.DomEvent.addListener(n,"submit",this._geocode,this),L.DomEvent.addListener(r,"keyup",this._autocomplete,this),L.DomEvent.disableClickPropagation(e),this._map=t,this._results=o,this._input=r,this._form=n,this.options.keepOpen?L.DomUtil.addClass(e,"active"):(this._map.on("click",this._closeIfOpen,this),L.DomEvent.addListener(i,"click",this._toggle,this)),e},_updateSubmit:function(t,e){if(L.DomUtil.removeClass(this._container,"searching"),this._results.innerHTML="",t||!e)this.fire("error",{error:t});else{var i=[];e.results&&e.results.features&&(i=e.results.features),1===i.length?(this.fire("autoselect",{feature:i[0]}),this.fire("found",{results:e.results}),this._chooseResult(i[0]),this._closeIfOpen()):i.length>1?(this.fire("found",{results:e.results}),this._displayResults(i)):this._displayResults(i)}},_updateAutocomplete:function(t,e){if(this._results.innerHTML="",t||!e)this.fire("error",{error:t});else{var i=[];e.results&&e.results.features&&(i=e.results.features),i.length&&this.fire("found",{results:e.results}),this._displayResults(i)}},_displayResults:function(t){for(var e=0,i=Math.min(t.length,5);i>e;e++){var o=t[e],s=o.place_name;if(s.length){var n=L.DomUtil.create("a","",this._results),r="innerText"in n?"innerText":"textContent";n[r]=s,n.setAttribute("title",s),n.href="#",L.bind(function(t){L.DomEvent.addListener(n,"click",function(e){this._chooseResult(t),L.DomEvent.stop(e),this.fire("select",{feature:t})},this)},this)(o)}}if(t.length>5){var l=L.DomUtil.create("span","",this._results);l.innerHTML="Top 5 of "+t.length+"  results"}},_chooseResult:function(t){t.bbox?this._map.fitBounds(util.lbounds(t.bbox)):t.center&&this._map.setView([t.center[1],t.center[0]],void 0===this._map.getZoom()?this.options.pointZoom:Math.max(this._map.getZoom(),this.options.pointZoom))},_geocode:function(t){return L.DomEvent.preventDefault(t),""===this._input.value?this._updateSubmit():(L.DomUtil.addClass(this._container,"searching"),void this.geocoder.query({query:this._input.value,proximity:this.options.proximity?this._map.getCenter():!1},this._updateSubmit))},_autocomplete:function(){return this.options.autocomplete?""===this._input.value?this._updateAutocomplete():void this.geocoder.query({query:this._input.value,proximity:this.options.proximity?this._map.getCenter():!1},this._updateAutocomplete):void 0}});module.exports.GeocoderControl=GeocoderControl,module.exports.geocoderControl=function(t,e){return new GeocoderControl(t,e)};
},{"./geocoder":12,"./util":31}],14:[function(require,module,exports){
"use strict";function utfDecode(t){return t>=93&&t--,t>=35&&t--,t-32}module.exports=function(t){return function(e,r){if(t){var u=utfDecode(t.grid[r].charCodeAt(e)),n=t.keys[u];return t.data[n]}}};
},{}],15:[function(require,module,exports){
"use strict";var util=require("./util"),Mustache=require("mustache"),GridControl=L.Control.extend({options:{pinnable:!0,follow:!1,sanitizer:require("sanitize-caja"),touchTeaser:!0,location:!0},_currentContent:"",_pinned:!1,initialize:function(t,o){L.Util.setOptions(this,o),util.strict_instance(t,L.Class,"L.mapbox.gridLayer"),this._layer=t},setTemplate:function(t){return util.strict(t,"string"),this.options.template=t,this},_template:function(t,o){if(o){var i=this.options.template||this._layer.getTileJSON().template;if(i){var e={};return e["__"+t+"__"]=!0,this.options.sanitizer(Mustache.to_html(i,L.extend(e,o)))}}},_show:function(t,o){t!==this._currentContent&&(this._currentContent=t,this.options.follow?(this._popup.setContent(t).setLatLng(o.latLng),this._map._popup!==this._popup&&this._popup.openOn(this._map)):(this._container.style.display="block",this._contentWrapper.innerHTML=t))},hide:function(){return this._pinned=!1,this._currentContent="",this._map.closePopup(),this._container.style.display="none",this._contentWrapper.innerHTML="",L.DomUtil.removeClass(this._container,"closable"),this},_mouseover:function(t){if(t.data?L.DomUtil.addClass(this._map._container,"map-clickable"):L.DomUtil.removeClass(this._map._container,"map-clickable"),!this._pinned){var o=this._template("teaser",t.data);o?this._show(o,t):this.hide()}},_mousemove:function(t){this._pinned||this.options.follow&&this._popup.setLatLng(t.latLng)},_navigateTo:function(t){window.top.location.href=t},_click:function(t){var o=this._template("location",t.data);if(this.options.location&&o&&0===o.search(/^https?:/))return this._navigateTo(this._template("location",t.data));if(this.options.pinnable){var i=this._template("full",t.data);!i&&this.options.touchTeaser&&L.Browser.touch&&(i=this._template("teaser",t.data)),i?(L.DomUtil.addClass(this._container,"closable"),this._pinned=!0,this._show(i,t)):this._pinned&&(L.DomUtil.removeClass(this._container,"closable"),this._pinned=!1,this.hide())}},_onPopupClose:function(){this._currentContent=null,this._pinned=!1},_createClosebutton:function(t,o){var i=L.DomUtil.create("a","close",t);return i.innerHTML="close",i.href="#",i.title="close",L.DomEvent.on(i,"click",L.DomEvent.stopPropagation).on(i,"mousedown",L.DomEvent.stopPropagation).on(i,"dblclick",L.DomEvent.stopPropagation).on(i,"click",L.DomEvent.preventDefault).on(i,"click",o,this),i},onAdd:function(t){this._map=t;var o="leaflet-control-grid map-tooltip",i=L.DomUtil.create("div",o),e=L.DomUtil.create("div","map-tooltip-content");return i.style.display="none",this._createClosebutton(i,this.hide),i.appendChild(e),this._contentWrapper=e,this._popup=new L.Popup({autoPan:!1,closeOnClick:!1}),t.on("popupclose",this._onPopupClose,this),L.DomEvent.disableClickPropagation(i).addListener(i,"mousewheel",L.DomEvent.stopPropagation),this._layer.on("mouseover",this._mouseover,this).on("mousemove",this._mousemove,this).on("click",this._click,this),i},onRemove:function(t){t.off("popupclose",this._onPopupClose,this),this._layer.off("mouseover",this._mouseover,this).off("mousemove",this._mousemove,this).off("click",this._click,this)}});module.exports.GridControl=GridControl,module.exports.gridControl=function(t,o){return new GridControl(t,o)};
},{"./util":31,"mustache":4,"sanitize-caja":5}],16:[function(require,module,exports){
"use strict";var util=require("./util"),request=require("./request"),grid=require("./grid"),GridLayer=L.Class.extend({includes:[L.Mixin.Events,require("./load_tilejson")],options:{template:function(){return""}},_mouseOn:null,_tilejson:{},_cache:{},initialize:function(t,i){L.Util.setOptions(this,i),this._loadTileJSON(t)},_setTileJSON:function(t){return util.strict(t,"object"),L.extend(this.options,{grids:t.grids,minZoom:t.minzoom,maxZoom:t.maxzoom,bounds:t.bounds&&util.lbounds(t.bounds)}),this._tilejson=t,this._cache={},this._update(),this},getTileJSON:function(){return this._tilejson},active:function(){return!!(this._map&&this.options.grids&&this.options.grids.length)},addTo:function(t){return t.addLayer(this),this},onAdd:function(t){this._map=t,this._update(),this._map.on("click",this._click,this).on("mousemove",this._move,this).on("moveend",this._update,this)},onRemove:function(){this._map.off("click",this._click,this).off("mousemove",this._move,this).off("moveend",this._update,this)},getData:function(t,i){if(this.active()){var e=this._map,o=e.project(t.wrap()),s=256,n=4,a=Math.floor(o.x/s),h=Math.floor(o.y/s),r=e.options.crs.scale(e.getZoom())/s;return a=(a+r)%r,h=(h+r)%r,this._getTile(e.getZoom(),a,h,function(t){var e=Math.floor((o.x-a*s)/n),r=Math.floor((o.y-h*s)/n);i(t(e,r))}),this}},_click:function(t){this.getData(t.latlng,L.bind(function(i){this.fire("click",{latLng:t.latlng,data:i})},this))},_move:function(t){this.getData(t.latlng,L.bind(function(i){i!==this._mouseOn?(this._mouseOn&&this.fire("mouseout",{latLng:t.latlng,data:this._mouseOn}),this.fire("mouseover",{latLng:t.latlng,data:i}),this._mouseOn=i):this.fire("mousemove",{latLng:t.latlng,data:i})},this))},_getTileURL:function(t){var i=this.options.grids,e=(t.x+t.y)%i.length,o=i[e];return L.Util.template(o,t)},_update:function(){if(this.active()){var t=this._map.getPixelBounds(),i=this._map.getZoom(),e=256;if(!(i>this.options.maxZoom||i<this.options.minZoom))for(var o=L.bounds(t.min.divideBy(e)._floor(),t.max.divideBy(e)._floor()),s=this._map.options.crs.scale(i)/e,n=o.min.x;n<=o.max.x;n++)for(var a=o.min.y;a<=o.max.y;a++)this._getTile(i,(n%s+s)%s,(a%s+s)%s)}},_getTile:function(t,i,e,o){var s=t+"_"+i+"_"+e,n=L.point(i,e);if(n.z=t,this._tileShouldBeLoaded(n)){if(s in this._cache){if(!o)return;return void("function"==typeof this._cache[s]?o(this._cache[s]):this._cache[s].push(o))}this._cache[s]=[],o&&this._cache[s].push(o),request(this._getTileURL(n),L.bind(function(t,i){var e=this._cache[s];this._cache[s]=grid(i);for(var o=0;o<e.length;++o)e[o](this._cache[s])},this))}},_tileShouldBeLoaded:function(t){if(t.z>this.options.maxZoom||t.z<this.options.minZoom)return!1;if(this.options.bounds){var i=256,e=t.multiplyBy(i),o=e.add(new L.Point(i,i)),s=this._map.unproject(e),n=this._map.unproject(o),a=new L.LatLngBounds([s,n]);if(!this.options.bounds.intersects(a))return!1}return!0}});module.exports.GridLayer=GridLayer,module.exports.gridLayer=function(t,i){return new GridLayer(t,i)};
},{"./grid":14,"./load_tilejson":21,"./request":26,"./util":31}],17:[function(require,module,exports){
"use strict";var leaflet=require("./leaflet");require("./mapbox"),module.exports=leaflet;
},{"./leaflet":19,"./mapbox":23}],18:[function(require,module,exports){
"use strict";var InfoControl=L.Control.extend({options:{position:"bottomright",sanitizer:require("sanitize-caja")},initialize:function(t){L.setOptions(this,t),this._info={},console.warn("infoControl has been deprecated and will be removed in mapbox.js v3.0.0. Use the default attribution control instead, which is now responsive.")},onAdd:function(t){this._container=L.DomUtil.create("div","mapbox-control-info mapbox-small"),this._content=L.DomUtil.create("div","map-info-container",this._container);var i=L.DomUtil.create("a","mapbox-info-toggle mapbox-icon mapbox-icon-info",this._container);i.href="#",L.DomEvent.addListener(i,"click",this._showInfo,this),L.DomEvent.disableClickPropagation(this._container);for(var n in t._layers)t._layers[n].getAttribution&&this.addInfo(t._layers[n].getAttribution());return t.on("layeradd",this._onLayerAdd,this).on("layerremove",this._onLayerRemove,this),this._update(),this._container},onRemove:function(t){t.off("layeradd",this._onLayerAdd,this).off("layerremove",this._onLayerRemove,this)},addInfo:function(t){return t?(this._info[t]||(this._info[t]=0),this._info[t]=!0,this._update()):this},removeInfo:function(t){return t?(this._info[t]&&(this._info[t]=!1),this._update()):this},_showInfo:function(t){return L.DomEvent.preventDefault(t),this._active===!0?this._hidecontent():(L.DomUtil.addClass(this._container,"active"),this._active=!0,void this._update())},_hidecontent:function(){this._content.innerHTML="",this._active=!1,L.DomUtil.removeClass(this._container,"active")},_update:function(){if(!this._map)return this;this._content.innerHTML="";var t="none",i=[];for(var n in this._info)this._info.hasOwnProperty(n)&&this._info[n]&&(i.push(this.options.sanitizer(n)),t="block");return this._content.innerHTML+=i.join(" | "),this._container.style.display=t,this},_onLayerAdd:function(t){t.layer.getAttribution&&t.layer.getAttribution()?this.addInfo(t.layer.getAttribution()):"on"in t.layer&&t.layer.getAttribution&&t.layer.on("ready",L.bind(function(){this.addInfo(t.layer.getAttribution())},this))},_onLayerRemove:function(t){t.layer.getAttribution&&this.removeInfo(t.layer.getAttribution())}});module.exports.InfoControl=InfoControl,module.exports.infoControl=function(t){return new InfoControl(t)};
},{"sanitize-caja":5}],19:[function(require,module,exports){
module.exports=window.L=require("leaflet/dist/leaflet-src");
},{"leaflet/dist/leaflet-src":3}],20:[function(require,module,exports){
"use strict";var LegendControl=L.Control.extend({options:{position:"bottomright",sanitizer:require("sanitize-caja")},initialize:function(e){L.setOptions(this,e),this._legends={}},onAdd:function(){return this._container=L.DomUtil.create("div","map-legends wax-legends"),L.DomEvent.disableClickPropagation(this._container),this._update(),this._container},addLegend:function(e){return e?(this._legends[e]||(this._legends[e]=0),this._legends[e]++,this._update()):this},removeLegend:function(e){return e?(this._legends[e]&&this._legends[e]--,this._update()):this},_update:function(){if(!this._map)return this;this._container.innerHTML="";var e="none";for(var t in this._legends)if(this._legends.hasOwnProperty(t)&&this._legends[t]){var n=L.DomUtil.create("div","map-legend wax-legend",this._container);n.innerHTML=this.options.sanitizer(t),e="block"}return this._container.style.display=e,this}});module.exports.LegendControl=LegendControl,module.exports.legendControl=function(e){return new LegendControl(e)};
},{"sanitize-caja":5}],21:[function(require,module,exports){
"use strict";var request=require("./request"),format_url=require("./format_url"),util=require("./util");module.exports={_loadTileJSON:function(e){"string"==typeof e?(e=format_url.tileJSON(e,this.options&&this.options.accessToken),request(e,L.bind(function(t,r){t?(util.log("could not load TileJSON at "+e),this.fire("error",{error:t})):r&&(this._setTileJSON(r),this.fire("ready"))},this))):e&&"object"==typeof e&&this._setTileJSON(e)}};
},{"./format_url":11,"./request":26,"./util":31}],22:[function(require,module,exports){
"use strict";function withAccessToken(t,o){return!o||t.accessToken?t:L.extend({accessToken:o},t)}var tileLayer=require("./tile_layer").tileLayer,featureLayer=require("./feature_layer").featureLayer,gridLayer=require("./grid_layer").gridLayer,gridControl=require("./grid_control").gridControl,infoControl=require("./info_control").infoControl,shareControl=require("./share_control").shareControl,legendControl=require("./legend_control").legendControl,mapboxLogoControl=require("./mapbox_logo").mapboxLogoControl,feedback=require("./feedback"),LMap=L.Map.extend({includes:[require("./load_tilejson")],options:{tileLayer:{},featureLayer:{},gridLayer:{},legendControl:{},gridControl:{},infoControl:!1,shareControl:!1,sanitizer:require("sanitize-caja")},_tilejson:{},initialize:function(t,o,e){if(L.Map.prototype.initialize.call(this,t,L.extend({},L.Map.prototype.options,e)),this.attributionControl){this.attributionControl.setPrefix("");var i=this.options.attributionControl.compact;(i||i!==!1&&this._container.offsetWidth<=640)&&L.DomUtil.addClass(this.attributionControl._container,"leaflet-compact-attribution"),void 0===i&&this.on("resize",function(){this._container.offsetWidth>640?L.DomUtil.removeClass(this.attributionControl._container,"leaflet-compact-attribution"):L.DomUtil.addClass(this.attributionControl._container,"leaflet-compact-attribution")})}this.options.tileLayer&&(this.tileLayer=tileLayer(void 0,withAccessToken(this.options.tileLayer,this.options.accessToken)),this.addLayer(this.tileLayer)),this.options.featureLayer&&(this.featureLayer=featureLayer(void 0,withAccessToken(this.options.featureLayer,this.options.accessToken)),this.addLayer(this.featureLayer)),this.options.gridLayer&&(this.gridLayer=gridLayer(void 0,withAccessToken(this.options.gridLayer,this.options.accessToken)),this.addLayer(this.gridLayer)),this.options.gridLayer&&this.options.gridControl&&(this.gridControl=gridControl(this.gridLayer,this.options.gridControl),this.addControl(this.gridControl)),this.options.infoControl&&(this.infoControl=infoControl(this.options.infoControl),this.addControl(this.infoControl)),this.options.legendControl&&(this.legendControl=legendControl(this.options.legendControl),this.addControl(this.legendControl)),this.options.shareControl&&(this.shareControl=shareControl(void 0,withAccessToken(this.options.shareControl,this.options.accessToken)),this.addControl(this.shareControl)),this._mapboxLogoControl=mapboxLogoControl(this.options.mapboxLogoControl),this.addControl(this._mapboxLogoControl),this._loadTileJSON(o),this.on("layeradd",this._onLayerAdd,this).on("layerremove",this._onLayerRemove,this).on("moveend",this._updateMapFeedbackLink,this),this.whenReady(function(){feedback.on("change",this._updateMapFeedbackLink,this)}),this.on("unload",function(){feedback.off("change",this._updateMapFeedbackLink,this)})},_setTileJSON:function(t){return this._tilejson=t,this._initialize(t),this},getTileJSON:function(){return this._tilejson},_initialize:function(t){if(this.tileLayer&&(this.tileLayer._setTileJSON(t),this._updateLayer(this.tileLayer)),this.featureLayer&&!this.featureLayer.getGeoJSON()&&t.data&&t.data[0]&&this.featureLayer.loadURL(t.data[0]),this.gridLayer&&(this.gridLayer._setTileJSON(t),this._updateLayer(this.gridLayer)),this.infoControl&&t.attribution&&(this.infoControl.addInfo(this.options.sanitizer(t.attribution)),this._updateMapFeedbackLink()),this.legendControl&&t.legend&&this.legendControl.addLegend(t.legend),this.shareControl&&this.shareControl._setTileJSON(t),this._mapboxLogoControl._setTileJSON(t),!this._loaded&&t.center){var o=void 0!==this.getZoom()?this.getZoom():t.center[2],e=L.latLng(t.center[1],t.center[0]);this.setView(e,o)}},_updateMapFeedbackLink:function(){if(this._controlContainer.getElementsByClassName){var t=this._controlContainer.getElementsByClassName("mapbox-improve-map");if(t.length&&this._loaded){var o=this.getCenter().wrap(),e=this._tilejson||{},i=e.id||"",n="#"+i+"/"+o.lng.toFixed(3)+"/"+o.lat.toFixed(3)+"/"+this.getZoom();for(var r in feedback.data)n+="/"+r+"="+feedback.data[r];for(var a=0;a<t.length;a++)t[a].hash=n}}},_onLayerAdd:function(t){"on"in t.layer&&t.layer.on("ready",this._onLayerReady,this),window.setTimeout(L.bind(this._updateMapFeedbackLink,this),0)},_onLayerRemove:function(t){"on"in t.layer&&t.layer.off("ready",this._onLayerReady,this),window.setTimeout(L.bind(this._updateMapFeedbackLink,this),0)},_onLayerReady:function(t){this._updateLayer(t.target)},_updateLayer:function(t){t.options&&(this.infoControl&&this._loaded&&this.infoControl.addInfo(t.options.infoControl),this.attributionControl&&this._loaded&&t.getAttribution&&this.attributionControl.addAttribution(t.getAttribution()),L.stamp(t)in this._zoomBoundLayers||!t.options.maxZoom&&!t.options.minZoom||(this._zoomBoundLayers[L.stamp(t)]=t),this._updateMapFeedbackLink(),this._updateZoomLevels())}});module.exports.Map=LMap,module.exports.map=function(t,o,e){return new LMap(t,o,e)};
},{"./feature_layer":9,"./feedback":10,"./grid_control":15,"./grid_layer":16,"./info_control":18,"./legend_control":20,"./load_tilejson":21,"./mapbox_logo":24,"./share_control":27,"./tile_layer":30,"sanitize-caja":5}],23:[function(require,module,exports){
"use strict";var geocoderControl=require("./geocoder_control"),gridControl=require("./grid_control"),featureLayer=require("./feature_layer"),legendControl=require("./legend_control"),shareControl=require("./share_control"),tileLayer=require("./tile_layer"),infoControl=require("./info_control"),map=require("./map"),gridLayer=require("./grid_layer"),styleLayer=require("./style_layer");L.mapbox=module.exports={VERSION:require("../package.json").version,geocoder:require("./geocoder"),marker:require("./marker"),simplestyle:require("./simplestyle"),tileLayer:tileLayer.tileLayer,TileLayer:tileLayer.TileLayer,styleLayer:styleLayer.styleLayer,StyleLayer:styleLayer.StyleLayer,infoControl:infoControl.infoControl,InfoControl:infoControl.InfoControl,shareControl:shareControl.shareControl,ShareControl:shareControl.ShareControl,legendControl:legendControl.legendControl,LegendControl:legendControl.LegendControl,geocoderControl:geocoderControl.geocoderControl,GeocoderControl:geocoderControl.GeocoderControl,gridControl:gridControl.gridControl,GridControl:gridControl.GridControl,gridLayer:gridLayer.gridLayer,GridLayer:gridLayer.GridLayer,featureLayer:featureLayer.featureLayer,FeatureLayer:featureLayer.FeatureLayer,map:map.map,Map:map.Map,config:require("./config"),sanitize:require("sanitize-caja"),template:require("mustache").to_html,feedback:require("./feedback")},window.L.Icon.Default.imagePath=("https:"===document.location.protocol||"http:"===document.location.protocol?"":"https:")+"//api.tiles.mapbox.com/mapbox.js/v"+require("../package.json").version+"/images";
},{"../package.json":7,"./config":8,"./feature_layer":9,"./feedback":10,"./geocoder":12,"./geocoder_control":13,"./grid_control":15,"./grid_layer":16,"./info_control":18,"./legend_control":20,"./map":22,"./marker":25,"./share_control":27,"./simplestyle":28,"./style_layer":29,"./tile_layer":30,"mustache":4,"sanitize-caja":5}],24:[function(require,module,exports){
"use strict";var MapboxLogoControl=L.Control.extend({options:{position:"bottomleft"},initialize:function(o){L.setOptions(this,o)},onAdd:function(){return this._container=L.DomUtil.create("div","mapbox-logo"),this._container},_setTileJSON:function(o){o.mapbox_logo&&L.DomUtil.addClass(this._container,"mapbox-logo-true")}});module.exports.MapboxLogoControl=MapboxLogoControl,module.exports.mapboxLogoControl=function(o){return new MapboxLogoControl(o)};
},{}],25:[function(require,module,exports){
"use strict";function icon(r,e){r=r||{};var i={small:[20,50],medium:[30,70],large:[35,90]},t=r["marker-size"]||"medium",o="marker-symbol"in r&&""!==r["marker-symbol"]?"-"+r["marker-symbol"]:"",s=(r["marker-color"]||"7e7e7e").replace("#","");return L.icon({iconUrl:format_url("/v4/marker/pin-"+t.charAt(0)+o+"+"+s+(L.Browser.retina?"@2x":"")+".png",e&&e.accessToken),iconSize:i[t],iconAnchor:[i[t][0]/2,i[t][1]/2],popupAnchor:[0,-i[t][1]/2]})}function style(r,e,i){return L.marker(e,{icon:icon(r.properties,i),title:util.strip_tags(sanitize(r.properties&&r.properties.title||""))})}function createPopup(r,e){if(!r||!r.properties)return"";var i="";return r.properties.title&&(i+='<div class="marker-title">'+r.properties.title+"</div>"),r.properties.description&&(i+='<div class="marker-description">'+r.properties.description+"</div>"),(e||sanitize)(i)}var format_url=require("./format_url"),util=require("./util"),sanitize=require("sanitize-caja");module.exports={icon:icon,style:style,createPopup:createPopup};
},{"./format_url":11,"./util":31,"sanitize-caja":5}],26:[function(require,module,exports){
"use strict";var corslite=require("corslite"),strict=require("./util").strict,config=require("./config"),protocol=/^(https?:)?(?=\/\/(.|api)\.tiles\.mapbox\.com\/)/;module.exports=function(t,o){function r(t,r){!t&&r&&(r=JSON.parse(r.responseText)),o(t,r)}return strict(t,"string"),strict(o,"function"),t=t.replace(protocol,function(t,o){return"withCredentials"in new window.XMLHttpRequest?"https:"===o||"https:"===document.location.protocol||config.FORCE_HTTPS?"https:":"http:":document.location.protocol}),corslite(t,r)};
},{"./config":8,"./util":31,"corslite":1}],27:[function(require,module,exports){
"use strict";var format_url=require("./format_url"),ShareControl=L.Control.extend({includes:[require("./load_tilejson")],options:{position:"topleft",url:""},initialize:function(t,e){L.setOptions(this,e),this._loadTileJSON(t)},_setTileJSON:function(t){this._tilejson=t},onAdd:function(t){this._map=t;var e=L.DomUtil.create("div","leaflet-control-mapbox-share leaflet-bar"),o=L.DomUtil.create("a","mapbox-share mapbox-icon mapbox-icon-share",e);return o.href="#",this._modal=L.DomUtil.create("div","mapbox-modal",this._map._container),this._mask=L.DomUtil.create("div","mapbox-modal-mask",this._modal),this._content=L.DomUtil.create("div","mapbox-modal-content",this._modal),L.DomEvent.addListener(o,"click",this._shareClick,this),L.DomEvent.disableClickPropagation(e),this._map.on("mousedown",this._clickOut,this),e},_clickOut:function(t){return this._sharing?(L.DomEvent.preventDefault(t),L.DomUtil.removeClass(this._modal,"active"),this._content.innerHTML="",void(this._sharing=null)):void 0},_shareClick:function(t){function e(t,e,o){var i=document.createElement("a");return i.setAttribute("class",t),i.setAttribute("href",e),i.setAttribute("target","_blank"),o=document.createTextNode(o),i.appendChild(o),i}if(L.DomEvent.stop(t),this._sharing)return this._clickOut(t);var o=this._tilejson||this._map._tilejson||{},i=encodeURIComponent(this.options.url||o.webpage||window.location),a=encodeURIComponent(o.name),n=format_url("/v4/"+o.id+"/"+this._map.getCenter().lng+","+this._map.getCenter().lat+","+this._map.getZoom()+"/600x600.png",this.options.accessToken),r=format_url("/v4/"+o.id+".html",this.options.accessToken),s="//twitter.com/intent/tweet?status="+a+" "+i,l="//www.facebook.com/sharer.php?u="+i+"&t="+a,m="//www.pinterest.com/pin/create/button/?url="+i+"&media="+n+"&description="+a,c='<iframe width="100%" height="500px" frameBorder="0" src="'+r+'"></iframe>',h="Copy and paste this <strong>HTML code</strong> into documents to embed this map on web pages.";L.DomUtil.addClass(this._modal,"active"),this._sharing=L.DomUtil.create("div","mapbox-modal-body",this._content);var p=e("mapbox-button mapbox-button-icon mapbox-icon-twitter",s,"Twitter"),d=e("mapbox-button mapbox-button-icon mapbox-icon-facebook",l,"Facebook"),u=e("mapbox-button mapbox-button-icon mapbox-icon-pinterest",m,"Pinterest"),b=document.createElement("h3"),_=document.createTextNode("Share this map");b.appendChild(_);var v=document.createElement("div");v.setAttribute("class","mapbox-share-buttons"),v.appendChild(d),v.appendChild(p),v.appendChild(u),this._sharing.appendChild(b),this._sharing.appendChild(v);var x=L.DomUtil.create("input","mapbox-embed",this._sharing);x.type="text",x.value=c;var f=L.DomUtil.create("label","mapbox-embed-description",this._sharing);f.innerHTML=h;var g=L.DomUtil.create("a","leaflet-popup-close-button",this._sharing);g.href="#",L.DomEvent.disableClickPropagation(this._sharing),L.DomEvent.addListener(g,"click",this._clickOut,this),L.DomEvent.addListener(x,"click",function(t){t.target.focus(),t.target.select()})}});module.exports.ShareControl=ShareControl,module.exports.shareControl=function(t,e){return new ShareControl(t,e)};
},{"./format_url":11,"./load_tilejson":21}],28:[function(require,module,exports){
"use strict";function fallback(t,l){var i={};for(var r in l)void 0===t[r]?i[r]=l[r]:i[r]=t[r];return i}function remap(t){for(var l={},i=0;i<mapping.length;i++)l[mapping[i][1]]=t[mapping[i][0]];return l}function style(t){return remap(fallback(t.properties||{},defaults))}var defaults={stroke:"#555555","stroke-width":2,"stroke-opacity":1,fill:"#555555","fill-opacity":.5},mapping=[["stroke","color"],["stroke-width","weight"],["stroke-opacity","opacity"],["fill","fillColor"],["fill-opacity","fillOpacity"]];module.exports={style:style,defaults:defaults};
},{}],29:[function(require,module,exports){
"use strict";var util=require("./util"),format_url=require("./format_url"),request=require("./request"),StyleLayer=L.TileLayer.extend({options:{sanitizer:require("sanitize-caja")},initialize:function(t,i){L.TileLayer.prototype.initialize.call(this,void 0,i),this.options.tiles=this._formatTileURL(t),this.options.tileSize=512,this.options.zoomOffset=-1,this.options.tms=!1,this._getAttribution(t)},_getAttribution:function(t){var i=format_url.style(t,this.options&&this.options.accessToken);request(i,L.bind(function(e,r){e&&(util.log("could not load Mapbox style at "+i),this.fire("error",{error:e}));var o=[];for(var s in r.sources){var l=r.sources[s].url.split("mapbox://")[1];o.push(l)}request(format_url.tileJSON(o.join(),this.options.accessToken),L.bind(function(i,e){i?(util.log("could not load TileJSON at "+t),this.fire("error",{error:i})):e&&(util.strict(e,"object"),this.options.attribution=this.options.sanitizer(e.attribution),this._tilejson=e,this.fire("ready"))},this))},this))},setUrl:null,_formatTileURL:function(t){var i=L.Browser.retina?"@2x":"";if("string"==typeof t){-1===t.indexOf("mapbox://styles/")&&(util.log("Incorrectly formatted Mapbox style at "+t),this.fire("error"));var e=t.split("mapbox://styles/")[1];return format_url("/styles/v1/"+e+"/tiles/{z}/{x}/{y}"+i,this.options.accessToken)}return"object"==typeof t?format_url("/styles/v1/"+t.owner+"/"+t.id+"/tiles/{z}/{x}/{y}"+i,this.options.accessToken):void 0},getTileUrl:function(t){var i=L.Util.template(this.options.tiles,t);return i}});module.exports.StyleLayer=StyleLayer,module.exports.styleLayer=function(t,i){return new StyleLayer(t,i)};
},{"./format_url":11,"./request":26,"./util":31,"sanitize-caja":5}],30:[function(require,module,exports){
"use strict";var util=require("./util"),formatPattern=/\.((?:png|jpg)\d*)(?=$|\?)/,TileLayer=L.TileLayer.extend({includes:[require("./load_tilejson")],options:{sanitizer:require("sanitize-caja")},formats:["png","jpg","png32","png64","png128","png256","jpg70","jpg80","jpg90"],scalePrefix:"@2x.",initialize:function(t,i){L.TileLayer.prototype.initialize.call(this,void 0,i),this._tilejson={},i&&i.format&&util.strict_oneof(i.format,this.formats),this._loadTileJSON(t)},setFormat:function(t){return util.strict(t,"string"),this.options.format=t,this.redraw(),this},setUrl:null,_setTileJSON:function(t){return util.strict(t,"object"),this.options.format=this.options.format||t.tiles[0].match(formatPattern)[1],L.extend(this.options,{tiles:t.tiles,attribution:this.options.sanitizer(t.attribution),minZoom:t.minzoom||0,maxZoom:t.maxzoom||18,tms:"tms"===t.scheme,bounds:t.bounds&&util.lbounds(t.bounds)}),this._tilejson=t,this.redraw(),this},getTileJSON:function(){return this._tilejson},getTileUrl:function(t){var i=this.options.tiles,e=Math.floor(Math.abs(t.x+t.y)%i.length),o=i[e],r=L.Util.template(o,t);return r?r.replace(formatPattern,(L.Browser.retina?this.scalePrefix:".")+this.options.format):r},_update:function(){this.options.tiles&&L.TileLayer.prototype._update.call(this)}});module.exports.TileLayer=TileLayer,module.exports.tileLayer=function(t,i){return new TileLayer(t,i)};
},{"./load_tilejson":21,"./util":31,"sanitize-caja":5}],31:[function(require,module,exports){
"use strict";function contains(n,t){if(!t||!t.length)return!1;for(var r=0;r<t.length;r++)if(t[r]===n)return!0;return!1}module.exports={idUrl:function(n,t){-1===n.indexOf("/")?t.loadID(n):t.loadURL(n)},log:function(n){"object"==typeof console&&"function"==typeof console.error&&console.error(n)},strict:function(n,t){if(typeof n!==t)throw new Error("Invalid argument: "+t+" expected")},strict_instance:function(n,t,r){if(!(n instanceof t))throw new Error("Invalid argument: "+r+" expected")},strict_oneof:function(n,t){if(!contains(n,t))throw new Error("Invalid argument: "+n+" given, valid values are "+t.join(", "))},strip_tags:function(n){return n.replace(/<[^<]+>/g,"")},lbounds:function(n){return new L.LatLngBounds([[n[1],n[0]],[n[3],n[2]]])}};
},{}]},{},[17]);
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/leaflet.markercluster.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/*
 Leaflet.markercluster, Provides Beautiful Animated Marker Clustering functionality for Leaflet, a JS library for interactive maps.
 https://github.com/Leaflet/Leaflet.markercluster
 (c) 2012-2013, Dave Leaver, smartrak
*/
!function(t,e){L.MarkerClusterGroup=L.FeatureGroup.extend({options:{maxClusterRadius:80,iconCreateFunction:null,spiderfyOnMaxZoom:!0,showCoverageOnHover:!0,zoomToBoundsOnClick:!0,singleMarkerMode:!1,disableClusteringAtZoom:null,removeOutsideVisibleBounds:!0,animateAddingMarkers:!1,spiderfyDistanceMultiplier:1,polygonOptions:{}},initialize:function(t){L.Util.setOptions(this,t),this.options.iconCreateFunction||(this.options.iconCreateFunction=this._defaultIconCreateFunction),this._featureGroup=L.featureGroup(),this._featureGroup.on(L.FeatureGroup.EVENTS,this._propagateEvent,this),this._nonPointGroup=L.featureGroup(),this._nonPointGroup.on(L.FeatureGroup.EVENTS,this._propagateEvent,this),this._inZoomAnimation=0,this._needsClustering=[],this._needsRemoving=[],this._currentShownBounds=null,this._queue=[]},addLayer:function(t){if(t instanceof L.LayerGroup){var e=[];for(var i in t._layers)e.push(t._layers[i]);return this.addLayers(e)}if(!t.getLatLng)return this._nonPointGroup.addLayer(t),this;if(!this._map)return this._needsClustering.push(t),this;if(this.hasLayer(t))return this;this._unspiderfy&&this._unspiderfy(),this._addLayer(t,this._maxZoom);var n=t,s=this._map.getZoom();if(t.__parent)for(;n.__parent._zoom>=s;)n=n.__parent;return this._currentShownBounds.contains(n.getLatLng())&&(this.options.animateAddingMarkers?this._animationAddLayer(t,n):this._animationAddLayerNonAnimated(t,n)),this},removeLayer:function(t){if(t instanceof L.LayerGroup){var e=[];for(var i in t._layers)e.push(t._layers[i]);return this.removeLayers(e)}return t.getLatLng?this._map?t.__parent?(this._unspiderfy&&(this._unspiderfy(),this._unspiderfyLayer(t)),this._removeLayer(t,!0),this._featureGroup.hasLayer(t)&&(this._featureGroup.removeLayer(t),t.setOpacity&&t.setOpacity(1)),this):this:(!this._arraySplice(this._needsClustering,t)&&this.hasLayer(t)&&this._needsRemoving.push(t),this):(this._nonPointGroup.removeLayer(t),this)},addLayers:function(t){var e,i,n,s=this._map,r=this._featureGroup,o=this._nonPointGroup;for(e=0,i=t.length;i>e;e++)if(n=t[e],n.getLatLng){if(!this.hasLayer(n))if(s){if(this._addLayer(n,this._maxZoom),n.__parent&&2===n.__parent.getChildCount()){var a=n.__parent.getAllChildMarkers(),h=a[0]===n?a[1]:a[0];r.removeLayer(h)}}else this._needsClustering.push(n)}else o.addLayer(n);return s&&(r.eachLayer(function(t){t instanceof L.MarkerCluster&&t._iconNeedsUpdate&&t._updateIcon()}),this._topClusterLevel._recursivelyAddChildrenToMap(null,this._zoom,this._currentShownBounds)),this},removeLayers:function(t){var e,i,n,s=this._featureGroup,r=this._nonPointGroup;if(!this._map){for(e=0,i=t.length;i>e;e++)n=t[e],this._arraySplice(this._needsClustering,n),r.removeLayer(n);return this}for(e=0,i=t.length;i>e;e++)n=t[e],n.__parent?(this._removeLayer(n,!0,!0),s.hasLayer(n)&&(s.removeLayer(n),n.setOpacity&&n.setOpacity(1))):r.removeLayer(n);return this._topClusterLevel._recursivelyAddChildrenToMap(null,this._zoom,this._currentShownBounds),s.eachLayer(function(t){t instanceof L.MarkerCluster&&t._updateIcon()}),this},clearLayers:function(){return this._map||(this._needsClustering=[],delete this._gridClusters,delete this._gridUnclustered),this._noanimationUnspiderfy&&this._noanimationUnspiderfy(),this._featureGroup.clearLayers(),this._nonPointGroup.clearLayers(),this.eachLayer(function(t){delete t.__parent}),this._map&&this._generateInitialClusters(),this},getBounds:function(){var t=new L.LatLngBounds;if(this._topClusterLevel)t.extend(this._topClusterLevel._bounds);else for(var e=this._needsClustering.length-1;e>=0;e--)t.extend(this._needsClustering[e].getLatLng());return t.extend(this._nonPointGroup.getBounds()),t},eachLayer:function(t,e){var i,n=this._needsClustering.slice();for(this._topClusterLevel&&this._topClusterLevel.getAllChildMarkers(n),i=n.length-1;i>=0;i--)t.call(e,n[i]);this._nonPointGroup.eachLayer(t,e)},getLayers:function(){var t=[];return this.eachLayer(function(e){t.push(e)}),t},getLayer:function(t){var e=null;return this.eachLayer(function(i){L.stamp(i)===t&&(e=i)}),e},hasLayer:function(t){if(!t)return!1;var e,i=this._needsClustering;for(e=i.length-1;e>=0;e--)if(i[e]===t)return!0;for(i=this._needsRemoving,e=i.length-1;e>=0;e--)if(i[e]===t)return!1;return!(!t.__parent||t.__parent._group!==this)||this._nonPointGroup.hasLayer(t)},zoomToShowLayer:function(t,e){var i=function(){if((t._icon||t.__parent._icon)&&!this._inZoomAnimation)if(this._map.off("moveend",i,this),this.off("animationend",i,this),t._icon)e();else if(t.__parent._icon){var n=function(){this.off("spiderfied",n,this),e()};this.on("spiderfied",n,this),t.__parent.spiderfy()}};t._icon&&this._map.getBounds().contains(t.getLatLng())?e():t.__parent._zoom<this._map.getZoom()?(this._map.on("moveend",i,this),this._map.panTo(t.getLatLng())):(this._map.on("moveend",i,this),this.on("animationend",i,this),this._map.setView(t.getLatLng(),t.__parent._zoom+1),t.__parent.zoomToBounds())},onAdd:function(t){this._map=t;var e,i,n;if(!isFinite(this._map.getMaxZoom()))throw"Map has no maxZoom specified";for(this._featureGroup.onAdd(t),this._nonPointGroup.onAdd(t),this._gridClusters||this._generateInitialClusters(),e=0,i=this._needsRemoving.length;i>e;e++)n=this._needsRemoving[e],this._removeLayer(n,!0);for(this._needsRemoving=[],e=0,i=this._needsClustering.length;i>e;e++)n=this._needsClustering[e],n.getLatLng?n.__parent||this._addLayer(n,this._maxZoom):this._featureGroup.addLayer(n);this._needsClustering=[],this._map.on("zoomend",this._zoomEnd,this),this._map.on("moveend",this._moveEnd,this),this._spiderfierOnAdd&&this._spiderfierOnAdd(),this._bindEvents(),this._zoom=this._map.getZoom(),this._currentShownBounds=this._getExpandedVisibleBounds(),this._topClusterLevel._recursivelyAddChildrenToMap(null,this._zoom,this._currentShownBounds)},onRemove:function(t){t.off("zoomend",this._zoomEnd,this),t.off("moveend",this._moveEnd,this),this._unbindEvents(),this._map._mapPane.className=this._map._mapPane.className.replace(" leaflet-cluster-anim",""),this._spiderfierOnRemove&&this._spiderfierOnRemove(),this._hideCoverage(),this._featureGroup.onRemove(t),this._nonPointGroup.onRemove(t),this._featureGroup.clearLayers(),this._map=null},getVisibleParent:function(t){for(var e=t;e&&!e._icon;)e=e.__parent;return e||null},_arraySplice:function(t,e){for(var i=t.length-1;i>=0;i--)if(t[i]===e)return t.splice(i,1),!0},_removeLayer:function(t,e,i){var n=this._gridClusters,s=this._gridUnclustered,r=this._featureGroup,o=this._map;if(e)for(var a=this._maxZoom;a>=0&&s[a].removeObject(t,o.project(t.getLatLng(),a));a--);var h,_=t.__parent,u=_._markers;for(this._arraySplice(u,t);_&&(_._childCount--,!(_._zoom<0));)e&&_._childCount<=1?(h=_._markers[0]===t?_._markers[1]:_._markers[0],n[_._zoom].removeObject(_,o.project(_._cLatLng,_._zoom)),s[_._zoom].addObject(h,o.project(h.getLatLng(),_._zoom)),this._arraySplice(_.__parent._childClusters,_),_.__parent._markers.push(h),h.__parent=_.__parent,_._icon&&(r.removeLayer(_),i||r.addLayer(h))):(_._recalculateBounds(),i&&_._icon||_._updateIcon()),_=_.__parent;delete t.__parent},_isOrIsParent:function(t,e){for(;e;){if(t===e)return!0;e=e.parentNode}return!1},_propagateEvent:function(t){if(t.layer instanceof L.MarkerCluster){if(t.originalEvent&&this._isOrIsParent(t.layer._icon,t.originalEvent.relatedTarget))return;t.type="cluster"+t.type}this.fire(t.type,t)},_defaultIconCreateFunction:function(t){var e=t.getChildCount(),i=" marker-cluster-";return i+=10>e?"small":100>e?"medium":"large",new L.DivIcon({html:"<div><span>"+e+"</span></div>",className:"marker-cluster"+i,iconSize:new L.Point(40,40)})},_bindEvents:function(){var t=this._map,e=this.options.spiderfyOnMaxZoom,i=this.options.showCoverageOnHover,n=this.options.zoomToBoundsOnClick;(e||n)&&this.on("clusterclick",this._zoomOrSpiderfy,this),i&&(this.on("clustermouseover",this._showCoverage,this),this.on("clustermouseout",this._hideCoverage,this),t.on("zoomend",this._hideCoverage,this))},_zoomOrSpiderfy:function(t){var e=this._map;e.getMaxZoom()===e.getZoom()?this.options.spiderfyOnMaxZoom&&t.layer.spiderfy():this.options.zoomToBoundsOnClick&&t.layer.zoomToBounds(),t.originalEvent&&13===t.originalEvent.keyCode&&e._container.focus()},_showCoverage:function(t){var e=this._map;this._inZoomAnimation||(this._shownPolygon&&e.removeLayer(this._shownPolygon),t.layer.getChildCount()>2&&t.layer!==this._spiderfied&&(this._shownPolygon=new L.Polygon(t.layer.getConvexHull(),this.options.polygonOptions),e.addLayer(this._shownPolygon)))},_hideCoverage:function(){this._shownPolygon&&(this._map.removeLayer(this._shownPolygon),this._shownPolygon=null)},_unbindEvents:function(){var t=this.options.spiderfyOnMaxZoom,e=this.options.showCoverageOnHover,i=this.options.zoomToBoundsOnClick,n=this._map;(t||i)&&this.off("clusterclick",this._zoomOrSpiderfy,this),e&&(this.off("clustermouseover",this._showCoverage,this),this.off("clustermouseout",this._hideCoverage,this),n.off("zoomend",this._hideCoverage,this))},_zoomEnd:function(){this._map&&(this._mergeSplitClusters(),this._zoom=this._map._zoom,this._currentShownBounds=this._getExpandedVisibleBounds())},_moveEnd:function(){if(!this._inZoomAnimation){var t=this._getExpandedVisibleBounds();this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds,this._zoom,t),this._topClusterLevel._recursivelyAddChildrenToMap(null,this._map._zoom,t),this._currentShownBounds=t}},_generateInitialClusters:function(){var t=this._map.getMaxZoom(),e=this.options.maxClusterRadius;this.options.disableClusteringAtZoom&&(t=this.options.disableClusteringAtZoom-1),this._maxZoom=t,this._gridClusters={},this._gridUnclustered={};for(var i=t;i>=0;i--)this._gridClusters[i]=new L.DistanceGrid(e),this._gridUnclustered[i]=new L.DistanceGrid(e);this._topClusterLevel=new L.MarkerCluster(this,-1)},_addLayer:function(t,e){var i,n,s=this._gridClusters,r=this._gridUnclustered;for(this.options.singleMarkerMode&&(t.options.icon=this.options.iconCreateFunction({getChildCount:function(){return 1},getAllChildMarkers:function(){return[t]}}));e>=0;e--){i=this._map.project(t.getLatLng(),e);var o=s[e].getNearObject(i);if(o)return o._addChild(t),t.__parent=o,void 0;if(o=r[e].getNearObject(i)){var a=o.__parent;a&&this._removeLayer(o,!1);var h=new L.MarkerCluster(this,e,o,t);s[e].addObject(h,this._map.project(h._cLatLng,e)),o.__parent=h,t.__parent=h;var _=h;for(n=e-1;n>a._zoom;n--)_=new L.MarkerCluster(this,n,_),s[n].addObject(_,this._map.project(o.getLatLng(),n));for(a._addChild(_),n=e;n>=0&&r[n].removeObject(o,this._map.project(o.getLatLng(),n));n--);return}r[e].addObject(t,i)}this._topClusterLevel._addChild(t),t.__parent=this._topClusterLevel},_enqueue:function(t){this._queue.push(t),this._queueTimeout||(this._queueTimeout=setTimeout(L.bind(this._processQueue,this),300))},_processQueue:function(){for(var t=0;t<this._queue.length;t++)this._queue[t].call(this);this._queue.length=0,clearTimeout(this._queueTimeout),this._queueTimeout=null},_mergeSplitClusters:function(){this._processQueue(),this._zoom<this._map._zoom&&this._currentShownBounds.contains(this._getExpandedVisibleBounds())?(this._animationStart(),this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds,this._zoom,this._getExpandedVisibleBounds()),this._animationZoomIn(this._zoom,this._map._zoom)):this._zoom>this._map._zoom?(this._animationStart(),this._animationZoomOut(this._zoom,this._map._zoom)):this._moveEnd()},_getExpandedVisibleBounds:function(){if(!this.options.removeOutsideVisibleBounds)return this.getBounds();var t=this._map,e=t.getBounds(),i=e._southWest,n=e._northEast,s=L.Browser.mobile?0:Math.abs(i.lat-n.lat),r=L.Browser.mobile?0:Math.abs(i.lng-n.lng);return new L.LatLngBounds(new L.LatLng(i.lat-s,i.lng-r,!0),new L.LatLng(n.lat+s,n.lng+r,!0))},_animationAddLayerNonAnimated:function(t,e){if(e===t)this._featureGroup.addLayer(t);else if(2===e._childCount){e._addToMap();var i=e.getAllChildMarkers();this._featureGroup.removeLayer(i[0]),this._featureGroup.removeLayer(i[1])}else e._updateIcon()}}),L.MarkerClusterGroup.include(L.DomUtil.TRANSITION?{_animationStart:function(){this._map._mapPane.className+=" leaflet-cluster-anim",this._inZoomAnimation++},_animationEnd:function(){this._map&&(this._map._mapPane.className=this._map._mapPane.className.replace(" leaflet-cluster-anim","")),this._inZoomAnimation--,this.fire("animationend")},_animationZoomIn:function(t,e){var i,n=this._getExpandedVisibleBounds(),s=this._featureGroup;this._topClusterLevel._recursively(n,t,0,function(r){var o,a=r._latlng,h=r._markers;for(n.contains(a)||(a=null),r._isSingleParent()&&t+1===e?(s.removeLayer(r),r._recursivelyAddChildrenToMap(null,e,n)):(r.setOpacity(0),r._recursivelyAddChildrenToMap(a,e,n)),i=h.length-1;i>=0;i--)o=h[i],n.contains(o._latlng)||s.removeLayer(o)}),this._forceLayout(),this._topClusterLevel._recursivelyBecomeVisible(n,e),s.eachLayer(function(t){t instanceof L.MarkerCluster||!t._icon||t.setOpacity(1)}),this._topClusterLevel._recursively(n,t,e,function(t){t._recursivelyRestoreChildPositions(e)}),this._enqueue(function(){this._topClusterLevel._recursively(n,t,0,function(t){s.removeLayer(t),t.setOpacity(1)}),this._animationEnd()})},_animationZoomOut:function(t,e){this._animationZoomOutSingle(this._topClusterLevel,t-1,e),this._topClusterLevel._recursivelyAddChildrenToMap(null,e,this._getExpandedVisibleBounds()),this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds,t,this._getExpandedVisibleBounds())},_animationZoomOutSingle:function(t,e,i){var n=this._getExpandedVisibleBounds();t._recursivelyAnimateChildrenInAndAddSelfToMap(n,e+1,i);var s=this;this._forceLayout(),t._recursivelyBecomeVisible(n,i),this._enqueue(function(){if(1===t._childCount){var r=t._markers[0];r.setLatLng(r.getLatLng()),r.setOpacity&&r.setOpacity(1)}else t._recursively(n,i,0,function(t){t._recursivelyRemoveChildrenFromMap(n,e+1)});s._animationEnd()})},_animationAddLayer:function(t,e){var i=this,n=this._featureGroup;n.addLayer(t),e!==t&&(e._childCount>2?(e._updateIcon(),this._forceLayout(),this._animationStart(),t._setPos(this._map.latLngToLayerPoint(e.getLatLng())),t.setOpacity(0),this._enqueue(function(){n.removeLayer(t),t.setOpacity(1),i._animationEnd()})):(this._forceLayout(),i._animationStart(),i._animationZoomOutSingle(e,this._map.getMaxZoom(),this._map.getZoom())))},_forceLayout:function(){L.Util.falseFn(e.body.offsetWidth)}}:{_animationStart:function(){},_animationZoomIn:function(t,e){this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds,t),this._topClusterLevel._recursivelyAddChildrenToMap(null,e,this._getExpandedVisibleBounds())},_animationZoomOut:function(t,e){this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds,t),this._topClusterLevel._recursivelyAddChildrenToMap(null,e,this._getExpandedVisibleBounds())},_animationAddLayer:function(t,e){this._animationAddLayerNonAnimated(t,e)}}),L.markerClusterGroup=function(t){return new L.MarkerClusterGroup(t)},L.MarkerCluster=L.Marker.extend({initialize:function(t,e,i,n){L.Marker.prototype.initialize.call(this,i?i._cLatLng||i.getLatLng():new L.LatLng(0,0),{icon:this}),this._group=t,this._zoom=e,this._markers=[],this._childClusters=[],this._childCount=0,this._iconNeedsUpdate=!0,this._bounds=new L.LatLngBounds,i&&this._addChild(i),n&&this._addChild(n)},getAllChildMarkers:function(t){t=t||[];for(var e=this._childClusters.length-1;e>=0;e--)this._childClusters[e].getAllChildMarkers(t);for(var i=this._markers.length-1;i>=0;i--)t.push(this._markers[i]);return t},getChildCount:function(){return this._childCount},zoomToBounds:function(){for(var t,e=this._childClusters.slice(),i=this._group._map,n=i.getBoundsZoom(this._bounds),s=this._zoom+1,r=i.getZoom();e.length>0&&n>s;){s++;var o=[];for(t=0;t<e.length;t++)o=o.concat(e[t]._childClusters);e=o}n>s?this._group._map.setView(this._latlng,s):r>=n?this._group._map.setView(this._latlng,r+1):this._group._map.fitBounds(this._bounds)},getBounds:function(){var t=new L.LatLngBounds;return t.extend(this._bounds),t},_updateIcon:function(){this._iconNeedsUpdate=!0,this._icon&&this.setIcon(this)},createIcon:function(){return this._iconNeedsUpdate&&(this._iconObj=this._group.options.iconCreateFunction(this),this._iconNeedsUpdate=!1),this._iconObj.createIcon()},createShadow:function(){return this._iconObj.createShadow()},_addChild:function(t,e){this._iconNeedsUpdate=!0,this._expandBounds(t),t instanceof L.MarkerCluster?(e||(this._childClusters.push(t),t.__parent=this),this._childCount+=t._childCount):(e||this._markers.push(t),this._childCount++),this.__parent&&this.__parent._addChild(t,!0)},_expandBounds:function(t){var e,i=t._wLatLng||t._latlng;t instanceof L.MarkerCluster?(this._bounds.extend(t._bounds),e=t._childCount):(this._bounds.extend(i),e=1),this._cLatLng||(this._cLatLng=t._cLatLng||i);var n=this._childCount+e;this._wLatLng?(this._wLatLng.lat=(i.lat*e+this._wLatLng.lat*this._childCount)/n,this._wLatLng.lng=(i.lng*e+this._wLatLng.lng*this._childCount)/n):this._latlng=this._wLatLng=new L.LatLng(i.lat,i.lng)},_addToMap:function(t){t&&(this._backupLatlng=this._latlng,this.setLatLng(t)),this._group._featureGroup.addLayer(this)},_recursivelyAnimateChildrenIn:function(t,e,i){this._recursively(t,0,i-1,function(t){var i,n,s=t._markers;for(i=s.length-1;i>=0;i--)n=s[i],n._icon&&(n._setPos(e),n.setOpacity(0))},function(t){var i,n,s=t._childClusters;for(i=s.length-1;i>=0;i--)n=s[i],n._icon&&(n._setPos(e),n.setOpacity(0))})},_recursivelyAnimateChildrenInAndAddSelfToMap:function(t,e,i){this._recursively(t,i,0,function(n){n._recursivelyAnimateChildrenIn(t,n._group._map.latLngToLayerPoint(n.getLatLng()).round(),e),n._isSingleParent()&&e-1===i?(n.setOpacity(1),n._recursivelyRemoveChildrenFromMap(t,e)):n.setOpacity(0),n._addToMap()})},_recursivelyBecomeVisible:function(t,e){this._recursively(t,0,e,null,function(t){t.setOpacity(1)})},_recursivelyAddChildrenToMap:function(t,e,i){this._recursively(i,-1,e,function(n){if(e!==n._zoom)for(var s=n._markers.length-1;s>=0;s--){var r=n._markers[s];i.contains(r._latlng)&&(t&&(r._backupLatlng=r.getLatLng(),r.setLatLng(t),r.setOpacity&&r.setOpacity(0)),n._group._featureGroup.addLayer(r))}},function(e){e._addToMap(t)})},_recursivelyRestoreChildPositions:function(t){for(var e=this._markers.length-1;e>=0;e--){var i=this._markers[e];i._backupLatlng&&(i.setLatLng(i._backupLatlng),delete i._backupLatlng)}if(t-1===this._zoom)for(var n=this._childClusters.length-1;n>=0;n--)this._childClusters[n]._restorePosition();else for(var s=this._childClusters.length-1;s>=0;s--)this._childClusters[s]._recursivelyRestoreChildPositions(t)},_restorePosition:function(){this._backupLatlng&&(this.setLatLng(this._backupLatlng),delete this._backupLatlng)},_recursivelyRemoveChildrenFromMap:function(t,e,i){var n,s;this._recursively(t,-1,e-1,function(t){for(s=t._markers.length-1;s>=0;s--)n=t._markers[s],i&&i.contains(n._latlng)||(t._group._featureGroup.removeLayer(n),n.setOpacity&&n.setOpacity(1))},function(t){for(s=t._childClusters.length-1;s>=0;s--)n=t._childClusters[s],i&&i.contains(n._latlng)||(t._group._featureGroup.removeLayer(n),n.setOpacity&&n.setOpacity(1))})},_recursively:function(t,e,i,n,s){var r,o,a=this._childClusters,h=this._zoom;if(e>h)for(r=a.length-1;r>=0;r--)o=a[r],t.intersects(o._bounds)&&o._recursively(t,e,i,n,s);else if(n&&n(this),s&&this._zoom===i&&s(this),i>h)for(r=a.length-1;r>=0;r--)o=a[r],t.intersects(o._bounds)&&o._recursively(t,e,i,n,s)},_recalculateBounds:function(){var t,e=this._markers,i=this._childClusters;for(this._bounds=new L.LatLngBounds,delete this._wLatLng,t=e.length-1;t>=0;t--)this._expandBounds(e[t]);for(t=i.length-1;t>=0;t--)this._expandBounds(i[t])},_isSingleParent:function(){return this._childClusters.length>0&&this._childClusters[0]._childCount===this._childCount}}),L.DistanceGrid=function(t){this._cellSize=t,this._sqCellSize=t*t,this._grid={},this._objectPoint={}},L.DistanceGrid.prototype={addObject:function(t,e){var i=this._getCoord(e.x),n=this._getCoord(e.y),s=this._grid,r=s[n]=s[n]||{},o=r[i]=r[i]||[],a=L.Util.stamp(t);this._objectPoint[a]=e,o.push(t)},updateObject:function(t,e){this.removeObject(t),this.addObject(t,e)},removeObject:function(t,e){var i,n,s=this._getCoord(e.x),r=this._getCoord(e.y),o=this._grid,a=o[r]=o[r]||{},h=a[s]=a[s]||[];for(delete this._objectPoint[L.Util.stamp(t)],i=0,n=h.length;n>i;i++)if(h[i]===t)return h.splice(i,1),1===n&&delete a[s],!0},eachObject:function(t,e){var i,n,s,r,o,a,h,_=this._grid;for(i in _){o=_[i];for(n in o)for(a=o[n],s=0,r=a.length;r>s;s++)h=t.call(e,a[s]),h&&(s--,r--)}},getNearObject:function(t){var e,i,n,s,r,o,a,h,_=this._getCoord(t.x),u=this._getCoord(t.y),l=this._objectPoint,d=this._sqCellSize,p=null;for(e=u-1;u+1>=e;e++)if(s=this._grid[e])for(i=_-1;_+1>=i;i++)if(r=s[i])for(n=0,o=r.length;o>n;n++)a=r[n],h=this._sqDist(l[L.Util.stamp(a)],t),d>h&&(d=h,p=a);return p},_getCoord:function(t){return Math.floor(t/this._cellSize)},_sqDist:function(t,e){var i=e.x-t.x,n=e.y-t.y;return i*i+n*n}},function(){L.QuickHull={getDistant:function(t,e){var i=e[1].lat-e[0].lat,n=e[0].lng-e[1].lng;return n*(t.lat-e[0].lat)+i*(t.lng-e[0].lng)},findMostDistantPointFromBaseLine:function(t,e){var i,n,s,r=0,o=null,a=[];for(i=e.length-1;i>=0;i--)n=e[i],s=this.getDistant(n,t),s>0&&(a.push(n),s>r&&(r=s,o=n));return{maxPoint:o,newPoints:a}},buildConvexHull:function(t,e){var i=[],n=this.findMostDistantPointFromBaseLine(t,e);return n.maxPoint?(i=i.concat(this.buildConvexHull([t[0],n.maxPoint],n.newPoints)),i=i.concat(this.buildConvexHull([n.maxPoint,t[1]],n.newPoints))):[t[0]]},getConvexHull:function(t){var e,i=!1,n=!1,s=null,r=null;for(e=t.length-1;e>=0;e--){var o=t[e];(i===!1||o.lat>i)&&(s=o,i=o.lat),(n===!1||o.lat<n)&&(r=o,n=o.lat)}var a=[].concat(this.buildConvexHull([r,s],t),this.buildConvexHull([s,r],t));return a}}}(),L.MarkerCluster.include({getConvexHull:function(){var t,e,i=this.getAllChildMarkers(),n=[];for(e=i.length-1;e>=0;e--)t=i[e].getLatLng(),n.push(t);return L.QuickHull.getConvexHull(n)}}),L.MarkerCluster.include({_2PI:2*Math.PI,_circleFootSeparation:25,_circleStartAngle:Math.PI/6,_spiralFootSeparation:28,_spiralLengthStart:11,_spiralLengthFactor:5,_circleSpiralSwitchover:9,spiderfy:function(){if(this._group._spiderfied!==this&&!this._group._inZoomAnimation){var t,e=this.getAllChildMarkers(),i=this._group,n=i._map,s=n.latLngToLayerPoint(this._latlng);this._group._unspiderfy(),this._group._spiderfied=this,e.length>=this._circleSpiralSwitchover?t=this._generatePointsSpiral(e.length,s):(s.y+=10,t=this._generatePointsCircle(e.length,s)),this._animationSpiderfy(e,t)}},unspiderfy:function(t){this._group._inZoomAnimation||(this._animationUnspiderfy(t),this._group._spiderfied=null)},_generatePointsCircle:function(t,e){var i,n,s=this._group.options.spiderfyDistanceMultiplier*this._circleFootSeparation*(2+t),r=s/this._2PI,o=this._2PI/t,a=[];for(a.length=t,i=t-1;i>=0;i--)n=this._circleStartAngle+i*o,a[i]=new L.Point(e.x+r*Math.cos(n),e.y+r*Math.sin(n))._round();return a},_generatePointsSpiral:function(t,e){var i,n=this._group.options.spiderfyDistanceMultiplier*this._spiralLengthStart,s=this._group.options.spiderfyDistanceMultiplier*this._spiralFootSeparation,r=this._group.options.spiderfyDistanceMultiplier*this._spiralLengthFactor,o=0,a=[];for(a.length=t,i=t-1;i>=0;i--)o+=s/n+5e-4*i,a[i]=new L.Point(e.x+n*Math.cos(o),e.y+n*Math.sin(o))._round(),n+=this._2PI*r/o;return a},_noanimationUnspiderfy:function(){var t,e,i=this._group,n=i._map,s=i._featureGroup,r=this.getAllChildMarkers();for(this.setOpacity(1),e=r.length-1;e>=0;e--)t=r[e],s.removeLayer(t),t._preSpiderfyLatlng&&(t.setLatLng(t._preSpiderfyLatlng),delete t._preSpiderfyLatlng),t.setZIndexOffset&&t.setZIndexOffset(0),t._spiderLeg&&(n.removeLayer(t._spiderLeg),delete t._spiderLeg);i._spiderfied=null}}),L.MarkerCluster.include(L.DomUtil.TRANSITION?{SVG_ANIMATION:function(){return e.createElementNS("http://www.w3.org/2000/svg","animate").toString().indexOf("SVGAnimate")>-1}(),_animationSpiderfy:function(t,i){var n,s,r,o,a=this,h=this._group,_=h._map,u=h._featureGroup,l=_.latLngToLayerPoint(this._latlng);for(n=t.length-1;n>=0;n--)s=t[n],s.setOpacity?(s.setZIndexOffset(1e6),s.setOpacity(0),u.addLayer(s),s._setPos(l)):u.addLayer(s);h._forceLayout(),h._animationStart();var d=L.Path.SVG?0:.3,p=L.Path.SVG_NS;for(n=t.length-1;n>=0;n--)if(o=_.layerPointToLatLng(i[n]),s=t[n],s._preSpiderfyLatlng=s._latlng,s.setLatLng(o),s.setOpacity&&s.setOpacity(1),r=new L.Polyline([a._latlng,o],{weight:1.5,color:"#222",opacity:d}),_.addLayer(r),s._spiderLeg=r,L.Path.SVG&&this.SVG_ANIMATION){var c=r._path.getTotalLength();r._path.setAttribute("stroke-dasharray",c+","+c);var m=e.createElementNS(p,"animate");m.setAttribute("attributeName","stroke-dashoffset"),m.setAttribute("begin","indefinite"),m.setAttribute("from",c),m.setAttribute("to",0),m.setAttribute("dur",.25),r._path.appendChild(m),m.beginElement(),m=e.createElementNS(p,"animate"),m.setAttribute("attributeName","stroke-opacity"),m.setAttribute("attributeName","stroke-opacity"),m.setAttribute("begin","indefinite"),m.setAttribute("from",0),m.setAttribute("to",.5),m.setAttribute("dur",.25),r._path.appendChild(m),m.beginElement()}if(a.setOpacity(.3),L.Path.SVG)for(this._group._forceLayout(),n=t.length-1;n>=0;n--)s=t[n]._spiderLeg,s.options.opacity=.5,s._path.setAttribute("stroke-opacity",.5);setTimeout(function(){h._animationEnd(),h.fire("spiderfied")},200)},_animationUnspiderfy:function(t){var e,i,n,s=this._group,r=s._map,o=s._featureGroup,a=t?r._latLngToNewLayerPoint(this._latlng,t.zoom,t.center):r.latLngToLayerPoint(this._latlng),h=this.getAllChildMarkers(),_=L.Path.SVG&&this.SVG_ANIMATION;for(s._animationStart(),this.setOpacity(1),i=h.length-1;i>=0;i--)e=h[i],e._preSpiderfyLatlng&&(e.setLatLng(e._preSpiderfyLatlng),delete e._preSpiderfyLatlng,e.setOpacity?(e._setPos(a),e.setOpacity(0)):o.removeLayer(e),_&&(n=e._spiderLeg._path.childNodes[0],n.setAttribute("to",n.getAttribute("from")),n.setAttribute("from",0),n.beginElement(),n=e._spiderLeg._path.childNodes[1],n.setAttribute("from",.5),n.setAttribute("to",0),n.setAttribute("stroke-opacity",0),n.beginElement(),e._spiderLeg._path.setAttribute("stroke-opacity",0)));setTimeout(function(){var t=0;for(i=h.length-1;i>=0;i--)e=h[i],e._spiderLeg&&t++;for(i=h.length-1;i>=0;i--)e=h[i],e._spiderLeg&&(e.setOpacity&&(e.setOpacity(1),e.setZIndexOffset(0)),t>1&&o.removeLayer(e),r.removeLayer(e._spiderLeg),delete e._spiderLeg);s._animationEnd()},200)}}:{_animationSpiderfy:function(t,e){var i,n,s,r,o=this._group,a=o._map,h=o._featureGroup;for(i=t.length-1;i>=0;i--)r=a.layerPointToLatLng(e[i]),n=t[i],n._preSpiderfyLatlng=n._latlng,n.setLatLng(r),n.setZIndexOffset&&n.setZIndexOffset(1e6),h.addLayer(n),s=new L.Polyline([this._latlng,r],{weight:1.5,color:"#222"}),a.addLayer(s),n._spiderLeg=s;this.setOpacity(.3),o.fire("spiderfied")},_animationUnspiderfy:function(){this._noanimationUnspiderfy()}}),L.MarkerClusterGroup.include({_spiderfied:null,_spiderfierOnAdd:function(){this._map.on("click",this._unspiderfyWrapper,this),this._map.options.zoomAnimation&&this._map.on("zoomstart",this._unspiderfyZoomStart,this),this._map.on("zoomend",this._noanimationUnspiderfy,this),L.Path.SVG&&!L.Browser.touch&&this._map._initPathRoot()},_spiderfierOnRemove:function(){this._map.off("click",this._unspiderfyWrapper,this),this._map.off("zoomstart",this._unspiderfyZoomStart,this),this._map.off("zoomanim",this._unspiderfyZoomAnim,this),this._unspiderfy()},_unspiderfyZoomStart:function(){this._map&&this._map.on("zoomanim",this._unspiderfyZoomAnim,this)},_unspiderfyZoomAnim:function(t){L.DomUtil.hasClass(this._map._mapPane,"leaflet-touching")||(this._map.off("zoomanim",this._unspiderfyZoomAnim,this),this._unspiderfy(t))},_unspiderfyWrapper:function(){this._unspiderfy()},_unspiderfy:function(t){this._spiderfied&&this._spiderfied.unspiderfy(t)},_noanimationUnspiderfy:function(){this._spiderfied&&this._spiderfied._noanimationUnspiderfy()},_unspiderfyLayer:function(t){t._spiderLeg&&(this._featureGroup.removeLayer(t),t.setOpacity(1),t.setZIndexOffset(0),this._map.removeLayer(t._spiderLeg),delete t._spiderLeg)}})}(window,document);
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/leafleft-google.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/*
 * L.TileLayer is used for standard xyz-numbered tile layers.
 */

L.Google = L.Class.extend({
	includes: L.Mixin.Events,
        options: {
		minZoom: 0,
		maxZoom: 18,
		tileSize: 256,
		subdomains: 'abc',
		errorTileUrl: '',
		attribution: '',
		opacity: 1,
		continuousWorld: false,
		noWrap: false,
		styles:'',
	},

	// Possible types: SATELLITE, ROADMAP, HYBRID
	initialize: function(type, options) {
		L.Util.setOptions(this, options);

		this._type = google.maps.MapTypeId[type || 'SATELLITE'];
	},

	onAdd: function(map, insertAtTheBottom) {
		this._map = map;
		this._insertAtTheBottom = insertAtTheBottom;

		// create a container div for tiles
		this._initContainer();
		this._initMapObject();

		// set up events
		map.on('viewreset', this._resetCallback, this);

		this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
		map.on('move', this._update, this);
		//map.on('moveend', this._update, this);

		this._reset();
		this._update();
	},

	onRemove: function(map) {
		this._map._container.removeChild(this._container);
		//this._container = null;

		this._map.off('viewreset', this._resetCallback, this);

		this._map.off('move', this._update, this);
		//this._map.off('moveend', this._update, this);
	},

	getAttribution: function() {
		return this.options.attribution;
	},

	setOpacity: function(opacity) {
		this.options.opacity = opacity;
		if (opacity < 1) {
			L.DomUtil.setOpacity(this._container, opacity);
		}
	},

	_initContainer: function() {
		var tilePane = this._map._container
			first = tilePane.firstChild;

		if (!this._container) {
			this._container = L.DomUtil.create('div', 'leaflet-google-layer leaflet-top leaflet-left');
			this._container.id = "_GMapContainer";
		}

		if (true) {
			tilePane.insertBefore(this._container, first);

			this.setOpacity(this.options.opacity);
			var size = this._map.getSize();
			this._container.style.width = size.x + 'px';
			this._container.style.height = size.y + 'px';
		}
	},

	_initMapObject: function() {
		this._google_center = new google.maps.LatLng(0, 0);
		var map = new google.maps.Map(this._container, {
		    center: this._google_center,
		    zoom: 0,
		    mapTypeId: this._type,
		    disableDefaultUI: true,
		    keyboardShortcuts: false,
		    draggable: false,
		    disableDoubleClickZoom: true,
		    scrollwheel: false,
		    streetViewControl: false,
			styles: this.options.styles
		});

		var _this = this;
		this._reposition = google.maps.event.addListenerOnce(map, "center_changed", 
			function() { _this.onReposition(); });
	
		map.backgroundColor = '#ff0000';
		this._google = map;
	},

	_resetCallback: function(e) {
		this._reset(e.hard);
	},

	_reset: function(clearOldContainer) {
		this._initContainer();
	},

	_update: function() {
		this._resize();

		var bounds = this._map.getBounds();
		var ne = bounds.getNorthEast();
		var sw = bounds.getSouthWest();
		var google_bounds = new google.maps.LatLngBounds(
			new google.maps.LatLng(sw.lat, sw.lng),
			new google.maps.LatLng(ne.lat, ne.lng)
		);
		var center = this._map.getCenter();
		var _center = new google.maps.LatLng(center.lat, center.lng);

		this._google.setCenter(_center);
		this._google.setZoom(this._map.getZoom());
		//this._google.fitBounds(google_bounds);
	},

	_resize: function() {
		var size = this._map.getSize();
		if (this._container.style.width == size.x &&
		    this._container.style.height == size.y)
			return;
		this._container.style.width = size.x + 'px';
		this._container.style.height = size.y + 'px';
		google.maps.event.trigger(this._google, "resize");
	},

	onReposition: function() {
		//google.maps.event.trigger(this._google, "resize");
	}
});
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/lib/chosen/chosen.jquery.js?ver=4fca74de5e3fa981b9659807f09e9e55 
(function(){var t,e,s,i,r,o={}.hasOwnProperty,n=function(t,e){function s(){this.constructor=t}for(var i in e)o.call(e,i)&&(t[i]=e[i]);return s.prototype=e.prototype,t.prototype=new s,t.__super__=e.prototype,t};i=function(){function t(){this.options_index=0,this.parsed=[]}return t.prototype.add_node=function(t){return"OPTGROUP"===t.nodeName.toUpperCase()?this.add_group(t):this.add_option(t)},t.prototype.add_group=function(t){var e,s,i,r,o,n;for(e=this.parsed.length,this.parsed.push({array_index:e,group:!0,label:this.escapeExpression(t.label),title:t.title?t.title:void 0,children:0,disabled:t.disabled,classes:t.className}),o=t.childNodes,n=[],i=0,r=o.length;r>i;i++)s=o[i],n.push(this.add_option(s,e,t.disabled));return n},t.prototype.add_option=function(t,e,s){return"OPTION"===t.nodeName.toUpperCase()?(""!==t.text?(null!=e&&(this.parsed[e].children+=1),this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:t.value,text:t.text,html:t.innerHTML,title:t.title?t.title:void 0,selected:t.selected,disabled:s===!0?s:t.disabled,group_array_index:e,group_label:null!=e?this.parsed[e].label:null,classes:t.className,style:t.style.cssText})):this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:!0}),this.options_index+=1):void 0},t.prototype.escapeExpression=function(t){var e,s;return null==t||t===!1?"":/[\&\<\>\"\'\`]/.test(t)?(e={"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},s=/&(?!\w+;)|[\<\>\"\'\`]/g,t.replace(s,function(t){return e[t]||"&amp;"})):t},t}(),i.select_to_array=function(t){var e,s,r,o,n;for(s=new i,n=t.childNodes,r=0,o=n.length;o>r;r++)e=n[r],s.add_node(e);return s.parsed},e=function(){function t(e,s){this.form_field=e,this.options=null!=s?s:{},t.browser_is_supported()&&(this.is_multiple=this.form_field.multiple,this.set_default_text(),this.set_default_values(),this.setup(),this.set_up_html(),this.register_observers(),this.on_ready())}return t.prototype.set_default_values=function(){var t=this;return this.click_test_action=function(e){return t.test_active_click(e)},this.activate_action=function(e){return t.activate_field(e)},this.active_field=!1,this.mouse_on_container=!1,this.results_showing=!1,this.result_highlighted=null,this.allow_single_deselect=null!=this.options.allow_single_deselect&&null!=this.form_field.options[0]&&""===this.form_field.options[0].text?this.options.allow_single_deselect:!1,this.disable_search_threshold=this.options.disable_search_threshold||0,this.disable_search=this.options.disable_search||!1,this.enable_split_word_search=null!=this.options.enable_split_word_search?this.options.enable_split_word_search:!0,this.group_search=null!=this.options.group_search?this.options.group_search:!0,this.search_contains=this.options.search_contains||!1,this.single_backstroke_delete=null!=this.options.single_backstroke_delete?this.options.single_backstroke_delete:!0,this.max_selected_options=this.options.max_selected_options||1/0,this.inherit_select_classes=this.options.inherit_select_classes||!1,this.display_selected_options=null!=this.options.display_selected_options?this.options.display_selected_options:!0,this.display_disabled_options=null!=this.options.display_disabled_options?this.options.display_disabled_options:!0,this.include_group_label_in_selected=this.options.include_group_label_in_selected||!1,this.max_shown_results=this.options.max_shown_results||Number.POSITIVE_INFINITY},t.prototype.set_default_text=function(){return this.form_field.getAttribute("data-placeholder")?this.default_text=this.form_field.getAttribute("data-placeholder"):this.is_multiple?this.default_text=this.options.placeholder_text_multiple||this.options.placeholder_text||t.default_multiple_text:this.default_text=this.options.placeholder_text_single||this.options.placeholder_text||t.default_single_text,this.results_none_found=this.form_field.getAttribute("data-no_results_text")||this.options.no_results_text||t.default_no_result_text},t.prototype.choice_label=function(t){return this.include_group_label_in_selected&&null!=t.group_label?"<b class='group-name'>"+t.group_label+"</b>"+t.html:t.html},t.prototype.mouse_enter=function(){return this.mouse_on_container=!0},t.prototype.mouse_leave=function(){return this.mouse_on_container=!1},t.prototype.input_focus=function(t){var e=this;if(this.is_multiple){if(!this.active_field)return setTimeout(function(){return e.container_mousedown()},50)}else if(!this.active_field)return this.activate_field()},t.prototype.input_blur=function(t){var e=this;return this.mouse_on_container?void 0:(this.active_field=!1,setTimeout(function(){return e.blur_test()},100))},t.prototype.results_option_build=function(t){var e,s,i,r,o,n,l;for(e="",r=0,l=this.results_data,o=0,n=l.length;n>o&&(s=l[o],i="",i=s.group?this.result_add_group(s):this.result_add_option(s),""!==i&&(r++,e+=i),(null!=t?t.first:void 0)&&(s.selected&&this.is_multiple?this.choice_build(s):s.selected&&!this.is_multiple&&this.single_set_selected_text(this.choice_label(s))),!(r>=this.max_shown_results));o++);return e},t.prototype.result_add_option=function(t){var e,s;return t.search_match&&this.include_option_in_results(t)?(e=[],t.disabled||t.selected&&this.is_multiple||e.push("active-result"),!t.disabled||t.selected&&this.is_multiple||e.push("disabled-result"),t.selected&&e.push("result-selected"),null!=t.group_array_index&&e.push("group-option"),""!==t.classes&&e.push(t.classes),s=document.createElement("li"),s.className=e.join(" "),s.style.cssText=t.style,s.setAttribute("data-option-array-index",t.array_index),s.innerHTML=t.search_text,t.title&&(s.title=t.title),this.outerHTML(s)):""},t.prototype.result_add_group=function(t){var e,s;return(t.search_match||t.group_match)&&t.active_options>0?(e=[],e.push("group-result"),t.classes&&e.push(t.classes),s=document.createElement("li"),s.className=e.join(" "),s.innerHTML=t.search_text,t.title&&(s.title=t.title),this.outerHTML(s)):""},t.prototype.results_update_field=function(){return this.set_default_text(),this.is_multiple||this.results_reset_cleanup(),this.result_clear_highlight(),this.results_build(),this.results_showing?this.winnow_results():void 0},t.prototype.reset_single_select_options=function(){var t,e,s,i,r;for(i=this.results_data,r=[],e=0,s=i.length;s>e;e++)t=i[e],t.selected?r.push(t.selected=!1):r.push(void 0);return r},t.prototype.results_toggle=function(){return this.results_showing?this.results_hide():this.results_show()},t.prototype.results_search=function(t){return this.results_showing?this.winnow_results():this.results_show()},t.prototype.winnow_results=function(){var t,e,s,i,r,o,n,l,h,c,a,_;for(this.no_results_clear(),i=0,o=this.get_search_text(),t=o.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),h=new RegExp(t,"i"),s=this.get_search_regex(t),_=this.results_data,c=0,a=_.length;a>c;c++)e=_[c],e.search_match=!1,r=null,this.include_option_in_results(e)&&(e.group&&(e.group_match=!1,e.active_options=0),null!=e.group_array_index&&this.results_data[e.group_array_index]&&(r=this.results_data[e.group_array_index],0===r.active_options&&r.search_match&&(i+=1),r.active_options+=1),e.search_text=e.group?e.label:e.html,(!e.group||this.group_search)&&(e.search_match=this.search_string_match(e.search_text,s),e.search_match&&!e.group&&(i+=1),e.search_match?(o.length&&(n=e.search_text.search(h),l=e.search_text.substr(0,n+o.length)+"</em>"+e.search_text.substr(n+o.length),e.search_text=l.substr(0,n)+"<em>"+l.substr(n)),null!=r&&(r.group_match=!0)):null!=e.group_array_index&&this.results_data[e.group_array_index].search_match&&(e.search_match=!0)));return this.result_clear_highlight(),1>i&&o.length?(this.update_results_content(""),this.no_results(o)):(this.update_results_content(this.results_option_build()),this.winnow_results_set_highlight())},t.prototype.get_search_regex=function(t){var e;return e=this.search_contains?"":"^",new RegExp(e+t,"i")},t.prototype.search_string_match=function(t,e){var s,i,r,o;if(e.test(t))return!0;if(this.enable_split_word_search&&(t.indexOf(" ")>=0||0===t.indexOf("["))&&(i=t.replace(/\[|\]/g,"").split(" "),i.length))for(r=0,o=i.length;o>r;r++)if(s=i[r],e.test(s))return!0},t.prototype.choices_count=function(){var t,e,s,i;if(null!=this.selected_option_count)return this.selected_option_count;for(this.selected_option_count=0,i=this.form_field.options,e=0,s=i.length;s>e;e++)t=i[e],t.selected&&(this.selected_option_count+=1);return this.selected_option_count},t.prototype.choices_click=function(t){return t.preventDefault(),this.results_showing||this.is_disabled?void 0:this.results_show()},t.prototype.keyup_checker=function(t){var e,s;switch(e=null!=(s=t.which)?s:t.keyCode,this.search_field_scale(),e){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices_count()>0)return this.keydown_backstroke();if(!this.pending_backstroke)return this.result_clear_highlight(),this.results_search();break;case 13:if(t.preventDefault(),this.results_showing)return this.result_select(t);break;case 27:return this.results_showing&&this.results_hide(),!0;case 9:case 38:case 40:case 16:case 91:case 17:case 18:break;default:return this.results_search()}},t.prototype.clipboard_event_checker=function(t){var e=this;return setTimeout(function(){return e.results_search()},50)},t.prototype.container_width=function(){return null!=this.options.width?this.options.width:""+this.form_field.offsetWidth+"px"},t.prototype.include_option_in_results=function(t){return this.is_multiple&&!this.display_selected_options&&t.selected?!1:!this.display_disabled_options&&t.disabled?!1:t.empty?!1:!0},t.prototype.search_results_touchstart=function(t){return this.touch_started=!0,this.search_results_mouseover(t)},t.prototype.search_results_touchmove=function(t){return this.touch_started=!1,this.search_results_mouseout(t)},t.prototype.search_results_touchend=function(t){return this.touch_started?this.search_results_mouseup(t):void 0},t.prototype.outerHTML=function(t){var e;return t.outerHTML?t.outerHTML:(e=document.createElement("div"),e.appendChild(t),e.innerHTML)},t.browser_is_supported=function(){return/iP(od|hone)/i.test(window.navigator.userAgent)?!1:/Android/i.test(window.navigator.userAgent)&&/Mobile/i.test(window.navigator.userAgent)?!1:/IEMobile/i.test(window.navigator.userAgent)?!1:/Windows Phone/i.test(window.navigator.userAgent)?!1:/BlackBerry/i.test(window.navigator.userAgent)?!1:/BB10/i.test(window.navigator.userAgent)?!1:"Microsoft Internet Explorer"===window.navigator.appName?document.documentMode>=8:!0},t.default_multiple_text="Select Some Options",t.default_single_text="Select an Option",t.default_no_result_text="No results match",t}(),t=jQuery,t.fn.extend({chosen:function(i){return e.browser_is_supported()?this.each(function(e){var r,o;return r=t(this),o=r.data("chosen"),"destroy"===i?void(o instanceof s&&o.destroy()):void(o instanceof s||r.data("chosen",new s(this,i)))}):this}}),s=function(e){function s(){return r=s.__super__.constructor.apply(this,arguments)}return n(s,e),s.prototype.setup=function(){return this.form_field_jq=t(this.form_field),this.current_selectedIndex=this.form_field.selectedIndex,this.is_rtl=this.form_field_jq.hasClass("chosen-rtl")},s.prototype.set_up_html=function(){var e,s;return e=["chosen-container"],e.push("chosen-container-"+(this.is_multiple?"multi":"single")),this.inherit_select_classes&&this.form_field.className&&e.push(this.form_field.className),this.is_rtl&&e.push("chosen-rtl"),s={"class":e.join(" "),style:"width: "+this.container_width()+";",title:this.form_field.title},this.form_field.id.length&&(s.id=this.form_field.id.replace(/[^\w]/g,"_")+"_chosen"),this.container=t("<div />",s),this.is_multiple?this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="'+this.default_text+'" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>'):this.container.html('<a class="chosen-single chosen-default"><span>'+this.default_text+'</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>'),this.form_field_jq.hide().after(this.container),this.dropdown=this.container.find("div.chosen-drop").first(),this.search_field=this.container.find("input").first(),this.search_results=this.container.find("ul.chosen-results").first(),this.search_field_scale(),this.search_no_results=this.container.find("li.no-results").first(),this.is_multiple?(this.search_choices=this.container.find("ul.chosen-choices").first(),this.search_container=this.container.find("li.search-field").first()):(this.search_container=this.container.find("div.chosen-search").first(),this.selected_item=this.container.find(".chosen-single").first()),this.results_build(),this.set_tab_index(),this.set_label_behavior()},s.prototype.on_ready=function(){return this.form_field_jq.trigger("chosen:ready",{chosen:this})},s.prototype.register_observers=function(){var t=this;return this.container.bind("touchstart.chosen",function(e){return t.container_mousedown(e),e.preventDefault()}),this.container.bind("touchend.chosen",function(e){return t.container_mouseup(e),e.preventDefault()}),this.container.bind("mousedown.chosen",function(e){t.container_mousedown(e)}),this.container.bind("mouseup.chosen",function(e){t.container_mouseup(e)}),this.container.bind("mouseenter.chosen",function(e){t.mouse_enter(e)}),this.container.bind("mouseleave.chosen",function(e){t.mouse_leave(e)}),this.search_results.bind("mouseup.chosen",function(e){t.search_results_mouseup(e)}),this.search_results.bind("mouseover.chosen",function(e){t.search_results_mouseover(e)}),this.search_results.bind("mouseout.chosen",function(e){t.search_results_mouseout(e)}),this.search_results.bind("mousewheel.chosen DOMMouseScroll.chosen",function(e){t.search_results_mousewheel(e)}),this.search_results.bind("touchstart.chosen",function(e){t.search_results_touchstart(e)}),this.search_results.bind("touchmove.chosen",function(e){t.search_results_touchmove(e)}),this.search_results.bind("touchend.chosen",function(e){t.search_results_touchend(e)}),this.form_field_jq.bind("chosen:updated.chosen",function(e){t.results_update_field(e)}),this.form_field_jq.bind("chosen:activate.chosen",function(e){t.activate_field(e)}),this.form_field_jq.bind("chosen:open.chosen",function(e){t.container_mousedown(e)}),this.form_field_jq.bind("chosen:close.chosen",function(e){t.input_blur(e)}),this.search_field.bind("blur.chosen",function(e){t.input_blur(e)}),this.search_field.bind("keyup.chosen",function(e){t.keyup_checker(e)}),this.search_field.bind("keydown.chosen",function(e){t.keydown_checker(e)}),this.search_field.bind("focus.chosen",function(e){t.input_focus(e)}),this.search_field.bind("cut.chosen",function(e){t.clipboard_event_checker(e)}),this.search_field.bind("paste.chosen",function(e){t.clipboard_event_checker(e)}),this.is_multiple?this.search_choices.bind("click.chosen",function(e){t.choices_click(e)}):this.container.bind("click.chosen",function(t){t.preventDefault()})},s.prototype.destroy=function(){return t(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.search_field[0].tabIndex&&(this.form_field_jq[0].tabIndex=this.search_field[0].tabIndex),this.container.remove(),this.form_field_jq.removeData("chosen"),this.form_field_jq.show()},s.prototype.search_field_disabled=function(){return this.is_disabled=this.form_field_jq[0].disabled,this.is_disabled?(this.container.addClass("chosen-disabled"),this.search_field[0].disabled=!0,this.is_multiple||this.selected_item.unbind("focus.chosen",this.activate_action),this.close_field()):(this.container.removeClass("chosen-disabled"),this.search_field[0].disabled=!1,this.is_multiple?void 0:this.selected_item.bind("focus.chosen",this.activate_action))},s.prototype.container_mousedown=function(e){return this.is_disabled||(e&&"mousedown"===e.type&&!this.results_showing&&e.preventDefault(),null!=e&&t(e.target).hasClass("search-choice-close"))?void 0:(this.active_field?this.is_multiple||!e||t(e.target)[0]!==this.selected_item[0]&&!t(e.target).parents("a.chosen-single").length||(e.preventDefault(),this.results_toggle()):(this.is_multiple&&this.search_field.val(""),t(this.container[0].ownerDocument).bind("click.chosen",this.click_test_action),this.results_show()),this.activate_field())},s.prototype.container_mouseup=function(t){return"ABBR"!==t.target.nodeName||this.is_disabled?void 0:this.results_reset(t)},s.prototype.search_results_mousewheel=function(t){var e;return t.originalEvent&&(e=t.originalEvent.deltaY||-t.originalEvent.wheelDelta||t.originalEvent.detail),null!=e?(t.preventDefault(),"DOMMouseScroll"===t.type&&(e=40*e),this.search_results.scrollTop(e+this.search_results.scrollTop())):void 0},s.prototype.blur_test=function(t){return!this.active_field&&this.container.hasClass("chosen-container-active")?this.close_field():void 0},s.prototype.close_field=function(){return t(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.active_field=!1,this.results_hide(),this.container.removeClass("chosen-container-active"),this.clear_backstroke(),this.show_search_field_default(),this.search_field_scale()},s.prototype.activate_field=function(){return this.container.addClass("chosen-container-active"),this.active_field=!0,this.search_field.val(this.search_field.val()),this.search_field.focus()},s.prototype.test_active_click=function(e){var s;return s=t(e.target).closest(".chosen-container"),s.length&&this.container[0]===s[0]?this.active_field=!0:this.close_field()},s.prototype.results_build=function(){return this.parsing=!0,this.selected_option_count=null,this.results_data=i.select_to_array(this.form_field),this.is_multiple?this.search_choices.find("li.search-choice").remove():this.is_multiple||(this.single_set_selected_text(),this.disable_search||this.form_field.options.length<=this.disable_search_threshold?(this.search_field[0].readOnly=!0,this.container.addClass("chosen-container-single-nosearch")):(this.search_field[0].readOnly=!1,this.container.removeClass("chosen-container-single-nosearch"))),this.update_results_content(this.results_option_build({first:!0})),this.search_field_disabled(),this.show_search_field_default(),this.search_field_scale(),this.parsing=!1},s.prototype.result_do_highlight=function(t){var e,s,i,r,o;if(t.length){if(this.result_clear_highlight(),this.result_highlight=t,this.result_highlight.addClass("highlighted"),i=parseInt(this.search_results.css("maxHeight"),10),o=this.search_results.scrollTop(),r=i+o,s=this.result_highlight.position().top+this.search_results.scrollTop(),e=s+this.result_highlight.outerHeight(),e>=r)return this.search_results.scrollTop(e-i>0?e-i:0);if(o>s)return this.search_results.scrollTop(s)}},s.prototype.result_clear_highlight=function(){return this.result_highlight&&this.result_highlight.removeClass("highlighted"),this.result_highlight=null},s.prototype.results_show=function(){return this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.container.addClass("chosen-with-drop"),this.results_showing=!0,this.search_field.focus(),this.search_field.val(this.search_field.val()),this.winnow_results(),this.form_field_jq.trigger("chosen:showing_dropdown",{chosen:this}))},s.prototype.update_results_content=function(t){return this.search_results.html(t)},s.prototype.results_hide=function(){return this.results_showing&&(this.result_clear_highlight(),this.container.removeClass("chosen-with-drop"),this.form_field_jq.trigger("chosen:hiding_dropdown",{chosen:this})),this.results_showing=!1},s.prototype.set_tab_index=function(t){var e;return this.form_field.tabIndex?(e=this.form_field.tabIndex,this.form_field.tabIndex=-1,this.search_field[0].tabIndex=e):void 0},s.prototype.set_label_behavior=function(){var e=this;return this.form_field_label=this.form_field_jq.parents("label"),!this.form_field_label.length&&this.form_field.id.length&&(this.form_field_label=t("label[for='"+this.form_field.id+"']")),this.form_field_label.length>0?this.form_field_label.bind("click.chosen",function(t){return e.is_multiple?e.container_mousedown(t):e.activate_field()}):void 0},s.prototype.show_search_field_default=function(){return this.is_multiple&&this.choices_count()<1&&!this.active_field?(this.search_field.val(this.default_text),this.search_field.addClass("default")):(this.search_field.val(""),this.search_field.removeClass("default"))},s.prototype.search_results_mouseup=function(e){var s;return s=t(e.target).hasClass("active-result")?t(e.target):t(e.target).parents(".active-result").first(),s.length?(this.result_highlight=s,this.result_select(e),this.search_field.focus()):void 0},s.prototype.search_results_mouseover=function(e){var s;return s=t(e.target).hasClass("active-result")?t(e.target):t(e.target).parents(".active-result").first(),s?this.result_do_highlight(s):void 0},s.prototype.search_results_mouseout=function(e){return t(e.target).hasClass("active-result")?this.result_clear_highlight():void 0},s.prototype.choice_build=function(e){var s,i,r=this;return s=t("<li />",{"class":"search-choice"}).html("<span>"+this.choice_label(e)+"</span>"),e.disabled?s.addClass("search-choice-disabled"):(i=t("<a />",{"class":"search-choice-close","data-option-array-index":e.array_index}),i.bind("click.chosen",function(t){return r.choice_destroy_link_click(t)}),s.append(i)),this.search_container.before(s)},s.prototype.choice_destroy_link_click=function(e){return e.preventDefault(),e.stopPropagation(),this.is_disabled?void 0:this.choice_destroy(t(e.target))},s.prototype.choice_destroy=function(t){return this.result_deselect(t[0].getAttribute("data-option-array-index"))?(this.show_search_field_default(),this.is_multiple&&this.choices_count()>0&&this.search_field.val().length<1&&this.results_hide(),t.parents("li").first().remove(),this.search_field_scale()):void 0},s.prototype.results_reset=function(){return this.reset_single_select_options(),this.form_field.options[0].selected=!0,this.single_set_selected_text(),this.show_search_field_default(),this.results_reset_cleanup(),this.form_field_jq.trigger("change"),this.active_field?this.results_hide():void 0},s.prototype.results_reset_cleanup=function(){return this.current_selectedIndex=this.form_field.selectedIndex,this.selected_item.find("abbr").remove()},s.prototype.result_select=function(t){var e,s;return this.result_highlight?(e=this.result_highlight,this.result_clear_highlight(),this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.is_multiple?e.removeClass("active-result"):this.reset_single_select_options(),e.addClass("result-selected"),s=this.results_data[e[0].getAttribute("data-option-array-index")],s.selected=!0,this.form_field.options[s.options_index].selected=!0,this.selected_option_count=null,this.is_multiple?this.choice_build(s):this.single_set_selected_text(this.choice_label(s)),(t.metaKey||t.ctrlKey)&&this.is_multiple||this.results_hide(),this.show_search_field_default(),(this.is_multiple||this.form_field.selectedIndex!==this.current_selectedIndex)&&this.form_field_jq.trigger("change",{selected:this.form_field.options[s.options_index].value}),this.current_selectedIndex=this.form_field.selectedIndex,t.preventDefault(),this.search_field_scale())):void 0},s.prototype.single_set_selected_text=function(t){return null==t&&(t=this.default_text),t===this.default_text?this.selected_item.addClass("chosen-default"):(this.single_deselect_control_build(),this.selected_item.removeClass("chosen-default")),this.selected_item.find("span").html(t)},s.prototype.result_deselect=function(t){var e;return e=this.results_data[t],this.form_field.options[e.options_index].disabled?!1:(e.selected=!1,this.form_field.options[e.options_index].selected=!1,this.selected_option_count=null,this.result_clear_highlight(),this.results_showing&&this.winnow_results(),this.form_field_jq.trigger("change",{deselected:this.form_field.options[e.options_index].value}),this.search_field_scale(),!0)},s.prototype.single_deselect_control_build=function(){return this.allow_single_deselect?(this.selected_item.find("abbr").length||this.selected_item.find("span").first().after('<abbr class="search-choice-close"></abbr>'),this.selected_item.addClass("chosen-single-with-deselect")):void 0},s.prototype.get_search_text=function(){return t("<div/>").text(t.trim(this.search_field.val())).html()},s.prototype.winnow_results_set_highlight=function(){var t,e;return e=this.is_multiple?[]:this.search_results.find(".result-selected.active-result"),t=e.length?e.first():this.search_results.find(".active-result").first(),null!=t?this.result_do_highlight(t):void 0},s.prototype.no_results=function(e){var s;return s=t('<li class="no-results">'+this.results_none_found+' "<span></span>"</li>'),s.find("span").first().html(e),this.search_results.append(s),this.form_field_jq.trigger("chosen:no_results",{chosen:this})},s.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove()},s.prototype.keydown_arrow=function(){var t;return this.results_showing&&this.result_highlight?(t=this.result_highlight.nextAll("li.active-result").first())?this.result_do_highlight(t):void 0:this.results_show()},s.prototype.keyup_arrow=function(){var t;return this.results_showing||this.is_multiple?this.result_highlight?(t=this.result_highlight.prevAll("li.active-result"),t.length?this.result_do_highlight(t.first()):(this.choices_count()>0&&this.results_hide(),this.result_clear_highlight())):void 0:this.results_show()},s.prototype.keydown_backstroke=function(){var t;return this.pending_backstroke?(this.choice_destroy(this.pending_backstroke.find("a").first()),this.clear_backstroke()):(t=this.search_container.siblings("li.search-choice").last(),t.length&&!t.hasClass("search-choice-disabled")?(this.pending_backstroke=t,this.single_backstroke_delete?this.keydown_backstroke():this.pending_backstroke.addClass("search-choice-focus")):void 0)},s.prototype.clear_backstroke=function(){return this.pending_backstroke&&this.pending_backstroke.removeClass("search-choice-focus"),this.pending_backstroke=null},s.prototype.keydown_checker=function(t){var e,s;switch(e=null!=(s=t.which)?s:t.keyCode,this.search_field_scale(),8!==e&&this.pending_backstroke&&this.clear_backstroke(),e){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:this.results_showing&&!this.is_multiple&&this.result_select(t),this.mouse_on_container=!1;break;case 13:this.results_showing&&t.preventDefault();break;case 32:this.disable_search&&t.preventDefault();break;case 38:t.preventDefault(),this.keyup_arrow();break;case 40:t.preventDefault(),this.keydown_arrow()}},s.prototype.search_field_scale=function(){var e,s,i,r,o,n,l,h,c;if(this.is_multiple){for(i=0,l=0,o="position:absolute; left: -1000px; top: -1000px; display:none;",n=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"],h=0,c=n.length;c>h;h++)r=n[h],o+=r+":"+this.search_field.css(r)+";";return e=t("<div />",{style:o}),e.text(this.search_field.val()),t("body").append(e),l=e.width()+25,e.remove(),s=this.container.outerWidth(),l>s-10&&(l=s-10),this.search_field.css({width:l+"px"})}},s}(e)}).call(this);
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/lib/bootstrap/js/bootstrap.min.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/*!
 * Bootstrap v3.3.7 (http://getbootstrap.com)
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under the MIT license
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){if(a(b.target).is(this))return b.handleObj.handler.apply(this,arguments)}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.7",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a("#"===f?[]:f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.7",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c).prop(c,!0)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c).prop(c,!1))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target).closest(".btn");b.call(d,"toggle"),a(c.target).is('input[type="radio"], input[type="checkbox"]')||(c.preventDefault(),d.is("input,button")?d.trigger("focus"):d.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(a>this.$items.length-1||a<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){if(!this.sliding)return this.slide("next")},c.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.7",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.7",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",c).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in"),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){document===a.target||this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+e).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",a,b)};c.VERSION="3.3.7",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);if(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),!c.isInStateTrue())return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-m<o.top?"bottom":"right"==h&&k.right+l>o.width?"left":"left"==h&&k.left-l<o.left?"right":h,f.removeClass(n).addClass(h)}var p=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(p,h);var q=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",q).emulateTransitionEnd(c.TRANSITION_DURATION):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top+=g,b.left+=h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element&&e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);if(this.$element.trigger(g),!g.isDefaultPrevented())return f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=window.SVGElement&&c instanceof window.SVGElement,g=d?{top:0,left:0}:f?null:b.offset(),h={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},i=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,h,i,g)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null,a.$element=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.7",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.7",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){
this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.7",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.7",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return e<c&&"top";if("bottom"==this.affixed)return null!=c?!(e+this.unpin<=f.top)&&"bottom":!(e+g<=a-d)&&"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&e<=c?"top":null!=d&&i+j>=a-d&&"bottom"},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/lib/jquerym.menu/js/jquery.mmenu.min.all.js?ver=4fca74de5e3fa981b9659807f09e9e55 
;(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('jquery'));
    } else {
        root.jquery_mmenu_all_js = factory(root.jQuery);
    }
}(this, function(jQuery) {
    /*!
     * jQuery mmenu v7.3.3
     * @requires jQuery 1.7.0 or later
     *
     * mmenujs.com
     *
     * Copyright (c) Fred Heusschen
     * www.frebsite.nl
     *
     * License: CC-BY-NC-4.0
     * http://creativecommons.org/licenses/by-nc/4.0/
     */
    !function(t){var e,n,i,s,a,r="mmenu";t[r]&&t[r].version>"7.3.3"||(t[r]=function(t,e,n){return this.$menu=t,this._api=["bind","getInstance","initPanels","openPanel","closePanel","closeAllPanels","setSelected"],this.opts=e,this.conf=n,this.vars={},this.cbck={},this.mtch={},"function"==typeof this.___deprecated&&this.___deprecated(),this._initWrappers(),this._initAddons(),this._initExtensions(),this._initHooks(),this._initMenu(),this._initPanels(),this._initOpened(),this._initAnchors(),this._initMatchMedia(),"function"==typeof this.___debug&&this.___debug(),this},t[r].version="7.3.3",t[r].uniqueId=0,t[r].wrappers={},t[r].addons={},t[r].defaults={hooks:{},extensions:[],wrappers:[],navbar:{add:!0,title:"Menu",titleLink:"parent"},onClick:{setSelected:!0},slidingSubmenus:!0},t[r].configuration={classNames:{divider:"Divider",inset:"Inset",nolistview:"NoListview",nopanel:"NoPanel",panel:"Panel",selected:"Selected",spacer:"Spacer",vertical:"Vertical"},clone:!1,language:null,openingInterval:25,panelNodetype:"ul, ol, div",transitionDuration:400},t[r].prototype={getInstance:function(){return this},initPanels:function(t){this._initPanels(t)},openPanel:function(e,s){if(this.trigger("openPanel:before",e),e&&e.length&&(e.is("."+n.panel)||(e=e.closest("."+n.panel)),e.is("."+n.panel))){var a=this;if("boolean"!=typeof s&&(s=!0),e.parent("."+n.listitem+"_vertical").length)e.parents("."+n.listitem+"_vertical").addClass(n.listitem+"_opened").children("."+n.panel).removeClass(n.hidden),this.openPanel(e.parents("."+n.panel).not(function(){return t(this).parent("."+n.listitem+"_vertical").length}).first()),this.trigger("openPanel:start",e),this.trigger("openPanel:finish",e);else{if(e.hasClass(n.panel+"_opened"))return;var l=this.$pnls.children("."+n.panel),o=this.$pnls.children("."+n.panel+"_opened");if(!t[r].support.csstransitions)return o.addClass(n.hidden).removeClass(n.panel+"_opened"),e.removeClass(n.hidden).addClass(n.panel+"_opened"),this.trigger("openPanel:start",e),void this.trigger("openPanel:finish",e);l.not(e).removeClass(n.panel+"_opened-parent");for(var d=e.data(i.parent);d;)(d=d.closest("."+n.panel)).parent("."+n.listitem+"_vertical").length||d.addClass(n.panel+"_opened-parent"),d=d.data(i.parent);l.removeClass(n.panel+"_highest").not(o).not(e).addClass(n.hidden),e.removeClass(n.hidden);var c=function(){o.removeClass(n.panel+"_opened"),e.addClass(n.panel+"_opened"),e.hasClass(n.panel+"_opened-parent")?(o.addClass(n.panel+"_highest"),e.removeClass(n.panel+"_opened-parent")):(o.addClass(n.panel+"_opened-parent"),e.addClass(n.panel+"_highest")),a.trigger("openPanel:start",e)},h=function(){o.removeClass(n.panel+"_highest").addClass(n.hidden),e.removeClass(n.panel+"_highest"),a.trigger("openPanel:finish",e)};s&&!e.hasClass(n.panel+"_noanimation")?setTimeout(function(){a.__transitionend(e,function(){h()},a.conf.transitionDuration),c()},a.conf.openingInterval):(c(),h())}this.trigger("openPanel:after",e)}},closePanel:function(t){this.trigger("closePanel:before",t);var e=t.parent();e.hasClass(n.listitem+"_vertical")&&(e.removeClass(n.listitem+"_opened"),t.addClass(n.hidden),this.trigger("closePanel",t)),this.trigger("closePanel:after",t)},closeAllPanels:function(t){this.trigger("closeAllPanels:before"),this.$pnls.find("."+n.listview).children().removeClass(n.listitem+"_selected").filter("."+n.listitem+"_vertical").removeClass(n.listitem+"_opened");var e=this.$pnls.children("."+n.panel),i=t&&t.length?t:e.first();this.$pnls.children("."+n.panel).not(i).removeClass(n.panel+"_opened").removeClass(n.panel+"_opened-parent").removeClass(n.panel+"_highest").addClass(n.hidden),this.openPanel(i,!1),this.trigger("closeAllPanels:after")},togglePanel:function(t){var e=t.parent();e.hasClass(n.listitem+"_vertical")&&this[e.hasClass(n.listitem+"_opened")?"closePanel":"openPanel"](t)},setSelected:function(t){this.trigger("setSelected:before",t),this.$menu.find("."+n.listitem+"_selected").removeClass(n.listitem+"_selected"),t.addClass(n.listitem+"_selected"),this.trigger("setSelected:after",t)},bind:function(t,e){this.cbck[t]=this.cbck[t]||[],this.cbck[t].push(e)},trigger:function(){var t=Array.prototype.slice.call(arguments),e=t.shift();if(this.cbck[e])for(var n=0,i=this.cbck[e].length;n<i;n++)this.cbck[e][n].apply(this,t)},matchMedia:function(t,e,n){var i={yes:e,no:n};this.mtch[t]=this.mtch[t]||[],this.mtch[t].push(i)},i18n:function(e){return t[r].i18n(e,this.conf.language)},_initHooks:function(){for(var t in this.opts.hooks)this.bind(t,this.opts.hooks[t])},_initWrappers:function(){this.trigger("initWrappers:before");for(var e=0;e<this.opts.wrappers.length;e++){var n=t[r].wrappers[this.opts.wrappers[e]];"function"==typeof n&&n.call(this)}this.trigger("initWrappers:after")},_initAddons:function(){var e;for(e in this.trigger("initAddons:before"),t[r].addons)t[r].addons[e].add.call(this),t[r].addons[e].add=function(){};for(e in t[r].addons)t[r].addons[e].setup.call(this);this.trigger("initAddons:after")},_initExtensions:function(){this.trigger("initExtensions:before");var t=this;for(var e in this.opts.extensions.constructor===Array&&(this.opts.extensions={all:this.opts.extensions}),this.opts.extensions)this.opts.extensions[e]=this.opts.extensions[e].length?n.menu+"_"+this.opts.extensions[e].join(" "+n.menu+"_"):"",this.opts.extensions[e]&&function(e){t.matchMedia(e,function(){this.$menu.addClass(this.opts.extensions[e])},function(){this.$menu.removeClass(this.opts.extensions[e])})}(e);this.trigger("initExtensions:after")},_initMenu:function(){this.trigger("initMenu:before");this.conf.clone&&(this.$orig=this.$menu,this.$menu=this.$orig.clone(),this.$menu.add(this.$menu.find("[id]")).filter("[id]").each(function(){t(this).attr("id",n.mm(t(this).attr("id")))})),this.$menu.attr("id",this.$menu.attr("id")||this.__getUniqueId()),this.$pnls=t('<div class="'+n.panels+'" />').append(this.$menu.children(this.conf.panelNodetype)).prependTo(this.$menu),this.$menu.addClass(n.menu).parent().addClass(n.wrapper),this.trigger("initMenu:after")},_initPanels:function(e){this.trigger("initPanels:before",e),e=e||this.$pnls.children(this.conf.panelNodetype);var i=t(),s=this,a=function(e){e.filter(s.conf.panelNodetype).each(function(e){var r=s._initPanel(t(this));if(r){s._initNavbar(r),s._initListview(r),i=i.add(r);var l=r.children("."+n.listview).children("li").children(s.conf.panelNodetype).add(r.children("."+s.conf.classNames.panel));l.length&&a(l)}})};a(e),this.trigger("initPanels:after",i)},_initPanel:function(t){this.trigger("initPanel:before",t);if(t.hasClass(n.panel))return t;if(this.__refactorClass(t,this.conf.classNames.panel,n.panel),this.__refactorClass(t,this.conf.classNames.nopanel,n.nopanel),this.__refactorClass(t,this.conf.classNames.inset,n.listview+"_inset"),t.filter("."+n.listview+"_inset").addClass(n.nopanel),t.hasClass(n.nopanel))return!1;var e=t.hasClass(this.conf.classNames.vertical)||!this.opts.slidingSubmenus;t.removeClass(this.conf.classNames.vertical);var s=t.attr("id")||this.__getUniqueId();t.is("ul, ol")&&(t.removeAttr("id"),t.wrap("<div />"),t=t.parent()),t.attr("id",s),t.addClass(n.panel+" "+n.hidden);var a=t.parent("li");return e?a.addClass(n.listitem+"_vertical"):t.appendTo(this.$pnls),a.length&&(a.data(i.child,t),t.data(i.parent,a)),this.trigger("initPanel:after",t),t},_initNavbar:function(e){if(this.trigger("initNavbar:before",e),!e.children("."+n.navbar).length){var s=e.data(i.parent),a=t('<div class="'+n.navbar+'" />'),r=this.__getPanelTitle(e,this.opts.navbar.title),l="";if(s&&s.length){if(s.hasClass(n.listitem+"_vertical"))return;if(s.parent().is("."+n.listview))var o=s.children("a, span").not("."+n.btn+"_next");else o=s.closest("."+n.panel).find('a[href="#'+e.attr("id")+'"]');var d=(s=(o=o.first()).closest("."+n.panel)).attr("id");switch(r=this.__getPanelTitle(e,t("<span>"+o.text()+"</span>").text()),this.opts.navbar.titleLink){case"anchor":l=o.attr("href")||"";break;case"parent":l="#"+d}a.append('<a class="'+n.btn+" "+n.btn+"_prev "+n.navbar+'__btn" href="#'+d+'" />')}else if(!this.opts.navbar.title)return;this.opts.navbar.add&&e.addClass(n.panel+"_has-navbar"),a.append('<a class="'+n.navbar+'__title"'+(l.length?' href="'+l+'"':"")+">"+r+"</a>").prependTo(e),this.trigger("initNavbar:after",e)}},_initListview:function(e){this.trigger("initListview:before",e);var s=this.__childAddBack(e,"ul, ol");this.__refactorClass(s,this.conf.classNames.nolistview,n.nolistview);var a=s.not("."+n.nolistview).addClass(n.listview).children().addClass(n.listitem);this.__refactorClass(a,this.conf.classNames.selected,n.listitem+"_selected"),this.__refactorClass(a,this.conf.classNames.divider,n.listitem+"_divider"),this.__refactorClass(a,this.conf.classNames.spacer,n.listitem+"_spacer"),a.children("a, span").not("."+n.btn).addClass(n.listitem+"__text");var r=e.data(i.parent);if(r&&r.is("."+n.listitem)&&!r.children("."+n.btn).length){var l=r.children("a, span").first(),o=t('<a class="'+n.btn+" "+n.btn+"_next "+n.listitem+'__btn" href="#'+e.attr("id")+'" />');o.insertAfter(l),l.is("span")&&(o.addClass(n.listitem+"__text "+l.attr("class")).html(l.html()),l.remove())}this.trigger("initListview:after",e)},_initOpened:function(){this.trigger("initOpened:before");var t=this.$pnls.find("."+n.listitem+"_selected").removeClass(n.listitem+"_selected").last().addClass(n.listitem+"_selected"),e=t.length?t.closest("."+n.panel):this.$pnls.children("."+n.panel).first();this.openPanel(e,!1),this.trigger("initOpened:after")},_initAnchors:function(){this.trigger("initAnchors:before");var e=this;a.$body.on(s.click+"-oncanvas","a[href]",function(i){var s=t(this),a=s.attr("href"),l=e.$menu.find(s).length,o=s.is("."+n.listitem+" > a"),d=s.is('[rel="external"]')||s.is('[target="_blank"]');if(l&&a.length>1&&"#"==a.slice(0,1))try{var c=e.$menu.find(a);if(c.is("."+n.panel))return e[s.parent().hasClass(n.listitem+"_vertical")?"togglePanel":"openPanel"](c),void i.preventDefault()}catch(t){}var h={close:null,setSelected:null,preventDefault:"#"==a.slice(0,1)};for(var p in t[r].addons){var f=t[r].addons[p].clickAnchor.call(e,s,l,o,d);if(f){if("boolean"==typeof f)return void i.preventDefault();"object"==typeof f&&(h=t.extend({},h,f))}}l&&o&&!d&&(e.__valueOrFn(s,e.opts.onClick.setSelected,h.setSelected)&&e.setSelected(t(i.target).parent()),e.__valueOrFn(s,e.opts.onClick.preventDefault,h.preventDefault)&&i.preventDefault(),e.__valueOrFn(s,e.opts.onClick.close,h.close)&&e.opts.offCanvas&&"function"==typeof e.close&&e.close())}),this.trigger("initAnchors:after")},_initMatchMedia:function(){var t=this;for(var e in this.mtch)!function(){var n=e,i=window.matchMedia(n);t._fireMatchMedia(n,i),i.addListener(function(e){t._fireMatchMedia(n,e)})}()},_fireMatchMedia:function(t,e){for(var n=e.matches?"yes":"no",i=0;i<this.mtch[t].length;i++)this.mtch[t][i][n].call(this)},_getOriginalMenuId:function(){var t=this.$menu.attr("id");return this.conf.clone&&t&&t.length&&(t=n.umm(t)),t},__api:function(){var e=this,n={};return t.each(this._api,function(t){var i=this;n[i]=function(){var t=e[i].apply(e,arguments);return void 0===t?n:t}}),n},__valueOrFn:function(t,e,n){if("function"==typeof e){var i=e.call(t[0]);if(void 0!==i)return i}return"function"!=typeof e&&void 0!==e||void 0===n?e:n},__getPanelTitle:function(e,n){var s;return"function"==typeof this.opts.navbar.title&&(s=this.opts.navbar.title.call(e[0])),void 0===s&&(s=e.data(i.title)),void 0!==s?s:"string"==typeof n?this.i18n(n):this.i18n(t[r].defaults.navbar.title)},__refactorClass:function(t,e,n){return t.filter("."+e).removeClass(e).addClass(n)},__findAddBack:function(t,e){return t.find(e).add(t.filter(e))},__childAddBack:function(t,e){return t.children(e).add(t.filter(e))},__filterListItems:function(t){return t.not("."+n.listitem+"_divider").not("."+n.hidden)},__filterListItemAnchors:function(t){return this.__filterListItems(t).children("a").not("."+n.btn+"_next")},__openPanelWoAnimation:function(t){t.hasClass(n.panel+"_noanimation")||(t.addClass(n.panel+"_noanimation"),this.__transitionend(t,function(){t.removeClass(n.panel+"_noanimation")},this.conf.openingInterval),this.openPanel(t))},__transitionend:function(t,e,n){var i=!1,a=function(n){void 0!==n&&n.target!=t[0]||(i||(t.off(s.transitionend),t.off(s.webkitTransitionEnd),e.call(t[0])),i=!0)};t.on(s.transitionend,a),t.on(s.webkitTransitionEnd,a),setTimeout(a,1.1*n)},__getUniqueId:function(){return n.mm(t[r].uniqueId++)}},t.fn[r]=function(e,l){!function(){if(t[r].glbl)return;a={$wndw:t(window),$docu:t(document),$html:t("html"),$body:t("body")},n={},i={},s={},t.each([n,i,s],function(t,e){e.add=function(t){t=t.split(" ");for(var n=0,i=t.length;n<i;n++)e[t[n]]=e.mm(t[n])}}),n.mm=function(t){return"mm-"+t},n.add("wrapper menu panels panel nopanel navbar listview nolistview listitem btn hidden"),n.umm=function(t){return"mm-"==t.slice(0,3)&&(t=t.slice(3)),t},i.mm=function(t){return"mm-"+t},i.add("parent child title"),s.mm=function(t){return t+".mm"},s.add("transitionend webkitTransitionEnd click scroll resize keydown mousedown mouseup touchstart touchmove touchend orientationchange"),t[r]._c=n,t[r]._d=i,t[r]._e=s,t[r].glbl=a}();var o=t();return this.each(function(){var n=t(this);if(!n.data(r)){var i=jQuery.extend(!0,{},t[r].defaults,e),s=jQuery.extend(!0,{},t[r].configuration,l),a=new t[r](n,i,s);a.$menu.data(r,a.__api()),o=o.add(a.$menu)}}),o},t[r].i18n=(e={},function(n,i){switch(typeof n){case"object":return"string"==typeof i&&(void 0===e[i]&&(e[i]={}),t.extend(e[i],n)),e;case"string":return"string"==typeof i&&void 0!==e[i]&&e[i][n]||n;case"undefined":default:return e}}),t[r].support={touch:"ontouchstart"in window||navigator.msMaxTouchPoints||!1,csstransitions:"undefined"==typeof Modernizr||void 0===Modernizr.csstransitions||Modernizr.csstransitions})}(jQuery);
    !function(e){var t,n,i,o,r="offCanvas";e.mmenu.addons[r]={setup:function(){if(this.opts[r]){var n=this.opts[r],i=this.conf[r];o=e.mmenu.glbl,this._api=e.merge(this._api,["open","close","setPage"]),"object"!=typeof n&&(n={}),n=this.opts[r]=e.extend(!0,{},e.mmenu.defaults[r],n),"string"!=typeof i.page.selector&&(i.page.selector="> "+i.page.nodetype),this.vars.opened=!1;var s=[t.menu+"_offcanvas"];this.bind("initMenu:after",function(){var e=this;this._initBlocker(),this.setPage(o.$page),this._initWindow_offCanvas(),this.$menu.addClass(s.join(" ")).parent("."+t.wrapper).removeClass(t.wrapper),this.$menu[i.menu.insertMethod](i.menu.insertSelector);var n=window.location.hash;if(n){var r=this._getOriginalMenuId();r&&r==n.slice(1)&&setTimeout(function(){e.open()},1e3)}}),this.bind("setPage:after",function(e){o.$blck&&o.$blck.children("a").attr("href","#"+e.attr("id"))}),this.bind("open:start:sr-aria",function(){this.__sr_aria(this.$menu,"hidden",!1)}),this.bind("close:finish:sr-aria",function(){this.__sr_aria(this.$menu,"hidden",!0)}),this.bind("initMenu:after:sr-aria",function(){this.__sr_aria(this.$menu,"hidden",!0)}),this.bind("initBlocker:after:sr-text",function(){o.$blck.children("a").html(this.__sr_text(this.i18n(this.conf.screenReader.text.closeMenu)))})}},add:function(){t=e.mmenu._c,n=e.mmenu._d,i=e.mmenu._e,t.add("slideout page no-csstransforms3d"),n.add("style")},clickAnchor:function(e,n){var i=this;if(this.opts[r]){var s=this._getOriginalMenuId();if(s&&e.is('[href="#'+s+'"]')){if(n)return this.open(),!0;var a=e.closest("."+t.menu);if(a.length){var p=a.data("mmenu");if(p&&p.close)return p.close(),i.__transitionend(a,function(){i.open()},i.conf.transitionDuration),!0}return this.open(),!0}if(o.$page)return(s=o.$page.first().attr("id"))&&e.is('[href="#'+s+'"]')?(this.close(),!0):void 0}}},e.mmenu.defaults[r]={blockUI:!0,moveBackground:!0},e.mmenu.configuration[r]={menu:{insertMethod:"prependTo",insertSelector:"body"},page:{nodetype:"div",selector:null,noSelector:[],wrapIfNeeded:!0}},e.mmenu.prototype.open=function(){if(this.trigger("open:before"),!this.vars.opened){var e=this;this._openSetup(),setTimeout(function(){e._openFinish()},this.conf.openingInterval),this.trigger("open:after")}},e.mmenu.prototype._openSetup=function(){var s=this,a=this.opts[r];this.closeAllOthers(),o.$page.each(function(){e(this).data(n.style,e(this).attr("style")||"")}),o.$wndw.trigger(i.resize+"-"+r,[!0]);var p=[t.wrapper+"_opened"];a.blockUI&&p.push(t.wrapper+"_blocking"),"modal"==a.blockUI&&p.push(t.wrapper+"_modal"),a.moveBackground&&p.push(t.wrapper+"_background"),o.$html.addClass(p.join(" ")),setTimeout(function(){s.vars.opened=!0},this.conf.openingInterval),this.$menu.addClass(t.menu+"_opened")},e.mmenu.prototype._openFinish=function(){var e=this;this.__transitionend(o.$page.first(),function(){e.trigger("open:finish")},this.conf.transitionDuration),this.trigger("open:start"),o.$html.addClass(t.wrapper+"_opening")},e.mmenu.prototype.close=function(){if(this.trigger("close:before"),this.vars.opened){var i=this;this.__transitionend(o.$page.first(),function(){i.$menu.removeClass(t.menu+"_opened");var r=[t.wrapper+"_opened",t.wrapper+"_blocking",t.wrapper+"_modal",t.wrapper+"_background"];o.$html.removeClass(r.join(" ")),o.$page.each(function(){var t=e(this).data(n.style);e(this).attr("style",t)}),i.vars.opened=!1,i.trigger("close:finish")},this.conf.transitionDuration),this.trigger("close:start"),o.$html.removeClass(t.wrapper+"_opening"),this.trigger("close:after")}},e.mmenu.prototype.closeAllOthers=function(){o.$body.find("."+t.menu+"_offcanvas").not(this.$menu).each(function(){var t=e(this).data("mmenu");t&&t.close&&t.close()})},e.mmenu.prototype.setPage=function(n){this.trigger("setPage:before",n);var i=this,s=this.conf[r];n&&n.length||(n=o.$body.find(s.page.selector).not("."+t.menu).not("."+t.wrapper+"__blocker"),s.page.noSelector.length&&(n=n.not(s.page.noSelector.join(", "))),n.length>1&&s.page.wrapIfNeeded&&(n=n.wrapAll("<"+this.conf[r].page.nodetype+" />").parent())),n.addClass(t.page+" "+t.slideout).each(function(){e(this).attr("id",e(this).attr("id")||i.__getUniqueId())}),o.$page=n,this.trigger("setPage:after",n)},e.mmenu.prototype._initWindow_offCanvas=function(){o.$wndw.off(i.keydown+"-"+r).on(i.keydown+"-"+r,function(e){if(o.$html.hasClass(t.wrapper+"_opened")&&9==e.keyCode)return e.preventDefault(),!1});var e=0;o.$wndw.off(i.resize+"-"+r).on(i.resize+"-"+r,function(n,i){if(1==o.$page.length&&(i||o.$html.hasClass(t.wrapper+"_opened"))){var r=o.$wndw.height();(i||r!=e)&&(e=r,o.$page.css("minHeight",r))}})},e.mmenu.prototype._initBlocker=function(){var n=this,s=this.opts[r],a=this.conf[r];this.trigger("initBlocker:before"),s.blockUI&&(o.$blck||(o.$blck=e('<div class="'+t.wrapper+"__blocker "+t.slideout+'" />').append("<a />")),o.$blck.appendTo(a.menu.insertSelector).off(i.touchstart+"-"+r+" "+i.touchmove+"-"+r).on(i.touchstart+"-"+r+" "+i.touchmove+"-"+r,function(e){e.preventDefault(),e.stopPropagation(),o.$blck.trigger(i.mousedown+"-"+r)}).off(i.mousedown+"-"+r).on(i.mousedown+"-"+r,function(e){e.preventDefault(),o.$html.hasClass(t.wrapper+"_modal")||(n.closeAllOthers(),n.close())}),this.trigger("initBlocker:after"))}}(jQuery);
    !function(t){var i,n,e="screenReader";t.mmenu.addons[e]={setup:function(){var r=this,a=this.opts[e],s=this.conf[e];t.mmenu.glbl,"boolean"==typeof a&&(a={aria:a,text:a}),"object"!=typeof a&&(a={}),(a=this.opts[e]=t.extend(!0,{},t.mmenu.defaults[e],a)).aria&&(this.bind("initAddons:after",function(){this.bind("initMenu:after",function(){this.trigger("initMenu:after:sr-aria")}),this.bind("initNavbar:after",function(){this.trigger("initNavbar:after:sr-aria",arguments[0])}),this.bind("openPanel:start",function(){this.trigger("openPanel:start:sr-aria",arguments[0])}),this.bind("close:start",function(){this.trigger("close:start:sr-aria")}),this.bind("close:finish",function(){this.trigger("close:finish:sr-aria")}),this.bind("open:start",function(){this.trigger("open:start:sr-aria")}),this.bind("initOpened:after",function(){this.trigger("initOpened:after:sr-aria")})}),this.bind("updateListview",function(){this.$pnls.find("."+i.listview).children().each(function(){r.__sr_aria(t(this),"hidden",t(this).is("."+i.hidden))})}),this.bind("openPanel:start",function(t){var n=this.$menu.find("."+i.panel).not(t).not(t.parents("."+i.panel)),e=t.add(t.find("."+i.listitem+"_vertical ."+i.listitem+"_opened").children("."+i.panel));this.__sr_aria(n,"hidden",!0),this.__sr_aria(e,"hidden",!1)}),this.bind("closePanel",function(t){this.__sr_aria(t,"hidden",!0)}),this.bind("initPanels:after",function(n){var e=n.find("."+i.btn).each(function(){r.__sr_aria(t(this),"owns",t(this).attr("href").replace("#",""))});this.__sr_aria(e,"haspopup",!0)}),this.bind("initNavbar:after",function(t){var n=t.children("."+i.navbar);this.__sr_aria(n,"hidden",!t.hasClass(i.panel+"_has-navbar"))}),a.text&&"parent"==this.opts.navbar.titleLink&&this.bind("initNavbar:after",function(t){var n=t.children("."+i.navbar),e=!!n.children("."+i.btn+"_prev").length;this.__sr_aria(n.children("."+i.title),"hidden",e)})),a.text&&(this.bind("initAddons:after",function(){this.bind("setPage:after",function(){this.trigger("setPage:after:sr-text",arguments[0])}),this.bind("initBlocker:after",function(){this.trigger("initBlocker:after:sr-text")})}),this.bind("initNavbar:after",function(t){var n=t.children("."+i.navbar),e=this.i18n(s.text.closeSubmenu);n.children("."+i.btn+"_prev").html(this.__sr_text(e))}),this.bind("initListview:after",function(t){var e=t.data(n.parent);if(e&&e.length){var a=e.children("."+i.btn+"_next"),o=this.i18n(s.text[a.parent().is("."+i.listitem+"_vertical")?"toggleSubmenu":"openSubmenu"]);a.append(r.__sr_text(o))}}))},add:function(){i=t.mmenu._c,n=t.mmenu._d,t.mmenu._e,i.add("sronly")},clickAnchor:function(t,i){}},t.mmenu.defaults[e]={aria:!0,text:!0},t.mmenu.configuration[e]={text:{closeMenu:"Close menu",closeSubmenu:"Close submenu",openSubmenu:"Open submenu",toggleSubmenu:"Toggle submenu"}},t.mmenu.prototype.__sr_aria=function(t,i,n){t.prop("aria-"+i,n)[n?"attr":"removeAttr"]("aria-"+i,n)},t.mmenu.prototype.__sr_role=function(t,i){t.prop("role",i)[i?"attr":"removeAttr"]("role",i)},t.mmenu.prototype.__sr_text=function(t){return'<span class="'+i.sronly+'">'+t+"</span>"}}(jQuery);
    !function(o){var t,n,e,r="scrollBugFix";o.mmenu.addons[r]={setup:function(){var n=this.opts[r];this.conf[r];e=o.mmenu.glbl,o.mmenu.support.touch&&this.opts.offCanvas&&this.opts.offCanvas.blockUI&&("boolean"==typeof n&&(n={fix:n}),"object"!=typeof n&&(n={}),(n=this.opts[r]=o.extend(!0,{},o.mmenu.defaults[r],n)).fix&&(this.bind("open:start",function(){this.$pnls.children("."+t.panel+"_opened").scrollTop(0)}),this.bind("initMenu:after",function(){this["_initWindow_"+r]()})))},add:function(){t=o.mmenu._c,o.mmenu._d,n=o.mmenu._e},clickAnchor:function(o,t){}},o.mmenu.defaults[r]={fix:!0},o.mmenu.prototype["_initWindow_"+r]=function(){var s=this;o(document).off(n.touchmove+"-"+r).on(n.touchmove+"-"+r,function(o){e.$html.hasClass(t.wrapper+"_opened")&&o.preventDefault()});var i=!1;e.$body.off(n.touchstart+"-"+r).on(n.touchstart+"-"+r,"."+t.panels+"> ."+t.panel,function(o){e.$html.hasClass(t.wrapper+"_opened")&&(i||(i=!0,0===o.currentTarget.scrollTop?o.currentTarget.scrollTop=1:o.currentTarget.scrollHeight===o.currentTarget.scrollTop+o.currentTarget.offsetHeight&&(o.currentTarget.scrollTop-=1),i=!1))}).off(n.touchmove+"-"+r).on(n.touchmove+"-"+r,"."+t.panels+"> ."+t.panel,function(n){e.$html.hasClass(t.wrapper+"_opened")&&o(this)[0].scrollHeight>o(this).innerHeight()&&n.stopPropagation()}),e.$wndw.off(n.orientationchange+"-"+r).on(n.orientationchange+"-"+r,function(){s.$pnls.children("."+t.panel+"_opened").scrollTop(0).css({"-webkit-overflow-scrolling":"auto"}).css({"-webkit-overflow-scrolling":"touch"})})}}(jQuery);
    !function(t){var e,i="autoHeight";t.mmenu.addons[i]={setup:function(){var n=this.opts[i];this.conf[i];if(t.mmenu.glbl,"boolean"==typeof n&&n&&(n={height:"auto"}),"string"==typeof n&&(n={height:n}),"object"!=typeof n&&(n={}),"auto"==(n=this.opts[i]=t.extend(!0,{},t.mmenu.defaults[i],n)).height||"highest"==n.height){this.bind("initMenu:after",function(){this.$menu.addClass(e.menu+"_autoheight")});var h=function(i){if(!this.opts.offCanvas||this.vars.opened){var h=Math.max(parseInt(this.$pnls.css("top"),10),0)||0,s=Math.max(parseInt(this.$pnls.css("bottom"),10),0)||0,a=0;this.$menu.addClass(e.menu+"_autoheight-measuring"),"auto"==n.height?((i=i||this.$pnls.children("."+e.panel+"_opened")).parent("."+e.listitem+"_vertical").length&&(i=i.parents("."+e.panel).not(function(){return t(this).parent("."+e.listitem+"_vertical").length})),i.length||(i=this.$pnls.children("."+e.panel)),a=i.first().outerHeight()):"highest"==n.height&&this.$pnls.children("."+e.panel).each(function(){var i=t(this);i.parent("."+e.listitem+"_vertical").length&&(i=i.parents("."+e.panel).not(function(){return t(this).parent("."+e.listitem+"_vertical").length})),a=Math.max(a,i.first().outerHeight())}),this.$menu.height(a+h+s).removeClass(e.menu+"_autoheight-measuring")}};this.opts.offCanvas&&this.bind("open:start",h),"highest"==n.height&&this.bind("initPanels:after",h),"auto"==n.height&&(this.bind("updateListview",h),this.bind("openPanel:start",h),this.bind("closePanel",h))}},add:function(){e=t.mmenu._c,t.mmenu._d,t.mmenu._e.add("resize")},clickAnchor:function(t,e){}},t.mmenu.defaults[i]={height:"default"}}(jQuery);
    !function(n){var t,e="backButton";n.mmenu.addons[e]={setup:function(){if(this.opts.offCanvas){var o=this,i=this.opts[e];this.conf[e];n.mmenu.glbl,"boolean"==typeof i&&(i={close:i}),"object"!=typeof i&&(i={}),i=n.extend(!0,{},n.mmenu.defaults[e],i);var s="#"+this.$menu.attr("id");if(i.close){var a=[];function u(){a=[s],this.$pnls.children("."+t.panel+"_opened-parent").add(o.$pnls.children("."+t.panel+"_opened")).each(function(){a.push("#"+n(this).attr("id"))})}this.bind("open:finish",function(){history.pushState(null,document.title,s)}),this.bind("open:finish",u),this.bind("openPanel:finish",u),this.bind("close:finish",function(){a=[],history.back(),history.pushState(null,document.title,location.pathname+location.search)}),n(window).on("popstate",function(t){if(o.vars.opened&&a.length){var e=(a=a.slice(0,-1))[a.length-1];e==s?o.close():(o.openPanel(n(e)),history.pushState(null,document.title,s))}})}i.open&&n(window).on("popstate",function(n){o.vars.opened||location.hash!=s||o.open()})}},add:function(){window.history&&window.history.pushState?(t=n.mmenu._c,n.mmenu._d,n.mmenu._e):n.mmenu.addons[e].setup=function(){}},clickAnchor:function(n,t){}},n.mmenu.defaults[e]={close:!1,open:!1}}(jQuery);
    !function(e){var n,i;e.mmenu.addons.columns={setup:function(){var s=this.opts.columns;this.conf.columns;if(e.mmenu.glbl,"boolean"==typeof s&&(s={add:s}),"number"==typeof s&&(s={add:!0,visible:s}),"object"!=typeof s&&(s={}),"number"==typeof s.visible&&(s.visible={min:s.visible,max:s.visible}),(s=this.opts.columns=e.extend(!0,{},e.mmenu.defaults.columns,s)).add){s.visible.min=Math.max(1,Math.min(6,s.visible.min)),s.visible.max=Math.max(s.visible.min,Math.min(6,s.visible.max));for(var a="",l="",t=0;t<=s.visible.max;t++)a+=" "+n.menu+"_columns-"+t,l+=" "+n.panel+"_columns-"+t;a.length&&(a=a.slice(1),l=l.slice(1));var m=l+" "+n.panel+"_opened "+n.panel+"_opened-parent "+n.panel+"_highest";this.bind("openPanel:before",function(e){var s=e.data(i.parent);if(s&&(s=s.closest("."+n.panel)).length){var a=s.attr("class");if(a&&(a=a.split(n.panel+"_columns-")[1]))for(a=parseInt(a.split(" ")[0],10)+1;a>0;){var l=this.$pnls.children("."+n.panel+"_columns-"+a);if(!l.length){a=-1;break}a++,l.removeClass(m).addClass(n.hidden)}}}),this.bind("openPanel:start",function(i){var t=this.$pnls.children("."+n.panel+"_opened-parent").length;i.hasClass(n.panel+"_opened-parent")||t++,t=Math.min(s.visible.max,Math.max(s.visible.min,t)),this.$menu.removeClass(a).addClass(n.menu+"_columns-"+t),this.$pnls.children("."+n.panel).removeClass(l).filter("."+n.panel+"_opened-parent").add(i).slice(-s.visible.max).each(function(i){e(this).addClass(n.panel+"_columns-"+i)})})}},add:function(){n=e.mmenu._c,i=e.mmenu._d,e.mmenu._e},clickAnchor:function(e,n){}},e.mmenu.defaults.columns={add:!1,visible:{min:1,max:3}}}(jQuery);
    !function(t){var n,e;t.mmenu.addons.counters={setup:function(){var i=this,s=this.opts.counters;this.conf.counters;if(t.mmenu.glbl,"boolean"==typeof s&&(s={add:s,update:s}),"object"!=typeof s&&(s={}),s=this.opts.counters=t.extend(!0,{},t.mmenu.defaults.counters,s),this.bind("initListview:after",function(t){var e=this.conf.classNames.counters.counter;this.__refactorClass(t.find("."+e),e,n.counter)}),s.add&&this.bind("initListview:after",function(i){var a;switch(s.addTo){case"panels":a=i;break;default:a=i.filter(s.addTo)}a.each(function(){var i=t(this).data(e.parent);i&&(i.find("."+n.counter).length||i.children("."+n.btn).prepend(t('<span class="'+n.counter+'" />')))})}),s.update){var a=function(s){(s=s||this.$pnls.children("."+n.panel)).each(function(){var s=t(this),a=s.data(e.parent);if(a){var c=a.find("."+n.counter);c.length&&(s=s.children("."+n.listview)).length&&c.html(i.__filterListItems(s.children()).length)}})};this.bind("initListview:after",a),this.bind("updateListview",a)}},add:function(){n=t.mmenu._c,e=t.mmenu._d,t.mmenu._e,n.add("counter")},clickAnchor:function(t,n){}},t.mmenu.defaults.counters={add:!1,addTo:"panels",count:!1},t.mmenu.configuration.classNames.counters={counter:"Counter"}}(jQuery);
    !function(i){var e,t,d="dividers";i.mmenu.addons.dividers={setup:function(){var n=this,s=this.opts.dividers;this.conf.dividers;if(i.mmenu.glbl,"boolean"==typeof s&&(s={add:s,fixed:s}),"object"!=typeof s&&(s={}),(s=this.opts.dividers=i.extend(!0,{},i.mmenu.defaults.dividers,s)).type&&this.bind("initMenu:after",function(){this.$menu.addClass(e.menu+"_"+d+"-"+s.type)}),s.add&&this.bind("initListview:after",function(t){var d;switch(s.addTo){case"panels":d=t;break;default:d=t.filter(s.addTo)}d.length&&(d.children("."+e.listitem+"_divider").remove(),d.find("."+e.listview).each(function(){var t="";n.__filterListItems(i(this).children()).each(function(){var d=i.trim(i(this).children("a, span").text()).slice(0,1).toLowerCase();d!=t&&d.length&&(t=d,i('<li class="'+e.listitem+" "+e.listitem+'_divider">'+d+"</li>").insertBefore(this))})}))}),s.fixed){this.bind("initPanels:before",function(){void 0===this.$fixeddivider&&(this.$fixeddivider=i('<ul class="'+e.listview+" "+e.listview+'_fixeddivider"><li class="'+e.listitem+" "+e.listitem+'_divider"></li></ul>').appendTo(this.$pnls).children())});var l=function(t){if(!(t=t||this.$pnls.children("."+e.panel+"_opened")).is(":hidden")){var d=t.find("."+e.listitem+"_divider").not("."+e.hidden),n=t.scrollTop()||0,s="";d.each(function(){i(this).position().top+n<n+1&&(s=i(this).text())}),this.$fixeddivider.text(s),this.$pnls[s.length?"addClass":"removeClass"](e.panel+"_dividers")}};this.bind("open:start",l),this.bind("openPanel:start",l),this.bind("updateListview",l),this.bind("initPanel:after",function(i){i.off(t.scroll+"-"+d+" "+t.touchmove+"-"+d).on(t.scroll+"-"+d+" "+t.touchmove+"-"+d,function(t){i.hasClass(e.panel+"_opened")&&l.call(n,i)})})}},add:function(){e=i.mmenu._c,i.mmenu._d,(t=i.mmenu._e).add("scroll")},clickAnchor:function(i,e){}},i.mmenu.defaults.dividers={add:!1,addTo:"panels",fixed:!1,type:null}}(jQuery);
    !function(n){var e,t,o,i="drag";function a(n,e,t){return n<e&&(n=e),n>t&&(n=t),n}n.mmenu.addons[i]={setup:function(){if(this.opts.offCanvas){var s=this.opts[i],r=this.conf[i];o=n.mmenu.glbl,"boolean"==typeof s&&(s={menu:s,panels:s}),"object"!=typeof s&&(s={}),"boolean"==typeof s.menu&&(s.menu={open:s.menu}),"object"!=typeof s.menu&&(s.menu={}),"boolean"==typeof s.panels&&(s.panels={close:s.panels}),"object"!=typeof s.panels&&(s.panels={}),(s=this.opts[i]=n.extend(!0,{},n.mmenu.defaults[i],s)).menu.open&&this.bind("setPage:after",function(){(function(t,o,s){var r,p,m,u,c=this,d={events:"panleft panright",typeLower:"x",typeUpper:"X",open_dir:"right",close_dir:"left",negative:!1},f="width",l=d.open_dir,h=function(n){n<=t.maxStartPos&&(_=1)},g=function(){return n("."+e.slideout)},_=0,v=0,b=0,w=this.opts.extensions.all,y=void 0===w?"left":w.indexOf(e.menu+"_position-right")>-1?"right":w.indexOf(e.menu+"_position-top")>-1?"top":w.indexOf(e.menu+"_position-bottom")>-1?"bottom":"left",x=void 0===w?"back":w.indexOf(e.menu+"_position-top")>-1||w.indexOf(e.menu+"_position-bottom")>-1||w.indexOf(e.menu+"_position-front")>-1?"front":"back";switch(y){case"top":case"bottom":d.events="panup pandown",d.typeLower="y",d.typeUpper="Y",f="height"}switch(y){case"right":case"bottom":d.negative=!0,h=function(n){n>=s.$wndw[f]()-t.maxStartPos&&(_=1)}}switch(y){case"right":d.open_dir="left",d.close_dir="right";break;case"top":d.open_dir="down",d.close_dir="up";break;case"bottom":d.open_dir="up",d.close_dir="down"}switch(x){case"front":g=function(){return c.$menu}}var O=this.__valueOrFn(this.$menu,t.node,s.$page);"string"==typeof O&&(O=n(O));var $=new Hammer(O[0],this.opts[i].vendors.hammer);$.on("panstart",function(n){h(n.center[d.typeLower]),u=g(),l=d.open_dir}),$.on(d.events+" panend",function(n){_>0&&n.preventDefault()}),$.on(d.events,function(n){if(r=n["delta"+d.typeUpper],d.negative&&(r=-r),r!=v&&(l=r>=v?d.open_dir:d.close_dir),(v=r)>t.threshold&&1==_){if(s.$html.hasClass(e.wrapper+"_opened"))return;_=2,c._openSetup(),c.trigger("open:start"),s.$html.addClass(e.dragging),b=a(s.$wndw[f]()*o[f].perc,o[f].min,o[f].max)}2==_&&(p=a(v,10,b)-("front"==x?b:0),d.negative&&(p=-p),m="translate"+d.typeUpper+"("+p+"px )",u.css({"-webkit-transform":"-webkit-"+m,transform:m}))}),$.on("panend",function(n){2==_&&(s.$html.removeClass(e.dragging),u.css("transform",""),c[l==d.open_dir?"_openFinish":"close"]()),_=0})}).call(this,s.menu,r.menu,o)}),s.panels.close&&this.bind("initPanel:after",function(n){(function(n,o,a,s){var r=this,p=n.data(t.parent);if(p){p=p.closest("."+e.panel);var m=new Hammer(n[0],r.opts[i].vendors.hammer),u=null;m.on("panright",function(n){u||(r.openPanel(p),u=setTimeout(function(){clearTimeout(u),u=null},r.conf.openingInterval+r.conf.transitionDuration))})}}).call(this,n,s.panels,r.panels,o)})}},add:function(){if("function"!=typeof Hammer||Hammer.VERSION<2)return n.mmenu.addons[i].add=function(){},void(n.mmenu.addons[i].setup=function(){});e=n.mmenu._c,t=n.mmenu._d,n.mmenu._e,e.add("dragging")},clickAnchor:function(n,e){}},n.mmenu.defaults[i]={menu:{open:!1,maxStartPos:100,threshold:50},panels:{close:!1},vendors:{hammer:{}}},n.mmenu.configuration[i]={menu:{width:{perc:.8,min:140,max:440},height:{perc:.8,min:140,max:880}},panels:{}}}(jQuery);
    !function(t){var o,e,n,i,s="dropdown";t.mmenu.addons.dropdown={setup:function(){if(this.opts.offCanvas){var r=this,a=this.opts.dropdown,p=this.conf.dropdown;if(i=t.mmenu.glbl,"boolean"==typeof a&&a&&(a={drop:a}),"object"!=typeof a&&(a={}),"string"==typeof a.position&&(a.position={of:a.position}),(a=this.opts.dropdown=t.extend(!0,{},t.mmenu.defaults.dropdown,a)).drop){var f;this.bind("initMenu:after",function(){if(this.$menu.addClass(o.menu+"_"+s),"string"!=typeof a.position.of){var e=this._getOriginalMenuId();e&&e.length&&(a.position.of='[href="#'+e+'"]')}"string"==typeof a.position.of&&(f=t(a.position.of),a.event=a.event.split(" "),1==a.event.length&&(a.event[1]=a.event[0]),"hover"==a.event[0]&&f.on(n.mouseenter+"-"+s,function(){r.open()}),"hover"==a.event[1]&&this.$menu.on(n.mouseleave+"-"+s,function(){r.close()}))}),this.bind("open:start",function(){this.$menu.data(e.style,this.$menu.attr("style")||""),i.$html.addClass(o.wrapper+"_dropdown")}),this.bind("close:finish",function(){this.$menu.attr("style",this.$menu.data(e.style)),i.$html.removeClass(o.wrapper+"_dropdown")});var d=function(t,e){var n,s,r=e[0],d=e[1],u="x"==t?"scrollLeft":"scrollTop",l="x"==t?"outerWidth":"outerHeight",h="x"==t?"left":"top",m="x"==t?"right":"bottom",c="x"==t?"width":"height",w="x"==t?"maxWidth":"maxHeight",v=null,x=i.$wndw[u](),b=f.offset()[h]-=x,g=b+f[l](),$=i.$wndw[c](),y=p.offset.button[t]+p.offset.viewport[t];if(a.position[t])switch(a.position[t]){case"left":case"bottom":v="after";break;case"right":case"top":v="before"}return null===v&&(v=b+(g-b)/2<$/2?"after":"before"),"after"==v?(s=$-((n="x"==t?b:g)+y),r[h]=n+p.offset.button[t],r[m]="auto",a.tip&&d.push(o.menu+"_tip-"+("x"==t?"left":"top"))):(s=(n="x"==t?g:b)-y,r[m]="calc( 100% - "+(n-p.offset.button[t])+"px )",r[h]="auto",a.tip&&d.push(o.menu+"_tip-"+("x"==t?"right":"bottom"))),a.fitViewport&&(r[w]=Math.min(p[c].max,s)),[r,d]},u=function(t){if(this.vars.opened){this.$menu.attr("style",this.$menu.data(e.style));var n=[{},[]];n=d.call(this,"y",n),n=d.call(this,"x",n),this.$menu.css(n[0]),a.tip&&this.$menu.removeClass(o.tipleft+" "+o.tipright+" "+o.tiptop+" "+o.tipbottom).addClass(n[1].join(" "))}};this.bind("open:start",u),i.$wndw.on(n.resize+"-"+s,function(t){u.call(r)}),this.opts.offCanvas.blockUI||i.$wndw.on(n.scroll+"-"+s,function(t){u.call(r)})}}},add:function(){o=t.mmenu._c,e=t.mmenu._d,n=t.mmenu._e,o.add("dropdown"),n.add("mouseenter mouseleave resize scroll")},clickAnchor:function(t,o){}},t.mmenu.defaults.dropdown={drop:!1,fitViewport:!0,event:"click",position:{},tip:!0},t.mmenu.configuration.dropdown={offset:{button:{x:-5,y:5},viewport:{x:20,y:20}},height:{max:880},width:{max:440}}}(jQuery);
    !function(s){var t,e,n="fixedElements";s.mmenu.addons[n]={setup:function(){if(this.opts.offCanvas){this.opts[n];var i=this.conf[n];e=s.mmenu.glbl;this.bind("setPage:after",function(o){var c=this.conf.classNames[n].fixed,f=o.find("."+c);this.__refactorClass(f,c,t.slideout),f[i.elemInsertMethod](i.elemInsertSelector);var a=this.conf.classNames[n].sticky,d=o.find("."+a);this.__refactorClass(d,a,t.sticky),(d=o.find("."+t.sticky)).length&&(this.bind("open:start",function(){if("hidden"==e.$html.css("overflow")){var t=e.$wndw.scrollTop()+i.sticky.offset;d.each(function(){s(this).css("top",parseInt(s(this).css("top"),10)+t)})}}),this.bind("close:finish",function(){d.css("top","")}))})}},add:function(){t=s.mmenu._c,s.mmenu._d,s.mmenu._e,t.add("sticky")},clickAnchor:function(s,t){}},s.mmenu.configuration[n]={sticky:{offset:0},elemInsertMethod:"appendTo",elemInsertSelector:"body"},s.mmenu.configuration.classNames[n]={fixed:"Fixed",sticky:"Sticky"}}(jQuery);
    !function(a){var n,e,t;a.mmenu.addons.iconbar={setup:function(){var i=this,o=this.opts.iconbar;this.conf.iconbar;if(a.mmenu.glbl,o instanceof Array&&(o={add:!0,top:o}),o.add){var r=null;if(a.each(["top","bottom"],function(e,t){var i=o[t];i instanceof Array||(i=[i]);for(var s=a('<div class="'+n.iconbar+"__"+t+'" />'),c=0,d=i.length;c<d;c++)s.append(i[c]);s.children().length&&(r||(r=a('<div class="'+n.iconbar+'" />')),r.append(s))}),r&&(this.bind("initMenu:after",function(){var a=n.menu+"_iconbar";o.size&&(a+=" "+n.menu+"_iconbar-"+o.size),this.$menu.addClass(a).prepend(r)}),"tabs"==o.type)){r.addClass(n.iconbar+"_tabs");var s=r.find("a");s.on(t.click+"-iconbar",function(e){var t=a(this);if(t.hasClass(n.iconbar+"__tab_selected"))e.stopImmediatePropagation();else try{var o=a(t.attr("href"));o.hasClass(n.panel)&&(e.preventDefault(),e.stopImmediatePropagation(),i.openPanel(o,!1))}catch(a){}}),this.bind("openPanel:start",function a(t){s.removeClass(n.iconbar+"__tab_selected");var i=s.filter('[href="#'+t.attr("id")+'"]');if(i.length)i.addClass(n.iconbar+"__tab_selected");else{var o=t.data(e.parent);o&&o.length&&a(o.closest("."+n.panel))}})}}},add:function(){n=a.mmenu._c,e=a.mmenu._d,t=a.mmenu._e,n.add("iconbar")},clickAnchor:function(a,n){}},a.mmenu.defaults.iconbar={add:!1,top:[],bottom:[]},a.mmenu.configuration.iconbar={}}(jQuery);
    !function(e){var i,n="iconPanels";e.mmenu.addons[n]={setup:function(){var a=this,t=this.opts[n],l=(this.conf[n],!1);e.mmenu.glbl,"boolean"==typeof t&&(t={add:t}),"number"!=typeof t&&"string"!=typeof t||(t={add:!0,visible:t}),"object"!=typeof t&&(t={}),"first"==t.visible&&(l=!0,t.visible=1),(t=this.opts[n]=e.extend(!0,{},e.mmenu.defaults[n],t)).visible=Math.min(3,Math.max(1,t.visible)),t.visible++;var s="";if(!l){for(var d=0;d<=t.visible;d++)s+=" "+i.panel+"_iconpanel-"+d;s.length&&(s=s.slice(1))}if(t.add){var r=function(n){if(!n.parent("."+i.listitem+"_vertical").length){var d=a.$pnls.children("."+i.panel);l?d.removeClass(i.panel+"_iconpanel-first").first().addClass(i.panel+"_iconpanel-first"):d.removeClass(s).filter("."+i.panel+"_opened-parent").removeClass(i.hidden).not(function(){return e(this).parent("."+i.listitem+"_vertical").length}).add(n).slice(-t.visible).each(function(n){e(this).addClass(i.panel+"_iconpanel-"+n)})}};this.bind("initMenu:after",function(){var e=[i.menu+"_iconpanel"];t.size&&e.push(i.menu+"_iconpanel-"+t.size),t.hideNavbar&&e.push(i.menu+"_hidenavbar"),t.hideDivider&&e.push(i.menu+"_hidedivider"),this.$menu.addClass(e.join(" "))}),this.bind("openPanel:start",r),this.bind("initPanels:after",function(e){r.call(a,a.$pnls.children("."+i.panel+"_opened"))}),this.bind("initListview:after",function(e){!t.blockPanel||e.parent("."+i.listitem+"_vertical").length||e.children("."+i.panel+"__blocker").length||e.prepend('<a href="#'+e.closest("."+i.panel).attr("id")+'" class="'+i.panel+'__blocker" />')})}},add:function(){i=e.mmenu._c,e.mmenu._d,e.mmenu._e},clickAnchor:function(e,i){}},e.mmenu.defaults[n]={add:!1,blockPanel:!0,hideDivider:!1,hideNavbar:!0,visible:3}}(jQuery);
    !function(n){var e,t,a,i,s="keyboardNavigation";n.mmenu.addons[s]={setup:function(){if(!n.mmenu.support.touch){var t=this.opts[s];this.conf[s];if(i=n.mmenu.glbl,"boolean"!=typeof t&&"string"!=typeof t||(t={enable:t}),"object"!=typeof t&&(t={}),(t=this.opts[s]=n.extend(!0,{},n.mmenu.defaults[s],t)).enable){var a=n('<button class="'+e.tabstart+'" />'),o=n('<button class="'+e.tabend+'" />'),r=n('<button class="'+e.tabend+'" />');this.bind("initMenu:after",function(){t.enhance&&this.$menu.addClass(e.menu+"_keyboardfocus"),this["_initWindow_"+s](t.enhance)}),this.bind("initOpened:before",function(){this.$menu.prepend(a).append(o).children("."+e.mm("navbars-top")+", ."+e.mm("navbars-bottom")).children("."+e.navbar).children("a."+e.title).attr("tabindex",-1)}),this.bind("initBlocker:after",function(){i.$blck.append(r).children("a").addClass(e.tabstart)}),this.bind("open:finish",function(){d.call(this,null,t.enable)}),this.bind("openPanel:finish",function(n){d.call(this,n,t.enable)}),this.bind("initOpened:after:sr-aria",function(){var n=this.$menu.add(i.$blck).children("."+e.tabstart+", ."+e.tabend);this.__sr_aria(n,"hidden",!0),this.__sr_role(n,"presentation")})}}},add:function(){e=n.mmenu._c,t=n.mmenu._d,a=n.mmenu._e,e.add("tabstart tabend"),a.add("focusin keydown")},clickAnchor:function(n,e){}},n.mmenu.defaults[s]={enable:!1,enhance:!1},n.mmenu.configuration[s]={},n.mmenu.prototype["_initWindow_"+s]=function(o){i.$wndw.off(a.keydown+"-offCanvas"),i.$wndw.off(a.focusin+"-"+s).on(a.focusin+"-"+s,function(t){if(i.$html.hasClass(e.wrapper+"_opened")){var a=n(t.target);if(a.is("."+e.tabend)){var s=n();a.parent().is("."+e.menu)&&i.$blck&&(s=i.$blck),a.parent().is("."+e.wrapper+"__blocker")&&(s=i.$body.find("."+e.menu+"_offcanvas").filter("."+e.menu+"_opened")),s.length||(s=a.parent()),s.children("."+e.tabstart).focus()}}}),i.$wndw.off(a.keydown+"-"+s).on(a.keydown+"-"+s,function(t){var i=n(t.target),s=i.closest("."+e.menu);if(s.length){s.data("mmenu");if(i.is("input, textarea"));else switch(t.keyCode){case 13:(i.is(".mm-toggle")||i.is(".mm-check"))&&i.trigger(a.click);break;case 32:case 37:case 38:case 39:case 40:t.preventDefault()}}}),o&&i.$wndw.off(a.keydown+"-"+s).on(a.keydown+"-"+s,function(a){var i=n(a.target),s=i.closest("."+e.menu);if(s.length){var o=s.data("mmenu");if(i.is("input"))switch(a.keyCode){case 27:i.val("")}else switch(a.keyCode){case 8:var d=s.find("."+e.panel+"_opened").data(t.parent);d&&d.length&&o.openPanel(d.closest("."+e.panel));break;case 27:s.hasClass(e.menu+"_offcanvas")&&o.close()}}})};var o="input, select, textarea, button, label, a[href]";function d(t,a){t=t||this.$pnls.children("."+e.panel+"_opened");var i=n(),s=this.$menu.children("."+e.mm("navbars_top")+", ."+e.mm("navbars_bottom")).children("."+e.navbar);s.find(o).filter(":focus").length||("default"==a&&((i=t.children("."+e.listview).find("a[href]").not("."+e.hidden)).length||(i=t.find(o).not("."+e.hidden)),i.length||(i=s.find(o).not("."+e.hidden))),i.length||(i=this.$menu.children("."+e.tabstart)),i.first().focus())}}(jQuery);
    !function(n){var e,i="lazySubmenus";n.mmenu.addons[i]={setup:function(){var l=this.opts[i];this.conf[i];n.mmenu.glbl,"boolean"==typeof l&&(l={load:l}),"object"!=typeof l&&(l={}),(l=this.opts[i]=n.extend(!0,{},n.mmenu.defaults[i],l)).load&&(this.bind("initMenu:after",function(){this.$pnls.find("li").children(this.conf.panelNodetype).not("."+e.inset).not("."+e.nolistview).not("."+e.nopanel).addClass(e.panel+"_lazysubmenu "+e.nolistview+" "+e.nopanel)}),this.bind("initPanels:before",function(n){n=n||this.$pnls.children(this.conf.panelNodetype),this.__findAddBack(n,"."+e.panel+"_lazysubmenu").not("."+e.panel+"_lazysubmenu ."+e.panel+"_lazysubmenu").removeClass(e.panel+"_lazysubmenu "+e.nolistview+" "+e.nopanel)}),this.bind("initOpened:before",function(){var n=this.$pnls.find("."+this.conf.classNames.selected).parents("."+e.panel+"_lazysubmenu");n.length&&(n.removeClass(e.panel+"_lazysubmenu "+e.nolistview+" "+e.nopanel),this.initPanels(n.last()))}),this.bind("openPanel:before",function(n){var i=this.__findAddBack(n,"."+e.panel+"_lazysubmenu").not("."+e.panel+"_lazysubmenu ."+e.panel+"_lazysubmenu");i.length&&this.initPanels(i)}))},add:function(){e=n.mmenu._c,n.mmenu._d,n.mmenu._e},clickAnchor:function(n,e){}},n.mmenu.defaults[i]={load:!1},n.mmenu.configuration[i]={}}(jQuery);
    !function(n){var a;n.mmenu.addons.navbars={setup:function(){var t=this,e=this.opts.navbars,o=this.conf.navbars;if(n.mmenu.glbl,void 0!==e){e instanceof Array||(e=[e]);var r={},s={};e.length&&(n.each(e,function(i){var c=e[i];"boolean"==typeof c&&c&&(c={}),"object"!=typeof c&&(c={}),void 0===c.content&&(c.content=["prev","title"]),c.content instanceof Array||(c.content=[c.content]),c=n.extend(!0,{},t.opts.navbar,c);var d=n('<div class="'+a.navbar+'" />'),v=c.height;"number"!=typeof v?v=1:(v=Math.min(4,Math.max(1,v)))>1&&d.addClass(a.navbar+"_size-"+v);var m=c.position;switch(m){case"bottom":break;default:m="top"}r[m]||(r[m]=0),r[m]+=v,s[m]||(s[m]=n('<div class="'+a.navbars+"_"+m+'" />')),s[m].append(d);for(var u=0,b=c.content.length;u<b;u++){var l=n.mmenu.addons.navbars[c.content[u]]||null;l?l.call(t,d,c,o):((l=c.content[u])instanceof n||(l=n(c.content[u])),d.append(l))}var f=n.mmenu.addons.navbars[c.type]||null;f&&f.call(t,d,c,o),d.children("."+a.btn).length&&d.addClass(a.navbar+"_has-btns")}),this.bind("initMenu:after",function(){for(var n in r)this.$menu.addClass(a.menu+"_navbar_"+n+"-"+r[n]),this.$menu["bottom"==n?"append":"prepend"](s[n])}))}},add:function(){a=n.mmenu._c,n.mmenu._d,n.mmenu._e,a.add("navbars")},clickAnchor:function(n,a){}},n.mmenu.configuration.navbars={breadcrumbs:{separator:"/",removeFirst:!1}},n.mmenu.configuration.classNames.navbars={}}(jQuery);
    !function(e){var t,n,i,s="pageScroll";e.mmenu.addons[s]={setup:function(){var r=this,o=this.opts[s],a=this.conf[s];if(i=e.mmenu.glbl,"boolean"==typeof o&&(o={scroll:o}),(o=this.opts[s]=e.extend(!0,{},e.mmenu.defaults[s],o)).scroll&&this.bind("close:finish",function(){l(a.scrollOffset)}),o.update){var c=[],d=[];(r=this).bind("initListview:after",function(n){r.__filterListItemAnchors(n.find("."+t.listview).children("li")).each(function(){var t=e(this).attr("href");f(t)&&c.push(t)}),d=c.reverse()});var u=-1;i.$wndw.on(n.scroll+"-"+s,function(n){for(var s=i.$wndw.scrollTop(),l=0;l<d.length;l++)if(e(d[l]).offset().top<s+a.updateOffset){u!==l&&(u=l,r.setSelected(r.__filterListItemAnchors(r.$pnls.children("."+t.panel+"_opened").find("."+t.listview).children("li")).filter('[href="'+d[l]+'"]').parent()));break}})}},add:function(){t=e.mmenu._c,e.mmenu._d,n=e.mmenu._e},clickAnchor:function(n,o,a){if(r=!1,o&&a&&this.opts.offCanvas&&this.opts[s].scroll&&i.$page&&i.$page.length){var c=n.attr("href");if(f(c)){if(r=e(c),!this.$menu.is("."+t.menu+"_sidebar-expanded")||!i.$html.is("."+t.wrapper+"_sidebar-expanded"))return{close:!0};l(this.conf[s].scrollOffset)}}}},e.mmenu.defaults[s]={scroll:!1,update:!1},e.mmenu.configuration[s]={scrollOffset:0,updateOffset:50};var r=!1;function l(e){r&&r.length&&r.is(":visible")&&i.$html.add(i.$body).animate({scrollTop:r.offset().top+e}),r=!1}function f(e){try{return!("#"==e||"#"!=e.slice(0,1)||!i.$page.find(e).length)}catch(e){return!1}}}(jQuery);
    !function(e){var n,s,a,t="searchfield";function i(e,n){if(n)for(var s in n)e.attr(s,n[s])}e.mmenu.addons[t]={setup:function(){var s=this,a=this.opts[t],i=this.conf[t];e.mmenu.glbl,"boolean"==typeof a&&(a={add:a}),"object"!=typeof a&&(a={}),"boolean"==typeof a.panel&&(a.panel={add:a.panel}),"object"!=typeof a.panel&&(a.panel={}),a.add&&("panel"==a.addTo&&(a.panel.add=!0),a.panel.add&&(a.showSubPanels=!1,a.panel.splash&&(a.cancel=!0)),a=this.opts[t]=e.extend(!0,{},e.mmenu.defaults[t],a),i=this.conf[t]=e.extend(!0,{},e.mmenu.configuration[t],i),this.bind("close:start",function(){this.$menu.find("."+n.searchfield).children("input").blur()}),this.bind("initPanels:after",function(n){var t,i=e();switch(a.panel.add&&(i=this._initSearchPanel(n)),a.addTo){case"panels":t=n;break;case"panel":t=i;break;default:t=this.$menu.find(a.addTo)}(t.each(function(){var n=s._initSearchfield(e(this));a.search&&n.length&&s._initSearching(n)}),a.noResults)&&(a.panel.add?i:n).each(function(){s._initNoResultsMsg(e(this))})}))},add:function(){n=e.mmenu._c,s=e.mmenu._d,a=e.mmenu._e,n.add("searchfield"),s.add("searchfield"),a.add("input focus blur")},clickAnchor:function(e,s){if(e.hasClass(n.searchfield+"__btn")){if(e.hasClass(n.btn+"_close")){var a=e.closest("."+n.searchfield).find("input");return a.val(""),this.search(a),!0}if(e.hasClass(n.btn+"_next"))return e.closest("."+n.searchfield).submit(),!0}}},e.mmenu.defaults[t]={add:!1,addTo:"panels",noResults:"No results found.",placeholder:"Search",panel:{add:!1,dividers:!0,fx:"none",id:null,splash:null,title:"Search"},search:!0,showTextItems:!1,showSubPanels:!0},e.mmenu.configuration[t]={clear:!1,form:!1,input:!1,submit:!1},e.mmenu.prototype._initSearchPanel=function(s){var a=this.opts[t];this.conf[t];if(this.$pnls.children("."+n.panel+"_search").length)return e();var i=e('<div class="'+n.panel+'_search " />').append("<ul />").appendTo(this.$pnls);switch(a.panel.id&&i.attr("id",a.panel.id),a.panel.title&&i.attr("data-mm-title",a.panel.title),a.panel.fx){case!1:break;case"none":i.addClass(n.panel+"_noanimation");break;default:i.addClass(n.panel+"_fx-"+a.panel.fx)}return a.panel.splash&&i.append('<div class="'+n.panel+'__searchsplash">'+a.panel.splash+"</div>"),this._initPanels(i),i},e.mmenu.prototype._initSearchfield=function(s){var a=this.opts[t],l=this.conf[t];if(s.parent("."+n.listitem+"_vertical").length)return e();if(s.find("."+n.searchfield).length)return s.find("."+n.searchfield);var d=e("<"+(l.form?"form":"div")+' class="'+n.searchfield+'" />'),h=e('<div class="'+n.searchfield+'__input" />'),r=e('<input placeholder="'+this.i18n(a.placeholder)+'" type="text" autocomplete="off" />');return h.append(r).appendTo(d),s.prepend(d),s.hasClass(n.panel)&&s.addClass(n.panel+"_has-searchfield"),i(r,l.input),l.clear&&e('<a class="'+n.btn+" "+n.btn+"_close "+n.searchfield+'__btn" href="#" />').appendTo(h),i(d,l.form),l.form&&l.submit&&!l.clear&&e('<a class="'+n.btn+" "+n.btn+"_next "+n.searchfield+'__btn" href="#" />').appendTo(h),a.cancel&&e('<a href="#" class="'+n.searchfield+'__cancel">'+this.i18n("cancel")+"</a>").appendTo(d),d},e.mmenu.prototype._initSearching=function(i){var l=this,d=this.opts[t],h=(this.conf[t],{});i.closest("."+n.panel+"_search").length?(h.$pnls=this.$pnls.find("."+n.panel),h.$nrsp=i.closest("."+n.panel)):i.closest("."+n.panel).length?(h.$pnls=i.closest("."+n.panel),h.$nrsp=h.$pnls):(h.$pnls=this.$pnls.find("."+n.panel),h.$nrsp=this.$menu),h.$pnls=h.$pnls.not(function(){return e(this).parent("."+n.listitem+"_vertical").length}),d.panel.add&&(h.$pnls=h.$pnls.not("."+n.panel+"_search"));var r=i.find("input"),c=i.find("."+n.searchfield+"__cancel"),p=this.$pnls.children("."+n.panel+"_search"),o=h.$pnls.find("."+n.listitem);h.$itms=o.not("."+n.listitem+"_divider"),h.$dvdr=o.filter("."+n.listitem+"_divider"),d.panel.add&&d.panel.splash&&r.off(a.focus+"-"+t+"-splash").on(a.focus+"-"+t+"-splash",function(e){l.openPanel(p)}),d.cancel&&(r.off(a.focus+"-"+t+"-cancel").on(a.focus+"-"+t+"-cancel",function(e){c.addClass(n.searchfield+"__cancel-active")}),c.off(a.click+"-"+t+"-splash").on(a.click+"-"+t+"-splash",function(s){s.preventDefault(),e(this).removeClass(n.searchfield+"__cancel-active"),p.hasClass(n.panel+"_opened")&&l.openPanel(l.$pnls.children("."+n.panel+"_opened-parent").last())})),d.panel.add&&"panel"==d.addTo&&this.bind("openPanel:finish",function(e){e[0]===p[0]&&r.focus()}),r.data(s.searchfield,h).off(a.input+"-"+t).on(a.input+"-"+t,function(e){(function(e){switch(e){case 9:case 16:case 17:case 18:case 37:case 38:case 39:case 40:return!0}return!1})(e.keyCode)||l.search(r)}),this.search(r)},e.mmenu.prototype._initNoResultsMsg=function(s){var a=this.opts[t];this.conf[t];if(s.closest("."+n.panel).length||(s=this.$pnls.children("."+n.panel).first()),!s.children("."+n.panel+"__noresultsmsg").length){var i=s.children("."+n.listview).first(),l=e('<div class="'+n.panel+"__noresultsmsg "+n.hidden+'" />').append(this.i18n(a.noResults));i.length?l.insertAfter(i):l.prependTo(s)}},e.mmenu.prototype.search=function(a,i){var l=this,d=this.opts[t];this.conf[t];a=a||this.$menu.find("."+n.searchfield).chidren("input").first(),i=(i=i||a.val()).toLowerCase().trim();var h=a.data(s.searchfield),r=a.closest("."+n.searchfield).find("."+n.btn),c=this.$pnls.children("."+n.panel+"_search"),p=h.$pnls,o=h.$itms,f=h.$dvdr,u=h.$nrsp;if(o.removeClass(n.listitem+"_nosubitems").find("."+n.btn+"_fullwidth-search").removeClass(n.btn+"_fullwidth-search "+n.btn+"_fullwidth"),c.children("."+n.listview).empty(),p.scrollTop(0),i.length){if(o.add(f).addClass(n.hidden),o.each(function(){var s=e(this),a="a";(d.showTextItems||d.showSubPanels&&s.find("."+n.btn+"_next"))&&(a="a, span"),s.children(a).not("."+n.btn+"_next").text().toLowerCase().indexOf(i)>-1&&s.removeClass(n.hidden)}),d.panel.add){var m=e();p.each(function(){var s=l.__filterListItems(e(this).find("."+n.listitem)).clone(!0);s.length&&(d.panel.dividers&&(m=m.add('<li class="'+n.listitem+" "+n.listitem+'_divider">'+e(this).find("."+n.navbar+"__title").text()+"</li>")),m=m.add(s))}),m.find("."+n.mm("toggle")).remove().end().find("."+n.mm("check")).remove().end().find("."+n.btn).remove(),c.children("."+n.listview).append(m),this.openPanel(c)}else d.showSubPanels&&p.each(function(a){var t=e(this);l.__filterListItems(t.find("."+n.listitem)).each(function(){var a=e(this).data(s.child);a&&a.find("."+n.listview).children().removeClass(n.hidden)})}),e(p.get().reverse()).each(function(t){var i=e(this),d=i.data(s.parent);d&&(l.__filterListItems(i.find("."+n.listitem)).length?d.hasClass(n.hidden)&&d.removeClass(n.hidden).children("."+n.btn+"_next").not("."+n.btn+"_fullwidth").addClass(n.btn+"_fullwidth").addClass(n.btn+"_fullwidth-search"):a.closest("."+n.panel).length||((i.hasClass(n.panel+"_opened")||i.hasClass(n.panel+"_opened-parent"))&&setTimeout(function(){l.openPanel(d.closest("."+n.panel))},(t+1)*(1.5*l.conf.openingInterval)),d.addClass(n.listitem+"_nosubitems")))}),this.__filterListItems(p.find("."+n.listitem)).each(function(){e(this).prevAll("."+n.listitem+"_divider").first().removeClass(n.hidden)});r.removeClass(n.hidden),u.find("."+n.panel+"__noresultsmsg")[o.not("."+n.hidden).length?"addClass":"removeClass"](n.hidden),d.panel.add&&(d.panel.splash&&c.find("."+n.panel+"__searchsplash").addClass(n.hidden),o.add(f).removeClass(n.hidden))}else o.add(f).removeClass(n.hidden),r.addClass(n.hidden),u.find("."+n.panel+"__noresultsmsg").addClass(n.hidden),d.panel.add&&(d.panel.splash?c.find("."+n.panel+"__searchsplash").removeClass(n.hidden):a.closest("."+n.panel+"_search").length||this.openPanel(this.$pnls.children("."+n.panel+"_opened-parent").last()));this.trigger("updateListview")}}(jQuery);
    !function(e){var a,n,i="sectionIndexer";e.mmenu.addons[i]={setup:function(){var r=this,t=this.opts[i];this.conf[i];e.mmenu.glbl,"boolean"==typeof t&&(t={add:t}),"object"!=typeof t&&(t={}),t=this.opts[i]=e.extend(!0,{},e.mmenu.defaults[i],t);var s=null;this.bind("initPanels:after",function(d){if(t.add){var h;switch(t.addTo){case"panels":h=d;break;default:h=(h=e(t.addTo,this.$menu)).filter("."+a.panel)}h.find("."+a.listitem+"_divider").closest("."+a.panel).addClass(a.panel+"_has-sectionindexer"),s||(s=e('<div class="'+a.sectionindexer+'" />').prependTo(this.$menu).append('<a href="#a">a</a><a href="#b">b</a><a href="#c">c</a><a href="#d">d</a><a href="#e">e</a><a href="#f">f</a><a href="#g">g</a><a href="#h">h</a><a href="#i">i</a><a href="#j">j</a><a href="#k">k</a><a href="#l">l</a><a href="#m">m</a><a href="#n">n</a><a href="#o">o</a><a href="#p">p</a><a href="#q">q</a><a href="#r">r</a><a href="#s">s</a><a href="#t">t</a><a href="#u">u</a><a href="#v">v</a><a href="#w">w</a><a href="#x">x</a><a href="#y">y</a><a href="#z">z</a>')).on(n.mouseover+"-"+i+" "+n.touchstart+"-"+i,"a",function(n){var i=e(n.target).attr("href").slice(1),t=r.$pnls.children("."+a.panel+"_opened"),s=t.find("."+a.listview),d=-1,h=t.scrollTop();t.scrollTop(0),s.children("."+a.listitem+"_divider").not("."+a.hidden).each(function(){d<0&&i==e(this).text().slice(0,1).toLowerCase()&&(d=e(this).position().top)}),t.scrollTop(d>-1?d:h)});var o=function(e){e=e||this.$pnls.children("."+a.panel+"_opened"),this.$menu[(e.hasClass(a.panel+"_has-sectionindexer")?"add":"remove")+"Class"](a.menu+"_has-sectionindexer")};this.bind("openPanel:start",o),this.bind("initPanels:after",o)}})},add:function(){a=e.mmenu._c,e.mmenu._d,n=e.mmenu._e,a.add("sectionindexer"),n.add("mouseover")},clickAnchor:function(e,n){if(e.parent().is("."+a.indexer))return!0}},e.mmenu.defaults[i]={add:!1,addTo:"panels"}}(jQuery);
    !function(e){var t,n,i="setSelected";e.mmenu.addons[i]={setup:function(){var s=this,a=this.opts[i];this.conf[i];if(e.mmenu.glbl,"boolean"==typeof a&&(a={hover:a,parent:a}),"object"!=typeof a&&(a={}),"detect"==(a=this.opts[i]=e.extend(!0,{},e.mmenu.defaults[i],a)).current){var l=function(e){e=e.split("?")[0].split("#")[0];var t=s.$menu.find('a[href="'+e+'"], a[href="'+e+'/"]');t.length?s.setSelected(t.parent(),!0):(e=e.split("/").slice(0,-1)).length&&l(e.join("/"))};this.bind("initMenu:after",function(){l(window.location.href)})}else a.current||this.bind("initListview:after",function(e){e.find("."+t.listview).children("."+t.listitem+"_selected").removeClass(t.listitem+"_selected")});a.hover&&this.bind("initMenu:after",function(){this.$menu.addClass(t.menu+"_selected-hover")}),a.parent&&(this.bind("openPanel:finish",function(e){this.$pnls.find("."+t.listview).find("."+t.listitem+"_selected-parent").removeClass(t.listitem+"_selected-parent");for(var i=e.data(n.parent);i;)i.not("."+t.listitem+"_vertical").addClass(t.listitem+"_selected-parent"),i=i.closest("."+t.panel).data(n.parent)}),this.bind("initMenu:after",function(){this.$menu.addClass(t.menu+"_selected-parent")}))},add:function(){t=e.mmenu._c,n=e.mmenu._d,e.mmenu._e},clickAnchor:function(e,t){}},e.mmenu.defaults[i]={current:!0,hover:!1,parent:!1}}(jQuery);
    !function(e){var d,s;e.mmenu.addons.sidebar={setup:function(){if(this.opts.offCanvas){var a=this.opts.sidebar;this.conf.sidebar;s=e.mmenu.glbl,("string"==typeof a||"boolean"==typeof a&&a||"number"==typeof a)&&(a={expanded:a}),"object"!=typeof a&&(a={}),"boolean"==typeof a.collapsed&&a.collapsed&&(a.collapsed="all"),"string"!=typeof a.collapsed&&"number"!=typeof a.collapsed||(a.collapsed={use:a.collapsed}),"object"!=typeof a.collapsed&&(a.collapsed={}),"number"==typeof a.collapsed.use&&(a.collapsed.use="(min-width: "+a.collapsed.use+"px)"),"boolean"==typeof a.expanded&&a.expanded&&(a.expanded="all"),"string"!=typeof a.expanded&&"number"!=typeof a.expanded||(a.expanded={use:a.expanded}),"object"!=typeof a.expanded&&(a.expanded={}),"number"==typeof a.expanded.use&&(a.expanded.use="(min-width: "+a.expanded.use+"px)"),a=this.opts.sidebar=e.extend(!0,{},e.mmenu.defaults.sidebar,a);var n=d.wrapper+"_sidebar-collapsed";a.collapsed.size&&(n+=" "+d.wrapper+"_sidebar-collapsed-"+a.collapsed.size);var i=d.wrapper+"_sidebar-expanded";a.expanded.size&&(i+=" "+d.wrapper+"_sidebar-expanded-"+a.expanded.size),a.collapsed.use&&(this.bind("initMenu:after",function(){this.$menu.addClass(d.menu+"_sidebar-collapsed"),a.collapsed.blockMenu&&this.opts.offCanvas&&!this.$menu.children("."+d.menu+"__blocker").length&&this.$menu.prepend('<a class="'+d.menu+'__blocker" href="#'+this.$menu.attr("id")+'" />'),a.collapsed.hideNavbar&&this.$menu.addClass(d.menu+"_hidenavbar"),a.collapsed.hideDivider&&this.$menu.addClass(d.menu+"_hidedivider")}),"boolean"==typeof a.collapsed.use?this.bind("initMenu:after",function(){s.$html.addClass(n)}):this.matchMedia(a.collapsed.use,function(){s.$html.addClass(n)},function(){s.$html.removeClass(n)})),a.expanded.use&&(this.bind("initMenu:after",function(){this.$menu.addClass(d.menu+"_sidebar-expanded")}),"boolean"==typeof a.expanded.use?this.bind("initMenu:after",function(){s.$html.addClass(i),this.open()}):this.matchMedia(a.expanded.use,function(){s.$html.addClass(i),s.$html.hasClass(d.wrapper+"_sidebar-closed")||this.open()},function(){s.$html.removeClass(i),this.close()}),this.bind("close:start",function(){s.$html.hasClass(i)&&s.$html.addClass(d.wrapper+"_sidebar-closed")}),this.bind("open:start",function(){s.$html.removeClass(d.wrapper+"_sidebar-closed")}))}},add:function(){d=e.mmenu._c,e.mmenu._d,e.mmenu._e},clickAnchor:function(e,a,n){if(this.opts.sidebar.expanded.use&&s.$html.is("."+d.wrapper+"_sidebar-expanded")&&a&&n)return{close:!1}}},e.mmenu.defaults.sidebar={collapsed:{use:!1,blockMenu:!0,hideDivider:!1,hideNavbar:!0},expanded:{use:!1}},e.mmenu.configuration.sidebar={}}(jQuery);
    !function(e){var t;e.mmenu.addons.toggles={setup:function(){var s=this;this.opts.toggles,this.conf.toggles;e.mmenu.glbl,this.bind("initPanels:after",function(n){this.__refactorClass(n.find("input"),this.conf.classNames.toggles.toggle,t.toggle),this.__refactorClass(n.find("input"),this.conf.classNames.toggles.check,t.check),n.find("input."+t.toggle+", input."+t.check).each(function(){var n=e(this),l=n.closest("li"),c=n.hasClass(t.toggle)?"toggle":"check",i=n.attr("id")||s.__getUniqueId();l.children('label[for="'+i+'"]').length||(n.attr("id",i),l.prepend(n),e('<label for="'+i+'" class="'+t[c]+'"></label>').insertAfter(l.children("."+t.listitem+"__text").last()))})})},add:function(){t=e.mmenu._c,e.mmenu._d,e.mmenu._e,t.add("toggle check")},clickAnchor:function(e,t){}},e.mmenu.configuration.classNames.toggles={toggle:"Toggle",check:"Check"}}(jQuery);
    !function(a){a.mmenu.addons.navbars.breadcrumbs=function(r,n,e){var s=this,t=a.mmenu._c,i=a.mmenu._d;t.add("separator");var b=a('<span class="'+t.navbar+'__breadcrumbs" />').appendTo(r);this.bind("initNavbar:after",function(r){if(!r.children("."+t.navbar).children("."+t.navbar+"__breadcrumbs").length){r.removeClass(t.panel+"_has-navbar");for(var n=[],s=a('<span class="'+t.navbar+'__breadcrumbs"></span>'),b=r,c=!0;b&&b.length;){if(b.is("."+t.panel)||(b=b.closest("."+t.panel)),!b.parent("."+t.listitem+"_vertical").length){var d=b.children("."+t.navbar).children("."+t.navbar+"__title").text();d.length&&n.unshift(c?"<span>"+d+"</span>":'<a href="#'+b.attr("id")+'">'+d+"</a>"),c=!1}b=b.data(i.parent)}e.breadcrumbs.removeFirst&&n.shift(),s.append(n.join('<span class="'+t.separator+'">'+e.breadcrumbs.separator+"</span>")).appendTo(r.children("."+t.navbar))}}),this.bind("openPanel:start",function(a){var r=a.find("."+t.navbar+"__breadcrumbs");r.length&&b.html(r.html()||"")}),this.bind("initNavbar:after:sr-aria",function(r){r.children("."+t.navbar).children("."+t.breadcrumbs).children("a").each(function(){s.__sr_aria(a(this),"owns",a(this).attr("href").slice(1))})})}}(jQuery);
    !function(t){t.mmenu.addons.navbars.close=function(e,n){var s=t.mmenu._c;t.mmenu.glbl;s.add("close");var a=t('<a class="'+s.btn+" "+s.btn+"_close "+s.navbar+'__btn" href="#" />').appendTo(e);this.bind("setPage:after",function(t){a.attr("href","#"+t.attr("id"))}),this.bind("setPage:after:sr-text",function(t){a.html(this.__sr_text(this.i18n(this.conf.screenReader.text.closeMenu))),this.__sr_aria(a,"owns",a.attr("href").slice(1))})}}(jQuery);
    !function(a){a.mmenu.addons.navbars.next=function(n,t){var e,s,r,i=a.mmenu._c,h=a('<a class="'+i.btn+" "+i.btn+"_next "+i.navbar+'__btn" href="#" />').appendTo(n);this.bind("openPanel:start",function(a){e=a.find("."+this.conf.classNames.navbars.panelNext),s=e.attr("href"),r=e.html(),s?h.attr("href",s):h.removeAttr("href"),h[s||r?"removeClass":"addClass"](i.hidden),h.html(r)}),this.bind("openPanel:start:sr-aria",function(a){this.__sr_aria(h,"hidden",h.hasClass(i.hidden)),this.__sr_aria(h,"owns",(h.attr("href")||"").slice(1))})},a.mmenu.configuration.classNames.navbars.panelNext="Next"}(jQuery);
    !function(a){a.mmenu.addons.navbars.prev=function(n,r){var e,t,i,s=a.mmenu._c,h=a('<a class="'+s.btn+" "+s.btn+"_prev "+s.navbar+'__btn" href="#" />').appendTo(n);this.bind("initNavbar:after",function(a){a.removeClass(s.panel+"_has-navbar")}),this.bind("openPanel:start",function(a){a.parent("."+s.listitem+"_vertical").length||((e=a.find("."+this.conf.classNames.navbars.panelPrev)).length||(e=a.children("."+s.navbar).children("."+s.btn+"_prev")),t=e.attr("href"),i=e.html(),t?h.attr("href",t):h.removeAttr("href"),h[t||i?"removeClass":"addClass"](s.hidden),h.html(i))}),this.bind("initNavbar:after:sr-aria",function(a){var n=a.children("."+s.navbar);this.__sr_aria(n,"hidden",!0)}),this.bind("openPanel:start:sr-aria",function(a){this.__sr_aria(h,"hidden",h.hasClass(s.hidden)),this.__sr_aria(h,"owns",(h.attr("href")||"").slice(1))})},a.mmenu.configuration.classNames.navbars.panelPrev="Prev"}(jQuery);
    !function(e){e.mmenu.addons.navbars.searchfield=function(s,t){e.mmenu._c;"object"!=typeof this.opts.searchfield&&(this.opts.searchfield={}),this.opts.searchfield.add=!0,this.opts.searchfield.addTo=s}}(jQuery);
    !function(a){a.mmenu.addons.navbars.tabs=function(e,t,n){var s=a.mmenu._c,r=a.mmenu._d,l=a.mmenu._e,d=this,i=e.children("a");e.addClass(s.navbar+"_tabs").parent().addClass(s.navbars+"_has-tabs"),i.on(l.click+"-navbars",function(e){e.preventDefault();var t=a(this);if(t.hasClass(s.navbar+"__tab_selected"))e.stopImmediatePropagation();else try{d.openPanel(a(t.attr("href")),!1),e.stopImmediatePropagation()}catch(a){}}),this.bind("openPanel:start",function a(e){i.removeClass(s.navbar+"__tab_selected");var t=i.filter('[href="#'+e.attr("id")+'"]');if(t.length)t.addClass(s.navbar+"__tab_selected");else{var n=e.data(r.parent);n&&n.length&&a(n.closest("."+s.panel))}})}}(jQuery);
    !function(t){t.mmenu.addons.navbars.title=function(a,n){var e,i,r,s,l=t.mmenu._c,h=t('<a class="'+l.navbar+'__title" />').appendTo(a);this.bind("openPanel:start",function(t){t.parent("."+l.listitem+"_vertical").length||((r=t.find("."+this.conf.classNames.navbars.panelTitle)).length||(r=t.children("."+l.navbar).children("."+l.navbar+"__title")),e=r.attr("href"),i=r.html()||n.title,e?h.attr("href",e):h.removeAttr("href"),h[e||i?"removeClass":"addClass"](l.hidden),h.html(i))}),this.bind("openPanel:start:sr-aria",function(t){if(this.opts.screenReader.text&&(s||(s=this.$menu.children("."+l.navbars+"_top, ."+l.navbars+"_bottom").children("."+l.navbar).children("."+l.btn+"_prev")),s.length)){var a=!0;"parent"==this.opts.navbar.titleLink&&(a=!s.hasClass(l.hidden)),this.__sr_aria(h,"hidden",a)}})},t.mmenu.configuration.classNames.navbars.panelTitle="Title"}(jQuery);
    jQuery.mmenu.wrappers.angular=function(){this.opts.onClick={close:!0,preventDefault:!1,setSelected:!0}};
    !function(n){n.mmenu.wrappers.bootstrap3=function(){if(this.$menu.hasClass("navbar-collapse")){this.conf.classNames.selected="active",this.conf.classNames.divider="divider",this.conf.clone=!0,this.opts.hooks=this.opts.hooks||{};for(var n="",e=["nav-tabs","nav-pills","navbar-nav"],t=0;t<e.length;t++)if(this.$menu.find("."+e[t]).length){n=e[t];break}n.length&&(this.opts.hooks["initMenu:before"]=function(){"navbar-nav"==n&&this.$menu.wrapInner("<div />")},this.opts.hooks["initMenu:after"]=function(){a.menu.call(this),a.dropdown.call(this),a[n.split("nav-").join("").split("-nav").join("")].call(this)})}};var a={menu:function(){this.$menu.find(".nav").removeClass("nav").end().find(".sr-only").remove().end().find(".divider:empty").remove();for(var n=["role","aria-haspopup","aria-expanded"],a=0;a<n.length;a++)this.$menu.find("["+n[a]+"]").removeAttr(n[a])},dropdown:function(){var a=this.$menu.find(".dropdown");a.removeClass("dropdown"),a.children(".dropdown-toggle").find(".caret").remove().end().each(function(){n(this).replaceWith("<span>"+n(this).html()+"</span>")}),a.children(".dropdown-menu").removeClass("dropdown-menu")},tabs:function(){this.$menu.find(".nav-tabs").removeClass("nav-tabs")},pills:function(){this.$menu.find(".nav-pills").removeClass("nav-pills")},navbar:function(){var n=this;this.$menu.removeClass("collapse navbar-collapse").find('[class*="navbar-"]').removeClass("navbar-left navbar-right navbar-nav navbar-text navbar-btn");var a=this.$menu.find(".navbar-form");this.conf.searchform={form:{action:a.attr("action"),method:a.attr("method")},input:{name:a.find("input").attr("name")},submit:!0},a.remove(),(this.$orig||this.$menu).closest(".navbar").find(".navbar-header").find(".navbar-toggle").off("click").on("click",function(a){n.open(),a.stopImmediatePropagation(),a.preventDefault()})}}}(jQuery);
    !function(a){function n(n){for(var e=n.is("a")?a("<a />"):a("<span />"),t=["href","title","target"],r=0;r<t.length;r++)void 0!==n.attr(t[r])&&e.attr(t[r],n.attr(t[r]));return e.html(n.html()),e.find(".sr-only").remove(),e}function e(e){var t=a("<ul />");return e.children().each(function(){var e=a(this),r=a("<li />");e.hasClass("dropdown-divider")?r.addClass("Divider"):e.hasClass("dropdown-item")&&r.append(n(e)),t.append(r)}),t}a.mmenu.wrappers.bootstrap4=function(){var t=this;if(this.$menu.hasClass("navbar-collapse")){this.conf.clone=!1;var r=a("<nav />"),i=a("<div />");r.append(i),this.$menu.children().each(function(){var r,s,o=a(this);switch(!0){case o.hasClass("navbar-nav"):i.append((r=o,s=a("<ul />"),r.find(".nav-item").each(function(){var t=a(this),r=a("<li />");if(t.hasClass("active")&&r.addClass("Selected"),!t.hasClass("nav-link")){var i=t.children(".dropdown-menu");i.length&&r.append(e(i)),t=t.children(".nav-link")}r.prepend(n(t)),s.append(r)}),s));break;case o.hasClass("dropdown-menu"):i.append(e(o));break;case o.hasClass("form-inline"):t.conf.searchfield.form={action:o.attr("action")||null,method:o.attr("method")||null},t.conf.searchfield.input={name:o.find("input").attr("name")||null},t.conf.searchfield.clear=!1,t.conf.searchfield.submit=!0;break;default:i.append(o.clone(!0))}}),this.bind("initMenu:before",function(){r.prependTo("body"),this.$menu=r}),this.$menu.parent().find(".navbar-toggler").removeAttr("data-target").removeAttr("aria-controls").off("click").on("click",function(a){a.preventDefault(),a.stopImmediatePropagation(),t[t.vars.opened?"close":"open"]()})}}}(jQuery);
    !function(e){e.mmenu.wrappers.jqueryMobile=function(){var n=this;this.opts.onClick.close=!1,this.conf.offCanvas.page.selector="div.ui-page-active",e("body").on("pagecontainerchange",function(e,t){"function"==typeof n.close&&(n.close(),n.setPage(t.toPage))}),this.bind("initAnchors:after",function(){e("body").on("click",".mm-listview a",function(n){n.isDefaultPrevented()||(n.preventDefault(),e("body").pagecontainer("change",e(this).attr("href")))})})}}(jQuery);
    jQuery.mmenu.wrappers.magento=function(){this.conf.classNames.selected="active"};
    jQuery.mmenu.wrappers.olark=function(){this.conf.offCanvas.page.noSelector.push("#olark")};
    !function(n){n.mmenu.wrappers.turbolinks=function(){var t,o;n(document).on("turbolinks:before-visit",function(){o=n("html"),t=o.attr("class"),t=n.grep(t.split(/\s+/),function(n){return!/mm-/.test(n)}).join(" ")}).on("turbolinks:load",function(){void 0!==o&&(o.attr("class",t),n.mmenu.glbl=!1)})}}(jQuery);
    !function(s){s.mmenu.wrappers.wordpress=function(){this.conf.classNames.selected="current-menu-item",s("#wpadminbar").css("position","fixed").addClass("mm-slideout")}}(jQuery);
    jQuery.mmenu.i18n({Menu:"Menü"},"de");
    jQuery.mmenu.i18n({"Close menu":"Menü schließen","Close submenu":"Untermenü schließen","Open submenu":"Untermenü öffnen","Toggle submenu":"Untermenü wechseln"},"de");
    jQuery.mmenu.i18n({Search:"Suche","No results found.":"Keine Ergebnisse gefunden.",cancel:"beenden"},"de");
    jQuery.mmenu.i18n({Menu:"منو"},"fa");
    jQuery.mmenu.i18n({"Close menu":"بستن منو","Close submenu":"بستن زیرمنو","Open submenu":"بازکردن زیرمنو","Toggle submenu":"سوییچ زیرمنو"},"fa");
    jQuery.mmenu.i18n({Search:"جستجو","No results found.":"نتیجه‌ای یافت نشد.",cancel:"انصراف"},"fa");
    jQuery.mmenu.i18n({Menu:"Menu"},"nl");
    jQuery.mmenu.i18n({"Close menu":"Menu sluiten","Close submenu":"Submenu sluiten","Open submenu":"Submenu openen","Toggle submenu":"Submenu wisselen"},"nl");
    jQuery.mmenu.i18n({Search:"Zoeken","No results found.":"Geen resultaten gevonden.",cancel:"annuleren"},"nl");
    jQuery.mmenu.i18n({Menu:"Меню"},"ru");
    jQuery.mmenu.i18n({"Close menu":"Закрыть меню","Close submenu":"Закрыть подменю","Open submenu":"Открыть подменю","Toggle submenu":"Переключить подменю"},"ru");
    jQuery.mmenu.i18n({Search:"Найти","No results found.":"Ничего не найдено.","Search results":"Результаты поиска"},"ru");
    return jQuery.mmenu;
}));
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/lib/Magnific-Popup-master/jquery.magnific-popup.min.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/*! Magnific Popup - v1.0.0 - 2015-09-17
 * http://dimsemenov.com/plugins/magnific-popup/
 * Copyright (c) 2015 Dmitry Semenov; */
! function(a) { "function" == typeof define && define.amd ? define(["jquery"], a) : a("object" == typeof exports ? require("jquery") : window.jQuery || window.Zepto) }(function(a) { var b, c, d, e, f, g, h = "Close",
        i = "BeforeClose",
        j = "AfterClose",
        k = "BeforeAppend",
        l = "MarkupParse",
        m = "Open",
        n = "Change",
        o = "mfp",
        p = "." + o,
        q = "mfp-ready",
        r = "mfp-removing",
        s = "mfp-prevent-close",
        t = function() {},
        u = !!window.jQuery,
        v = a(window),
        w = function(a, c) { b.ev.on(o + a + p, c) },
        x = function(b, c, d, e) { var f = document.createElement("div"); return f.className = "mfp-" + b, d && (f.innerHTML = d), e ? c && c.appendChild(f) : (f = a(f), c && f.appendTo(c)), f },
        y = function(c, d) { b.ev.triggerHandler(o + c, d), b.st.callbacks && (c = c.charAt(0).toLowerCase() + c.slice(1), b.st.callbacks[c] && b.st.callbacks[c].apply(b, a.isArray(d) ? d : [d])) },
        z = function(c) { return c === g && b.currTemplate.closeBtn || (b.currTemplate.closeBtn = a(b.st.closeMarkup.replace("%title%", b.st.tClose)), g = c), b.currTemplate.closeBtn },
        A = function() { a.magnificPopup.instance || (b = new t, b.init(), a.magnificPopup.instance = b) },
        B = function() { var a = document.createElement("p").style,
                b = ["ms", "O", "Moz", "Webkit"]; if (void 0 !== a.transition) return !0; for (; b.length;)
                if (b.pop() + "Transition" in a) return !0;
            return !1 };
    t.prototype = { constructor: t, init: function() { var c = navigator.appVersion;
            b.isIE7 = -1 !== c.indexOf("MSIE 7."), b.isIE8 = -1 !== c.indexOf("MSIE 8."), b.isLowIE = b.isIE7 || b.isIE8, b.isAndroid = /android/gi.test(c), b.isIOS = /iphone|ipad|ipod/gi.test(c), b.supportsTransition = B(), b.probablyMobile = b.isAndroid || b.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent), d = a(document), b.popupsCache = {} }, open: function(c) { var e; if (c.isObj === !1) { b.items = c.items.toArray(), b.index = 0; var g, h = c.items; for (e = 0; e < h.length; e++)
                    if (g = h[e], g.parsed && (g = g.el[0]), g === c.el[0]) { b.index = e; break } } else b.items = a.isArray(c.items) ? c.items : [c.items], b.index = c.index || 0; if (b.isOpen) return void b.updateItemHTML();
            b.types = [], f = "", c.mainEl && c.mainEl.length ? b.ev = c.mainEl.eq(0) : b.ev = d, c.key ? (b.popupsCache[c.key] || (b.popupsCache[c.key] = {}), b.currTemplate = b.popupsCache[c.key]) : b.currTemplate = {}, b.st = a.extend(!0, {}, a.magnificPopup.defaults, c), b.fixedContentPos = "auto" === b.st.fixedContentPos ? !b.probablyMobile : b.st.fixedContentPos, b.st.modal && (b.st.closeOnContentClick = !1, b.st.closeOnBgClick = !1, b.st.showCloseBtn = !1, b.st.enableEscapeKey = !1), b.bgOverlay || (b.bgOverlay = x("bg").on("click" + p, function() { b.close() }), b.wrap = x("wrap").attr("tabindex", -1).on("click" + p, function(a) { b._checkIfClose(a.target) && b.close() }), b.container = x("container", b.wrap)), b.contentContainer = x("content"), b.st.preloader && (b.preloader = x("preloader", b.container, b.st.tLoading)); var i = a.magnificPopup.modules; for (e = 0; e < i.length; e++) { var j = i[e];
                j = j.charAt(0).toUpperCase() + j.slice(1), b["init" + j].call(b) }
            y("BeforeOpen"), b.st.showCloseBtn && (b.st.closeBtnInside ? (w(l, function(a, b, c, d) { c.close_replaceWith = z(d.type) }), f += " mfp-close-btn-in") : b.wrap.append(z())), b.st.alignTop && (f += " mfp-align-top"), b.fixedContentPos ? b.wrap.css({ overflow: b.st.overflowY, overflowX: "hidden", overflowY: b.st.overflowY }) : b.wrap.css({ top: v.scrollTop(), position: "absolute" }), (b.st.fixedBgPos === !1 || "auto" === b.st.fixedBgPos && !b.fixedContentPos) && b.bgOverlay.css({ height: d.height(), position: "absolute" }), b.st.enableEscapeKey && d.on("keyup" + p, function(a) { 27 === a.keyCode && b.close() }), v.on("resize" + p, function() { b.updateSize() }), b.st.closeOnContentClick || (f += " mfp-auto-cursor"), f && b.wrap.addClass(f); var k = b.wH = v.height(),
                n = {}; if (b.fixedContentPos && b._hasScrollBar(k)) { var o = b._getScrollbarSize();
                o && (n.marginRight = o) }
            b.fixedContentPos && (b.isIE7 ? a("body, html").css("overflow", "hidden") : n.overflow = "hidden"); var r = b.st.mainClass; return b.isIE7 && (r += " mfp-ie7"), r && b._addClassToMFP(r), b.updateItemHTML(), y("BuildControls"), a("html").css(n), b.bgOverlay.add(b.wrap).prependTo(b.st.prependTo || a(document.body)), b._lastFocusedEl = document.activeElement, setTimeout(function() { b.content ? (b._addClassToMFP(q), b._setFocus()) : b.bgOverlay.addClass(q), d.on("focusin" + p, b._onFocusIn) }, 16), b.isOpen = !0, b.updateSize(k), y(m), c }, close: function() { b.isOpen && (y(i), b.isOpen = !1, b.st.removalDelay && !b.isLowIE && b.supportsTransition ? (b._addClassToMFP(r), setTimeout(function() { b._close() }, b.st.removalDelay)) : b._close()) }, _close: function() { y(h); var c = r + " " + q + " "; if (b.bgOverlay.detach(), b.wrap.detach(), b.container.empty(), b.st.mainClass && (c += b.st.mainClass + " "), b._removeClassFromMFP(c), b.fixedContentPos) { var e = { marginRight: "" };
                b.isIE7 ? a("body, html").css("overflow", "") : e.overflow = "", a("html").css(e) }
            d.off("keyup" + p + " focusin" + p), b.ev.off(p), b.wrap.attr("class", "mfp-wrap").removeAttr("style"), b.bgOverlay.attr("class", "mfp-bg"), b.container.attr("class", "mfp-container"), !b.st.showCloseBtn || b.st.closeBtnInside && b.currTemplate[b.currItem.type] !== !0 || b.currTemplate.closeBtn && b.currTemplate.closeBtn.detach(), b._lastFocusedEl && a(b._lastFocusedEl).focus(), b.currItem = null, b.content = null, b.currTemplate = null, b.prevHeight = 0, y(j) }, updateSize: function(a) { if (b.isIOS) { var c = document.documentElement.clientWidth / window.innerWidth,
                    d = window.innerHeight * c;
                b.wrap.css("height", d), b.wH = d } else b.wH = a || v.height();
            b.fixedContentPos || b.wrap.css("height", b.wH), y("Resize") }, updateItemHTML: function() { var c = b.items[b.index];
            b.contentContainer.detach(), b.content && b.content.detach(), c.parsed || (c = b.parseEl(b.index)); var d = c.type; if (y("BeforeChange", [b.currItem ? b.currItem.type : "", d]), b.currItem = c, !b.currTemplate[d]) { var f = b.st[d] ? b.st[d].markup : !1;
                y("FirstMarkupParse", f), f ? b.currTemplate[d] = a(f) : b.currTemplate[d] = !0 }
            e && e !== c.type && b.container.removeClass("mfp-" + e + "-holder"); var g = b["get" + d.charAt(0).toUpperCase() + d.slice(1)](c, b.currTemplate[d]);
            b.appendContent(g, d), c.preloaded = !0, y(n, c), e = c.type, b.container.prepend(b.contentContainer), y("AfterChange") }, appendContent: function(a, c) { b.content = a, a ? b.st.showCloseBtn && b.st.closeBtnInside && b.currTemplate[c] === !0 ? b.content.find(".mfp-close").length || b.content.append(z()) : b.content = a : b.content = "", y(k), b.container.addClass("mfp-" + c + "-holder"), b.contentContainer.append(b.content) }, parseEl: function(c) { var d, e = b.items[c]; if (e.tagName ? e = { el: a(e) } : (d = e.type, e = { data: e, src: e.src }), e.el) { for (var f = b.types, g = 0; g < f.length; g++)
                    if (e.el.hasClass("mfp-" + f[g])) { d = f[g]; break }
                e.src = e.el.attr("data-mfp-src"), e.src || (e.src = e.el.attr("href")) } return e.type = d || b.st.type || "inline", e.index = c, e.parsed = !0, b.items[c] = e, y("ElementParse", e), b.items[c] }, addGroup: function(a, c) { var d = function(d) { d.mfpEl = this, b._openClick(d, a, c) };
            c || (c = {}); var e = "click.magnificPopup";
            c.mainEl = a, c.items ? (c.isObj = !0, a.off(e).on(e, d)) : (c.isObj = !1, c.delegate ? a.off(e).on(e, c.delegate, d) : (c.items = a, a.off(e).on(e, d))) }, _openClick: function(c, d, e) { var f = void 0 !== e.midClick ? e.midClick : a.magnificPopup.defaults.midClick; if (f || !(2 === c.which || c.ctrlKey || c.metaKey || c.altKey || c.shiftKey)) { var g = void 0 !== e.disableOn ? e.disableOn : a.magnificPopup.defaults.disableOn; if (g)
                    if (a.isFunction(g)) { if (!g.call(b)) return !0 } else if (v.width() < g) return !0;
                c.type && (c.preventDefault(), b.isOpen && c.stopPropagation()), e.el = a(c.mfpEl), e.delegate && (e.items = d.find(e.delegate)), b.open(e) } }, updateStatus: function(a, d) { if (b.preloader) { c !== a && b.container.removeClass("mfp-s-" + c), d || "loading" !== a || (d = b.st.tLoading); var e = { status: a, text: d };
                y("UpdateStatus", e), a = e.status, d = e.text, b.preloader.html(d), b.preloader.find("a").on("click", function(a) { a.stopImmediatePropagation() }), b.container.addClass("mfp-s-" + a), c = a } }, _checkIfClose: function(c) { if (!a(c).hasClass(s)) { var d = b.st.closeOnContentClick,
                    e = b.st.closeOnBgClick; if (d && e) return !0; if (!b.content || a(c).hasClass("mfp-close") || b.preloader && c === b.preloader[0]) return !0; if (c === b.content[0] || a.contains(b.content[0], c)) { if (d) return !0 } else if (e && a.contains(document, c)) return !0; return !1 } }, _addClassToMFP: function(a) { b.bgOverlay.addClass(a), b.wrap.addClass(a) }, _removeClassFromMFP: function(a) { this.bgOverlay.removeClass(a), b.wrap.removeClass(a) }, _hasScrollBar: function(a) { return (b.isIE7 ? d.height() : document.body.scrollHeight) > (a || v.height()) }, _setFocus: function() {
            (b.st.focus ? b.content.find(b.st.focus).eq(0) : b.wrap).focus() }, _onFocusIn: function(c) { return c.target === b.wrap[0] || a.contains(b.wrap[0], c.target) ? void 0 : (b._setFocus(), !1) }, _parseMarkup: function(b, c, d) { var e;
            d.data && (c = a.extend(d.data, c)), y(l, [b, c, d]), a.each(c, function(a, c) { if (void 0 === c || c === !1) return !0; if (e = a.split("_"), e.length > 1) { var d = b.find(p + "-" + e[0]); if (d.length > 0) { var f = e[1]; "replaceWith" === f ? d[0] !== c[0] && d.replaceWith(c) : "img" === f ? d.is("img") ? d.attr("src", c) : d.replaceWith('<img alt="image" src="' + c + '" class="' + d.attr("class") + '" />') : d.attr(e[1], c) } } else b.find(p + "-" + a).html(c) }) }, _getScrollbarSize: function() { if (void 0 === b.scrollbarSize) { var a = document.createElement("div");
                a.style.cssText = "width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;", document.body.appendChild(a), b.scrollbarSize = a.offsetWidth - a.clientWidth, document.body.removeChild(a) } return b.scrollbarSize } }, a.magnificPopup = { instance: null, proto: t.prototype, modules: [], open: function(b, c) { return A(), b = b ? a.extend(!0, {}, b) : {}, b.isObj = !0, b.index = c || 0, this.instance.open(b) }, close: function() { return a.magnificPopup.instance && a.magnificPopup.instance.close() }, registerModule: function(b, c) { c.options && (a.magnificPopup.defaults[b] = c.options), a.extend(this.proto, c.proto), this.modules.push(b) }, defaults: { disableOn: 0, key: null, midClick: !1, mainClass: "", preloader: !0, focus: "", closeOnContentClick: !1, closeOnBgClick: !0, closeBtnInside: !0, showCloseBtn: !0, enableEscapeKey: !0, modal: !1, alignTop: !1, removalDelay: 0, prependTo: null, fixedContentPos: "auto", fixedBgPos: "auto", overflowY: "auto", closeMarkup: '<button title="%title%" type="button" class="mfp-close">&#215;</button>', tClose: "Close (Esc)", tLoading: "Loading..." } }, a.fn.magnificPopup = function(c) { A(); var d = a(this); if ("string" == typeof c)
            if ("open" === c) { var e, f = u ? d.data("magnificPopup") : d[0].magnificPopup,
                    g = parseInt(arguments[1], 10) || 0;
                f.items ? e = f.items[g] : (e = d, f.delegate && (e = e.find(f.delegate)), e = e.eq(g)), b._openClick({ mfpEl: e }, d, f) } else b.isOpen && b[c].apply(b, Array.prototype.slice.call(arguments, 1));
        else c = a.extend(!0, {}, c), u ? d.data("magnificPopup", c) : d[0].magnificPopup = c, b.addGroup(d, c); return d }; var C, D, E, F = "inline",
        G = function() { E && (D.after(E.addClass(C)).detach(), E = null) };
    a.magnificPopup.registerModule(F, { options: { hiddenClass: "hide", markup: "", tNotFound: "Content not found" }, proto: { initInline: function() { b.types.push(F), w(h + "." + F, function() { G() }) }, getInline: function(c, d) { if (G(), c.src) { var e = b.st.inline,
                        f = a(c.src); if (f.length) { var g = f[0].parentNode;
                        g && g.tagName && (D || (C = e.hiddenClass, D = x(C), C = "mfp-" + C), E = f.after(D).detach().removeClass(C)), b.updateStatus("ready") } else b.updateStatus("error", e.tNotFound), f = a("<div>"); return c.inlineElement = f, f } return b.updateStatus("ready"), b._parseMarkup(d, {}, c), d } } }); var H, I = "ajax",
        J = function() { H && a(document.body).removeClass(H) },
        K = function() { J(), b.req && b.req.abort() };
    a.magnificPopup.registerModule(I, { options: { settings: null, cursor: "mfp-ajax-cur", tError: '<a href="%url%">The content</a> could not be loaded.' }, proto: { initAjax: function() { b.types.push(I), H = b.st.ajax.cursor, w(h + "." + I, K), w("BeforeChange." + I, K) }, getAjax: function(c) { H && a(document.body).addClass(H), b.updateStatus("loading"); var d = a.extend({ url: c.src, success: function(d, e, f) { var g = { data: d, xhr: f };
                        y("ParseAjax", g), b.appendContent(a(g.data), I), c.finished = !0, J(), b._setFocus(), setTimeout(function() { b.wrap.addClass(q) }, 16), b.updateStatus("ready"), y("AjaxContentAdded") }, error: function() { J(), c.finished = c.loadError = !0, b.updateStatus("error", b.st.ajax.tError.replace("%url%", c.src)) } }, b.st.ajax.settings); return b.req = a.ajax(d), "" } } }); var L, M = function(c) { if (c.data && void 0 !== c.data.title) return c.data.title; var d = b.st.image.titleSrc; if (d) { if (a.isFunction(d)) return d.call(b, c); if (c.el) return c.el.attr(d) || "" } return "" };
    a.magnificPopup.registerModule("image", { options: { markup: '<div class="mfp-figure"><div class="mfp-close"></div><figure><div class="mfp-img"></div><figcaption><div class="mfp-bottom-bar"><div class="mfp-title"></div><div class="mfp-counter"></div></div></figcaption></figure></div>', cursor: "mfp-zoom-out-cur", titleSrc: "title", verticalFit: !0, tError: '<a href="%url%">The image</a> could not be loaded.' }, proto: { initImage: function() { var c = b.st.image,
                    d = ".image";
                b.types.push("image"), w(m + d, function() { "image" === b.currItem.type && c.cursor && a(document.body).addClass(c.cursor) }), w(h + d, function() { c.cursor && a(document.body).removeClass(c.cursor), v.off("resize" + p) }), w("Resize" + d, b.resizeImage), b.isLowIE && w("AfterChange", b.resizeImage) }, resizeImage: function() { var a = b.currItem; if (a && a.img && b.st.image.verticalFit) { var c = 0;
                    b.isLowIE && (c = parseInt(a.img.css("padding-top"), 10) + parseInt(a.img.css("padding-bottom"), 10)), a.img.css("max-height", b.wH - c) } }, _onImageHasSize: function(a) { a.img && (a.hasSize = !0, L && clearInterval(L), a.isCheckingImgSize = !1, y("ImageHasSize", a), a.imgHidden && (b.content && b.content.removeClass("mfp-loading"), a.imgHidden = !1)) }, findImageSize: function(a) { var c = 0,
                    d = a.img[0],
                    e = function(f) { L && clearInterval(L), L = setInterval(function() { return d.naturalWidth > 0 ? void b._onImageHasSize(a) : (c > 200 && clearInterval(L), c++, void(3 === c ? e(10) : 40 === c ? e(50) : 100 === c && e(500))) }, f) };
                e(1) }, getImage: function(c, d) { var e = 0,
                    f = function() { c && (c.img[0].complete ? (c.img.off(".mfploader"), c === b.currItem && (b._onImageHasSize(c), b.updateStatus("ready")), c.hasSize = !0, c.loaded = !0, y("ImageLoadComplete")) : (e++, 200 > e ? setTimeout(f, 100) : g())) },
                    g = function() { c && (c.img.off(".mfploader"), c === b.currItem && (b._onImageHasSize(c), b.updateStatus("error", h.tError.replace("%url%", c.src))), c.hasSize = !0, c.loaded = !0, c.loadError = !0) },
                    h = b.st.image,
                    i = d.find(".mfp-img"); if (i.length) { var j = document.createElement("img");
                    j.className = "mfp-img", c.el && c.el.find("img").length && (j.alt = c.el.find("img").attr("alt")), c.img = a(j).on("load.mfploader", f).on("error.mfploader", g), j.src = c.src, i.is("img") && (c.img = c.img.clone()), j = c.img[0], j.naturalWidth > 0 ? c.hasSize = !0 : j.width || (c.hasSize = !1) } return b._parseMarkup(d, { title: M(c), img_replaceWith: c.img }, c), b.resizeImage(), c.hasSize ? (L && clearInterval(L), c.loadError ? (d.addClass("mfp-loading"), b.updateStatus("error", h.tError.replace("%url%", c.src))) : (d.removeClass("mfp-loading"), b.updateStatus("ready")), d) : (b.updateStatus("loading"), c.loading = !0, c.hasSize || (c.imgHidden = !0, d.addClass("mfp-loading"), b.findImageSize(c)), d) } } }); var N, O = function() { return void 0 === N && (N = void 0 !== document.createElement("p").style.MozTransform), N };
    a.magnificPopup.registerModule("zoom", { options: { enabled: !1, easing: "ease-in-out", duration: 300, opener: function(a) { return a.is("img") ? a : a.find("img") } }, proto: { initZoom: function() { var a, c = b.st.zoom,
                    d = ".zoom"; if (c.enabled && b.supportsTransition) { var e, f, g = c.duration,
                        j = function(a) { var b = a.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),
                                d = "all " + c.duration / 1e3 + "s " + c.easing,
                                e = { position: "fixed", zIndex: 9999, left: 0, top: 0, "-webkit-backface-visibility": "hidden" },
                                f = "transition"; return e["-webkit-" + f] = e["-moz-" + f] = e["-o-" + f] = e[f] = d, b.css(e), b },
                        k = function() { b.content.css("visibility", "visible") };
                    w("BuildControls" + d, function() { if (b._allowZoom()) { if (clearTimeout(e), b.content.css("visibility", "hidden"), a = b._getItemToZoom(), !a) return void k();
                            f = j(a), f.css(b._getOffset()), b.wrap.append(f), e = setTimeout(function() { f.css(b._getOffset(!0)), e = setTimeout(function() { k(), setTimeout(function() { f.remove(), a = f = null, y("ZoomAnimationEnded") }, 16) }, g) }, 16) } }), w(i + d, function() { if (b._allowZoom()) { if (clearTimeout(e), b.st.removalDelay = g, !a) { if (a = b._getItemToZoom(), !a) return;
                                f = j(a) }
                            f.css(b._getOffset(!0)), b.wrap.append(f), b.content.css("visibility", "hidden"), setTimeout(function() { f.css(b._getOffset()) }, 16) } }), w(h + d, function() { b._allowZoom() && (k(), f && f.remove(), a = null) }) } }, _allowZoom: function() { return "image" === b.currItem.type }, _getItemToZoom: function() { return b.currItem.hasSize ? b.currItem.img : !1 }, _getOffset: function(c) { var d;
                d = c ? b.currItem.img : b.st.zoom.opener(b.currItem.el || b.currItem); var e = d.offset(),
                    f = parseInt(d.css("padding-top"), 10),
                    g = parseInt(d.css("padding-bottom"), 10);
                e.top -= a(window).scrollTop() - f; var h = { width: d.width(), height: (u ? d.innerHeight() : d[0].offsetHeight) - g - f }; return O() ? h["-moz-transform"] = h.transform = "translate(" + e.left + "px," + e.top + "px)" : (h.left = e.left, h.top = e.top), h } } }); var P = "iframe",
        Q = "//about:blank",
        R = function(a) { if (b.currTemplate[P]) { var c = b.currTemplate[P].find("iframe");
                c.length && (a || (c[0].src = Q), b.isIE8 && c.css("display", a ? "block" : "none")) } };
    a.magnificPopup.registerModule(P, { options: { markup: '<div class="mfp-iframe-scaler"><div class="mfp-close"></div><iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe></div>', srcAction: "iframe_src", patterns: { youtube: { index: "youtube.com", id: "v=", src: "//www.youtube.com/embed/%id%?autoplay=1" }, vimeo: { index: "vimeo.com/", id: "/", src: "//player.vimeo.com/video/%id%?autoplay=1" }, gmaps: { index: "//maps.google.", src: "%id%&output=embed" } } }, proto: { initIframe: function() { b.types.push(P), w("BeforeChange", function(a, b, c) { b !== c && (b === P ? R() : c === P && R(!0)) }), w(h + "." + P, function() { R() }) }, getIframe: function(c, d) { var e = c.src,
                    f = b.st.iframe;
                a.each(f.patterns, function() { return e.indexOf(this.index) > -1 ? (this.id && (e = "string" == typeof this.id ? e.substr(e.lastIndexOf(this.id) + this.id.length, e.length) : this.id.call(this, e)), e = this.src.replace("%id%", e), !1) : void 0 }); var g = {}; return f.srcAction && (g[f.srcAction] = e), b._parseMarkup(d, g, c), b.updateStatus("ready"), d } } }); var S = function(a) { var c = b.items.length; return a > c - 1 ? a - c : 0 > a ? c + a : a },
        T = function(a, b, c) { return a.replace(/%curr%/gi, b + 1).replace(/%total%/gi, c) };
    a.magnificPopup.registerModule("gallery", { options: { enabled: !1, arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>', preload: [0, 2], navigateByImgClick: !0, arrows: !0, tPrev: "Previous (Left arrow key)", tNext: "Next (Right arrow key)", tCounter: "%curr% of %total%" }, proto: { initGallery: function() { var c = b.st.gallery,
                    e = ".mfp-gallery",
                    g = Boolean(a.fn.mfpFastClick); return b.direction = !0, c && c.enabled ? (f += " mfp-gallery", w(m + e, function() { c.navigateByImgClick && b.wrap.on("click" + e, ".mfp-img", function() { return b.items.length > 1 ? (b.next(), !1) : void 0 }), d.on("keydown" + e, function(a) { 37 === a.keyCode ? b.prev() : 39 === a.keyCode && b.next() }) }), w("UpdateStatus" + e, function(a, c) { c.text && (c.text = T(c.text, b.currItem.index, b.items.length)) }), w(l + e, function(a, d, e, f) { var g = b.items.length;
                    e.counter = g > 1 ? T(c.tCounter, f.index, g) : "" }), w("BuildControls" + e, function() { if (b.items.length > 1 && c.arrows && !b.arrowLeft) { var d = c.arrowMarkup,
                            e = b.arrowLeft = a(d.replace(/%title%/gi, c.tPrev).replace(/%dir%/gi, "left")).addClass(s),
                            f = b.arrowRight = a(d.replace(/%title%/gi, c.tNext).replace(/%dir%/gi, "right")).addClass(s),
                            h = g ? "mfpFastClick" : "click";
                        e[h](function() { b.prev() }), f[h](function() { b.next() }), b.isIE7 && (x("b", e[0], !1, !0), x("a", e[0], !1, !0), x("b", f[0], !1, !0), x("a", f[0], !1, !0)), b.container.append(e.add(f)) } }), w(n + e, function() { b._preloadTimeout && clearTimeout(b._preloadTimeout), b._preloadTimeout = setTimeout(function() { b.preloadNearbyImages(), b._preloadTimeout = null }, 16) }), void w(h + e, function() { d.off(e), b.wrap.off("click" + e), b.arrowLeft && g && b.arrowLeft.add(b.arrowRight).destroyMfpFastClick(), b.arrowRight = b.arrowLeft = null })) : !1 }, next: function() { b.direction = !0, b.index = S(b.index + 1), b.updateItemHTML() }, prev: function() { b.direction = !1, b.index = S(b.index - 1), b.updateItemHTML() }, goTo: function(a) { b.direction = a >= b.index, b.index = a, b.updateItemHTML() }, preloadNearbyImages: function() { var a, c = b.st.gallery.preload,
                    d = Math.min(c[0], b.items.length),
                    e = Math.min(c[1], b.items.length); for (a = 1; a <= (b.direction ? e : d); a++) b._preloadItem(b.index + a); for (a = 1; a <= (b.direction ? d : e); a++) b._preloadItem(b.index - a) }, _preloadItem: function(c) { if (c = S(c), !b.items[c].preloaded) { var d = b.items[c];
                    d.parsed || (d = b.parseEl(c)), y("LazyLoad", d), "image" === d.type && (d.img = a('<img alt="image" class="mfp-img" />').on("load.mfploader", function() { d.hasSize = !0 }).on("error.mfploader", function() { d.hasSize = !0, d.loadError = !0, y("LazyLoadError", d) }).attr("src", d.src)), d.preloaded = !0 } } } }); var U = "retina";
    a.magnificPopup.registerModule(U, { options: { replaceSrc: function(a) { return a.src.replace(/\.\w+$/, function(a) { return "@2x" + a }) }, ratio: 1 }, proto: { initRetina: function() { if (window.devicePixelRatio > 1) { var a = b.st.retina,
                            c = a.ratio;
                        c = isNaN(c) ? c() : c, c > 1 && (w("ImageHasSize." + U, function(a, b) { b.img.css({ "max-width": b.img[0].naturalWidth / c, width: "100%" }) }), w("ElementParse." + U, function(b, d) { d.src = a.replaceSrc(d, c) })) } } } }),
        function() { var b = 1e3,
                c = "ontouchstart" in window,
                d = function() { v.off("touchmove" + f + " touchend" + f) },
                e = "mfpFastClick",
                f = "." + e;
            a.fn.mfpFastClick = function(e) { return a(this).each(function() { var g, h = a(this); if (c) { var i, j, k, l, m, n;
                        h.on("touchstart" + f, function(a) { l = !1, n = 1, m = a.originalEvent ? a.originalEvent.touches[0] : a.touches[0], j = m.clientX, k = m.clientY, v.on("touchmove" + f, function(a) { m = a.originalEvent ? a.originalEvent.touches : a.touches, n = m.length, m = m[0], (Math.abs(m.clientX - j) > 10 || Math.abs(m.clientY - k) > 10) && (l = !0, d()) }).on("touchend" + f, function(a) { d(), l || n > 1 || (g = !0, a.preventDefault(), clearTimeout(i), i = setTimeout(function() { g = !1 }, b), e()) }) }) }
                    h.on("click" + f, function() { g || e() }) }) }, a.fn.destroyMfpFastClick = function() { a(this).off("touchstart" + f + " click" + f), c && v.off("touchmove" + f + " touchend" + f) } }(), A() });
// source --> https://classified.maalz.com/wp-content/plugins/cubewp-framework/cube/assets/lib/select2/select2.full.min.js?ver=1.1.29 
/*! Select2 4.1.0-rc.0 | https://github.com/select2/select2/blob/master/LICENSE.md */
!function(n){"function"==typeof define&&define.amd?define(["jquery"],n):"object"==typeof module&&module.exports?module.exports=function(e,t){return void 0===t&&(t="undefined"!=typeof window?require("jquery"):require("jquery")(e)),n(t),t}:n(jQuery)}(function(t){var e,n,s,p,r,o,h,f,g,m,y,v,i,a,_,s=((u=t&&t.fn&&t.fn.select2&&t.fn.select2.amd?t.fn.select2.amd:u)&&u.requirejs||(u?n=u:u={},g={},m={},y={},v={},i=Object.prototype.hasOwnProperty,a=[].slice,_=/\.js$/,h=function(e,t){var n,s,i=c(e),r=i[0],t=t[1];return e=i[1],r&&(n=x(r=l(r,t))),r?e=n&&n.normalize?n.normalize(e,(s=t,function(e){return l(e,s)})):l(e,t):(r=(i=c(e=l(e,t)))[0],e=i[1],r&&(n=x(r))),{f:r?r+"!"+e:e,n:e,pr:r,p:n}},f={require:function(e){return w(e)},exports:function(e){var t=g[e];return void 0!==t?t:g[e]={}},module:function(e){return{id:e,uri:"",exports:g[e],config:(t=e,function(){return y&&y.config&&y.config[t]||{}})};var t}},r=function(e,t,n,s){var i,r,o,a,l,c=[],u=typeof n,d=A(s=s||e);if("undefined"==u||"function"==u){for(t=!t.length&&n.length?["require","exports","module"]:t,a=0;a<t.length;a+=1)if("require"===(r=(o=h(t[a],d)).f))c[a]=f.require(e);else if("exports"===r)c[a]=f.exports(e),l=!0;else if("module"===r)i=c[a]=f.module(e);else if(b(g,r)||b(m,r)||b(v,r))c[a]=x(r);else{if(!o.p)throw new Error(e+" missing "+r);o.p.load(o.n,w(s,!0),function(t){return function(e){g[t]=e}}(r),{}),c[a]=g[r]}u=n?n.apply(g[e],c):void 0,e&&(i&&i.exports!==p&&i.exports!==g[e]?g[e]=i.exports:u===p&&l||(g[e]=u))}else e&&(g[e]=n)},e=n=o=function(e,t,n,s,i){if("string"==typeof e)return f[e]?f[e](t):x(h(e,A(t)).f);if(!e.splice){if((y=e).deps&&o(y.deps,y.callback),!t)return;t.splice?(e=t,t=n,n=null):e=p}return t=t||function(){},"function"==typeof n&&(n=s,s=i),s?r(p,e,t,n):setTimeout(function(){r(p,e,t,n)},4),o},o.config=function(e){return o(e)},e._defined=g,(s=function(e,t,n){if("string"!=typeof e)throw new Error("See almond README: incorrect module build, no module name");t.splice||(n=t,t=[]),b(g,e)||b(m,e)||(m[e]=[e,t,n])}).amd={jQuery:!0},u.requirejs=e,u.require=n,u.define=s),u.define("almond",function(){}),u.define("jquery",[],function(){var e=t||$;return null==e&&console&&console.error&&console.error("Select2: An instance of jQuery or a jQuery-compatible library was not found. Make sure that you are including jQuery before Select2 on your web page."),e}),u.define("select2/utils",["jquery"],function(r){var s={};function c(e){var t,n=e.prototype,s=[];for(t in n)"function"==typeof n[t]&&"constructor"!==t&&s.push(t);return s}s.Extend=function(e,t){var n,s={}.hasOwnProperty;function i(){this.constructor=e}for(n in t)s.call(t,n)&&(e[n]=t[n]);return i.prototype=t.prototype,e.prototype=new i,e.__super__=t.prototype,e},s.Decorate=function(s,i){var e=c(i),t=c(s);function r(){var e=Array.prototype.unshift,t=i.prototype.constructor.length,n=s.prototype.constructor;0<t&&(e.call(arguments,s.prototype.constructor),n=i.prototype.constructor),n.apply(this,arguments)}i.displayName=s.displayName,r.prototype=new function(){this.constructor=r};for(var n=0;n<t.length;n++){var o=t[n];r.prototype[o]=s.prototype[o]}for(var a=0;a<e.length;a++){var l=e[a];r.prototype[l]=function(e){var t=function(){};e in r.prototype&&(t=r.prototype[e]);var n=i.prototype[e];return function(){return Array.prototype.unshift.call(arguments,t),n.apply(this,arguments)}}(l)}return r};function e(){this.listeners={}}e.prototype.on=function(e,t){this.listeners=this.listeners||{},e in this.listeners?this.listeners[e].push(t):this.listeners[e]=[t]},e.prototype.trigger=function(e){var t=Array.prototype.slice,n=t.call(arguments,1);this.listeners=this.listeners||{},0===(n=null==n?[]:n).length&&n.push({}),(n[0]._type=e)in this.listeners&&this.invoke(this.listeners[e],t.call(arguments,1)),"*"in this.listeners&&this.invoke(this.listeners["*"],arguments)},e.prototype.invoke=function(e,t){for(var n=0,s=e.length;n<s;n++)e[n].apply(this,t)},s.Observable=e,s.generateChars=function(e){for(var t="",n=0;n<e;n++)t+=Math.floor(36*Math.random()).toString(36);return t},s.bind=function(e,t){return function(){e.apply(t,arguments)}},s._convertData=function(e){for(var t in e){var n=t.split("-"),s=e;if(1!==n.length){for(var i=0;i<n.length;i++){var r=n[i];(r=r.substring(0,1).toLowerCase()+r.substring(1))in s||(s[r]={}),i==n.length-1&&(s[r]=e[t]),s=s[r]}delete e[t]}}return e},s.hasScroll=function(e,t){var n=r(t),s=t.style.overflowX,i=t.style.overflowY;return(s!==i||"hidden"!==i&&"visible"!==i)&&("scroll"===s||"scroll"===i||(n.innerHeight()<t.scrollHeight||n.innerWidth()<t.scrollWidth))},s.escapeMarkup=function(e){var t={"\\":"&#92;","&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#47;"};return"string"!=typeof e?e:String(e).replace(/[&<>"'\/\\]/g,function(e){return t[e]})},s.__cache={};var n=0;return s.GetUniqueElementId=function(e){var t=e.getAttribute("data-select2-id");return null!=t||(t=e.id?"select2-data-"+e.id:"select2-data-"+(++n).toString()+"-"+s.generateChars(4),e.setAttribute("data-select2-id",t)),t},s.StoreData=function(e,t,n){e=s.GetUniqueElementId(e);s.__cache[e]||(s.__cache[e]={}),s.__cache[e][t]=n},s.GetData=function(e,t){var n=s.GetUniqueElementId(e);return t?s.__cache[n]&&null!=s.__cache[n][t]?s.__cache[n][t]:r(e).data(t):s.__cache[n]},s.RemoveData=function(e){var t=s.GetUniqueElementId(e);null!=s.__cache[t]&&delete s.__cache[t],e.removeAttribute("data-select2-id")},s.copyNonInternalCssClasses=function(e,t){var n=(n=e.getAttribute("class").trim().split(/\s+/)).filter(function(e){return 0===e.indexOf("select2-")}),t=(t=t.getAttribute("class").trim().split(/\s+/)).filter(function(e){return 0!==e.indexOf("select2-")}),t=n.concat(t);e.setAttribute("class",t.join(" "))},s}),u.define("select2/results",["jquery","./utils"],function(d,p){function s(e,t,n){this.$element=e,this.data=n,this.options=t,s.__super__.constructor.call(this)}return p.Extend(s,p.Observable),s.prototype.render=function(){var e=d('<ul class="select2-results__options" role="listbox"></ul>');return this.options.get("multiple")&&e.attr("aria-multiselectable","true"),this.$results=e},s.prototype.clear=function(){this.$results.empty()},s.prototype.displayMessage=function(e){var t=this.options.get("escapeMarkup");this.clear(),this.hideLoading();var n=d('<li role="alert" aria-live="assertive" class="select2-results__option"></li>'),s=this.options.get("translations").get(e.message);n.append(t(s(e.args))),n[0].className+=" select2-results__message",this.$results.append(n)},s.prototype.hideMessages=function(){this.$results.find(".select2-results__message").remove()},s.prototype.append=function(e){this.hideLoading();var t=[];if(null!=e.results&&0!==e.results.length){e.results=this.sort(e.results);for(var n=0;n<e.results.length;n++){var s=e.results[n],s=this.option(s);t.push(s)}this.$results.append(t)}else 0===this.$results.children().length&&this.trigger("results:message",{message:"noResults"})},s.prototype.position=function(e,t){t.find(".select2-results").append(e)},s.prototype.sort=function(e){return this.options.get("sorter")(e)},s.prototype.highlightFirstItem=function(){var e=this.$results.find(".select2-results__option--selectable"),t=e.filter(".select2-results__option--selected");(0<t.length?t:e).first().trigger("mouseenter"),this.ensureHighlightVisible()},s.prototype.setClasses=function(){var t=this;this.data.current(function(e){var s=e.map(function(e){return e.id.toString()});t.$results.find(".select2-results__option--selectable").each(function(){var e=d(this),t=p.GetData(this,"data"),n=""+t.id;null!=t.element&&t.element.selected||null==t.element&&-1<s.indexOf(n)?(this.classList.add("select2-results__option--selected"),e.attr("aria-selected","true")):(this.classList.remove("select2-results__option--selected"),e.attr("aria-selected","false"))})})},s.prototype.showLoading=function(e){this.hideLoading();e={disabled:!0,loading:!0,text:this.options.get("translations").get("searching")(e)},e=this.option(e);e.className+=" loading-results",this.$results.prepend(e)},s.prototype.hideLoading=function(){this.$results.find(".loading-results").remove()},s.prototype.option=function(e){var t=document.createElement("li");t.classList.add("select2-results__option"),t.classList.add("select2-results__option--selectable");var n,s={role:"option"},i=window.Element.prototype.matches||window.Element.prototype.msMatchesSelector||window.Element.prototype.webkitMatchesSelector;for(n in(null!=e.element&&i.call(e.element,":disabled")||null==e.element&&e.disabled)&&(s["aria-disabled"]="true",t.classList.remove("select2-results__option--selectable"),t.classList.add("select2-results__option--disabled")),null==e.id&&t.classList.remove("select2-results__option--selectable"),null!=e._resultId&&(t.id=e._resultId),e.title&&(t.title=e.title),e.children&&(s.role="group",s["aria-label"]=e.text,t.classList.remove("select2-results__option--selectable"),t.classList.add("select2-results__option--group")),s){var r=s[n];t.setAttribute(n,r)}if(e.children){var o=d(t),a=document.createElement("strong");a.className="select2-results__group",this.template(e,a);for(var l=[],c=0;c<e.children.length;c++){var u=e.children[c],u=this.option(u);l.push(u)}i=d("<ul></ul>",{class:"select2-results__options select2-results__options--nested",role:"none"});i.append(l),o.append(a),o.append(i)}else this.template(e,t);return p.StoreData(t,"data",e),t},s.prototype.bind=function(t,e){var i=this,n=t.id+"-results";this.$results.attr("id",n),t.on("results:all",function(e){i.clear(),i.append(e.data),t.isOpen()&&(i.setClasses(),i.highlightFirstItem())}),t.on("results:append",function(e){i.append(e.data),t.isOpen()&&i.setClasses()}),t.on("query",function(e){i.hideMessages(),i.showLoading(e)}),t.on("select",function(){t.isOpen()&&(i.setClasses(),i.options.get("scrollAfterSelect")&&i.highlightFirstItem())}),t.on("unselect",function(){t.isOpen()&&(i.setClasses(),i.options.get("scrollAfterSelect")&&i.highlightFirstItem())}),t.on("open",function(){i.$results.attr("aria-expanded","true"),i.$results.attr("aria-hidden","false"),i.setClasses(),i.ensureHighlightVisible()}),t.on("close",function(){i.$results.attr("aria-expanded","false"),i.$results.attr("aria-hidden","true"),i.$results.removeAttr("aria-activedescendant")}),t.on("results:toggle",function(){var e=i.getHighlightedResults();0!==e.length&&e.trigger("mouseup")}),t.on("results:select",function(){var e,t=i.getHighlightedResults();0!==t.length&&(e=p.GetData(t[0],"data"),t.hasClass("select2-results__option--selected")?i.trigger("close",{}):i.trigger("select",{data:e}))}),t.on("results:previous",function(){var e,t=i.getHighlightedResults(),n=i.$results.find(".select2-results__option--selectable"),s=n.index(t);s<=0||(e=s-1,0===t.length&&(e=0),(s=n.eq(e)).trigger("mouseenter"),t=i.$results.offset().top,n=s.offset().top,s=i.$results.scrollTop()+(n-t),0===e?i.$results.scrollTop(0):n-t<0&&i.$results.scrollTop(s))}),t.on("results:next",function(){var e,t=i.getHighlightedResults(),n=i.$results.find(".select2-results__option--selectable"),s=n.index(t)+1;s>=n.length||((e=n.eq(s)).trigger("mouseenter"),t=i.$results.offset().top+i.$results.outerHeight(!1),n=e.offset().top+e.outerHeight(!1),e=i.$results.scrollTop()+n-t,0===s?i.$results.scrollTop(0):t<n&&i.$results.scrollTop(e))}),t.on("results:focus",function(e){e.element[0].classList.add("select2-results__option--highlighted"),e.element[0].setAttribute("aria-selected","true")}),t.on("results:message",function(e){i.displayMessage(e)}),d.fn.mousewheel&&this.$results.on("mousewheel",function(e){var t=i.$results.scrollTop(),n=i.$results.get(0).scrollHeight-t+e.deltaY,t=0<e.deltaY&&t-e.deltaY<=0,n=e.deltaY<0&&n<=i.$results.height();t?(i.$results.scrollTop(0),e.preventDefault(),e.stopPropagation()):n&&(i.$results.scrollTop(i.$results.get(0).scrollHeight-i.$results.height()),e.preventDefault(),e.stopPropagation())}),this.$results.on("mouseup",".select2-results__option--selectable",function(e){var t=d(this),n=p.GetData(this,"data");t.hasClass("select2-results__option--selected")?i.options.get("multiple")?i.trigger("unselect",{originalEvent:e,data:n}):i.trigger("close",{}):i.trigger("select",{originalEvent:e,data:n})}),this.$results.on("mouseenter",".select2-results__option--selectable",function(e){var t=p.GetData(this,"data");i.getHighlightedResults().removeClass("select2-results__option--highlighted").attr("aria-selected","false"),i.trigger("results:focus",{data:t,element:d(this)})})},s.prototype.getHighlightedResults=function(){return this.$results.find(".select2-results__option--highlighted")},s.prototype.destroy=function(){this.$results.remove()},s.prototype.ensureHighlightVisible=function(){var e,t,n,s,i=this.getHighlightedResults();0!==i.length&&(e=this.$results.find(".select2-results__option--selectable").index(i),s=this.$results.offset().top,t=i.offset().top,n=this.$results.scrollTop()+(t-s),s=t-s,n-=2*i.outerHeight(!1),e<=2?this.$results.scrollTop(0):(s>this.$results.outerHeight()||s<0)&&this.$results.scrollTop(n))},s.prototype.template=function(e,t){var n=this.options.get("templateResult"),s=this.options.get("escapeMarkup"),e=n(e,t);null==e?t.style.display="none":"string"==typeof e?t.innerHTML=s(e):d(t).append(e)},s}),u.define("select2/keys",[],function(){return{BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46}}),u.define("select2/selection/base",["jquery","../utils","../keys"],function(n,s,i){function r(e,t){this.$element=e,this.options=t,r.__super__.constructor.call(this)}return s.Extend(r,s.Observable),r.prototype.render=function(){var e=n('<span class="select2-selection" role="combobox"  aria-haspopup="true" aria-expanded="false"></span>');return this._tabindex=0,null!=s.GetData(this.$element[0],"old-tabindex")?this._tabindex=s.GetData(this.$element[0],"old-tabindex"):null!=this.$element.attr("tabindex")&&(this._tabindex=this.$element.attr("tabindex")),e.attr("title",this.$element.attr("title")),e.attr("tabindex",this._tabindex),e.attr("aria-disabled","false"),this.$selection=e},r.prototype.bind=function(e,t){var n=this,s=e.id+"-results";this.container=e,this.$selection.on("focus",function(e){n.trigger("focus",e)}),this.$selection.on("blur",function(e){n._handleBlur(e)}),this.$selection.on("keydown",function(e){n.trigger("keypress",e),e.which===i.SPACE&&e.preventDefault()}),e.on("results:focus",function(e){n.$selection.attr("aria-activedescendant",e.data._resultId)}),e.on("selection:update",function(e){n.update(e.data)}),e.on("open",function(){n.$selection.attr("aria-expanded","true"),n.$selection.attr("aria-owns",s),n._attachCloseHandler(e)}),e.on("close",function(){n.$selection.attr("aria-expanded","false"),n.$selection.removeAttr("aria-activedescendant"),n.$selection.removeAttr("aria-owns"),n.$selection.trigger("focus"),n._detachCloseHandler(e)}),e.on("enable",function(){n.$selection.attr("tabindex",n._tabindex),n.$selection.attr("aria-disabled","false")}),e.on("disable",function(){n.$selection.attr("tabindex","-1"),n.$selection.attr("aria-disabled","true")})},r.prototype._handleBlur=function(e){var t=this;window.setTimeout(function(){document.activeElement==t.$selection[0]||n.contains(t.$selection[0],document.activeElement)||t.trigger("blur",e)},1)},r.prototype._attachCloseHandler=function(e){n(document.body).on("mousedown.select2."+e.id,function(e){var t=n(e.target).closest(".select2");n(".select2.select2-container--open").each(function(){this!=t[0]&&s.GetData(this,"element").select2("close")})})},r.prototype._detachCloseHandler=function(e){n(document.body).off("mousedown.select2."+e.id)},r.prototype.position=function(e,t){t.find(".selection").append(e)},r.prototype.destroy=function(){this._detachCloseHandler(this.container)},r.prototype.update=function(e){throw new Error("The `update` method must be defined in child classes.")},r.prototype.isEnabled=function(){return!this.isDisabled()},r.prototype.isDisabled=function(){return this.options.get("disabled")},r}),u.define("select2/selection/single",["jquery","./base","../utils","../keys"],function(e,t,n,s){function i(){i.__super__.constructor.apply(this,arguments)}return n.Extend(i,t),i.prototype.render=function(){var e=i.__super__.render.call(this);return e[0].classList.add("select2-selection--single"),e.html('<span class="select2-selection__rendered"></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span>'),e},i.prototype.bind=function(t,e){var n=this;i.__super__.bind.apply(this,arguments);var s=t.id+"-container";this.$selection.find(".select2-selection__rendered").attr("id",s).attr("role","textbox").attr("aria-readonly","true"),this.$selection.attr("aria-labelledby",s),this.$selection.attr("aria-controls",s),this.$selection.on("mousedown",function(e){1===e.which&&n.trigger("toggle",{originalEvent:e})}),this.$selection.on("focus",function(e){}),this.$selection.on("blur",function(e){}),t.on("focus",function(e){t.isOpen()||n.$selection.trigger("focus")})},i.prototype.clear=function(){var e=this.$selection.find(".select2-selection__rendered");e.empty(),e.removeAttr("title")},i.prototype.display=function(e,t){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(e,t))},i.prototype.selectionContainer=function(){return e("<span></span>")},i.prototype.update=function(e){var t,n;0!==e.length?(n=e[0],t=this.$selection.find(".select2-selection__rendered"),e=this.display(n,t),t.empty().append(e),(n=n.title||n.text)?t.attr("title",n):t.removeAttr("title")):this.clear()},i}),u.define("select2/selection/multiple",["jquery","./base","../utils"],function(i,e,c){function r(e,t){r.__super__.constructor.apply(this,arguments)}return c.Extend(r,e),r.prototype.render=function(){var e=r.__super__.render.call(this);return e[0].classList.add("select2-selection--multiple"),e.html('<ul class="select2-selection__rendered"></ul>'),e},r.prototype.bind=function(e,t){var n=this;r.__super__.bind.apply(this,arguments);var s=e.id+"-container";this.$selection.find(".select2-selection__rendered").attr("id",s),this.$selection.on("click",function(e){n.trigger("toggle",{originalEvent:e})}),this.$selection.on("click",".select2-selection__choice__remove",function(e){var t;n.isDisabled()||(t=i(this).parent(),t=c.GetData(t[0],"data"),n.trigger("unselect",{originalEvent:e,data:t}))}),this.$selection.on("keydown",".select2-selection__choice__remove",function(e){n.isDisabled()||e.stopPropagation()})},r.prototype.clear=function(){var e=this.$selection.find(".select2-selection__rendered");e.empty(),e.removeAttr("title")},r.prototype.display=function(e,t){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(e,t))},r.prototype.selectionContainer=function(){return i('<li class="select2-selection__choice"><button type="button" class="select2-selection__choice__remove" tabindex="-1"><span aria-hidden="true">&times;</span></button><span class="select2-selection__choice__display"></span></li>')},r.prototype.update=function(e){if(this.clear(),0!==e.length){for(var t=[],n=this.$selection.find(".select2-selection__rendered").attr("id")+"-choice-",s=0;s<e.length;s++){var i=e[s],r=this.selectionContainer(),o=this.display(i,r),a=n+c.generateChars(4)+"-";i.id?a+=i.id:a+=c.generateChars(4),r.find(".select2-selection__choice__display").append(o).attr("id",a);var l=i.title||i.text;l&&r.attr("title",l);o=this.options.get("translations").get("removeItem"),l=r.find(".select2-selection__choice__remove");l.attr("title",o()),l.attr("aria-label",o()),l.attr("aria-describedby",a),c.StoreData(r[0],"data",i),t.push(r)}this.$selection.find(".select2-selection__rendered").append(t)}},r}),u.define("select2/selection/placeholder",[],function(){function e(e,t,n){this.placeholder=this.normalizePlaceholder(n.get("placeholder")),e.call(this,t,n)}return e.prototype.normalizePlaceholder=function(e,t){return t="string"==typeof t?{id:"",text:t}:t},e.prototype.createPlaceholder=function(e,t){var n=this.selectionContainer();n.html(this.display(t)),n[0].classList.add("select2-selection__placeholder"),n[0].classList.remove("select2-selection__choice");t=t.title||t.text||n.text();return this.$selection.find(".select2-selection__rendered").attr("title",t),n},e.prototype.update=function(e,t){var n=1==t.length&&t[0].id!=this.placeholder.id;if(1<t.length||n)return e.call(this,t);this.clear();t=this.createPlaceholder(this.placeholder);this.$selection.find(".select2-selection__rendered").append(t)},e}),u.define("select2/selection/allowClear",["jquery","../keys","../utils"],function(i,s,a){function e(){}return e.prototype.bind=function(e,t,n){var s=this;e.call(this,t,n),null==this.placeholder&&this.options.get("debug")&&window.console&&console.error&&console.error("Select2: The `allowClear` option should be used in combination with the `placeholder` option."),this.$selection.on("mousedown",".select2-selection__clear",function(e){s._handleClear(e)}),t.on("keypress",function(e){s._handleKeyboardClear(e,t)})},e.prototype._handleClear=function(e,t){if(!this.isDisabled()){var n=this.$selection.find(".select2-selection__clear");if(0!==n.length){t.stopPropagation();var s=a.GetData(n[0],"data"),i=this.$element.val();this.$element.val(this.placeholder.id);var r={data:s};if(this.trigger("clear",r),r.prevented)this.$element.val(i);else{for(var o=0;o<s.length;o++)if(r={data:s[o]},this.trigger("unselect",r),r.prevented)return void this.$element.val(i);this.$element.trigger("input").trigger("change"),this.trigger("toggle",{})}}}},e.prototype._handleKeyboardClear=function(e,t,n){n.isOpen()||t.which!=s.DELETE&&t.which!=s.BACKSPACE||this._handleClear(t)},e.prototype.update=function(e,t){var n,s;e.call(this,t),this.$selection.find(".select2-selection__clear").remove(),this.$selection[0].classList.remove("select2-selection--clearable"),0<this.$selection.find(".select2-selection__placeholder").length||0===t.length||(n=this.$selection.find(".select2-selection__rendered").attr("id"),s=this.options.get("translations").get("removeAllItems"),(e=i('<button type="button" class="select2-selection__clear" tabindex="-1"><span aria-hidden="true">&times;</span></button>')).attr("title",s()),e.attr("aria-label",s()),e.attr("aria-describedby",n),a.StoreData(e[0],"data",t),this.$selection.prepend(e),this.$selection[0].classList.add("select2-selection--clearable"))},e}),u.define("select2/selection/search",["jquery","../utils","../keys"],function(s,a,l){function e(e,t,n){e.call(this,t,n)}return e.prototype.render=function(e){var t=this.options.get("translations").get("search"),n=s('<span class="select2-search select2-search--inline"><textarea class="select2-search__field" type="search" tabindex="-1" autocorrect="off" autocapitalize="none" spellcheck="false" role="searchbox" aria-autocomplete="list" ></textarea></span>');this.$searchContainer=n,this.$search=n.find("textarea"),this.$search.prop("autocomplete",this.options.get("autocomplete")),this.$search.attr("aria-label",t());e=e.call(this);return this._transferTabIndex(),e.append(this.$searchContainer),e},e.prototype.bind=function(e,t,n){var s=this,i=t.id+"-results",r=t.id+"-container";e.call(this,t,n),s.$search.attr("aria-describedby",r),t.on("open",function(){s.$search.attr("aria-controls",i),s.$search.trigger("focus")}),t.on("close",function(){s.$search.val(""),s.resizeSearch(),s.$search.removeAttr("aria-controls"),s.$search.removeAttr("aria-activedescendant"),s.$search.trigger("focus")}),t.on("enable",function(){s.$search.prop("disabled",!1),s._transferTabIndex()}),t.on("disable",function(){s.$search.prop("disabled",!0)}),t.on("focus",function(e){s.$search.trigger("focus")}),t.on("results:focus",function(e){e.data._resultId?s.$search.attr("aria-activedescendant",e.data._resultId):s.$search.removeAttr("aria-activedescendant")}),this.$selection.on("focusin",".select2-search--inline",function(e){s.trigger("focus",e)}),this.$selection.on("focusout",".select2-search--inline",function(e){s._handleBlur(e)}),this.$selection.on("keydown",".select2-search--inline",function(e){var t;e.stopPropagation(),s.trigger("keypress",e),s._keyUpPrevented=e.isDefaultPrevented(),e.which!==l.BACKSPACE||""!==s.$search.val()||0<(t=s.$selection.find(".select2-selection__choice").last()).length&&(t=a.GetData(t[0],"data"),s.searchRemoveChoice(t),e.preventDefault())}),this.$selection.on("click",".select2-search--inline",function(e){s.$search.val()&&e.stopPropagation()});var t=document.documentMode,o=t&&t<=11;this.$selection.on("input.searchcheck",".select2-search--inline",function(e){o?s.$selection.off("input.search input.searchcheck"):s.$selection.off("keyup.search")}),this.$selection.on("keyup.search input.search",".select2-search--inline",function(e){var t;o&&"input"===e.type?s.$selection.off("input.search input.searchcheck"):(t=e.which)!=l.SHIFT&&t!=l.CTRL&&t!=l.ALT&&t!=l.TAB&&s.handleSearch(e)})},e.prototype._transferTabIndex=function(e){this.$search.attr("tabindex",this.$selection.attr("tabindex")),this.$selection.attr("tabindex","-1")},e.prototype.createPlaceholder=function(e,t){this.$search.attr("placeholder",t.text)},e.prototype.update=function(e,t){var n=this.$search[0]==document.activeElement;this.$search.attr("placeholder",""),e.call(this,t),this.resizeSearch(),n&&this.$search.trigger("focus")},e.prototype.handleSearch=function(){var e;this.resizeSearch(),this._keyUpPrevented||(e=this.$search.val(),this.trigger("query",{term:e})),this._keyUpPrevented=!1},e.prototype.searchRemoveChoice=function(e,t){this.trigger("unselect",{data:t}),this.$search.val(t.text),this.handleSearch()},e.prototype.resizeSearch=function(){this.$search.css("width","25px");var e="100%";""===this.$search.attr("placeholder")&&(e=.75*(this.$search.val().length+1)+"em"),this.$search.css("width",e)},e}),u.define("select2/selection/selectionCss",["../utils"],function(n){function e(){}return e.prototype.render=function(e){var t=e.call(this),e=this.options.get("selectionCssClass")||"";return-1!==e.indexOf(":all:")&&(e=e.replace(":all:",""),n.copyNonInternalCssClasses(t[0],this.$element[0])),t.addClass(e),t},e}),u.define("select2/selection/eventRelay",["jquery"],function(o){function e(){}return e.prototype.bind=function(e,t,n){var s=this,i=["open","opening","close","closing","select","selecting","unselect","unselecting","clear","clearing"],r=["opening","closing","selecting","unselecting","clearing"];e.call(this,t,n),t.on("*",function(e,t){var n;-1!==i.indexOf(e)&&(t=t||{},n=o.Event("select2:"+e,{params:t}),s.$element.trigger(n),-1!==r.indexOf(e)&&(t.prevented=n.isDefaultPrevented()))})},e}),u.define("select2/translation",["jquery","require"],function(t,n){function s(e){this.dict=e||{}}return s.prototype.all=function(){return this.dict},s.prototype.get=function(e){return this.dict[e]},s.prototype.extend=function(e){this.dict=t.extend({},e.all(),this.dict)},s._cache={},s.loadPath=function(e){var t;return e in s._cache||(t=n(e),s._cache[e]=t),new s(s._cache[e])},s}),u.define("select2/diacritics",[],function(){return{"Ⓐ":"A","Ａ":"A","À":"A","Á":"A","Â":"A","Ầ":"A","Ấ":"A","Ẫ":"A","Ẩ":"A","Ã":"A","Ā":"A","Ă":"A","Ằ":"A","Ắ":"A","Ẵ":"A","Ẳ":"A","Ȧ":"A","Ǡ":"A","Ä":"A","Ǟ":"A","Ả":"A","Å":"A","Ǻ":"A","Ǎ":"A","Ȁ":"A","Ȃ":"A","Ạ":"A","Ậ":"A","Ặ":"A","Ḁ":"A","Ą":"A","Ⱥ":"A","Ɐ":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ⓑ":"B","Ｂ":"B","Ḃ":"B","Ḅ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ɓ":"B","Ⓒ":"C","Ｃ":"C","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","Ç":"C","Ḉ":"C","Ƈ":"C","Ȼ":"C","Ꜿ":"C","Ⓓ":"D","Ｄ":"D","Ḋ":"D","Ď":"D","Ḍ":"D","Ḑ":"D","Ḓ":"D","Ḏ":"D","Đ":"D","Ƌ":"D","Ɗ":"D","Ɖ":"D","Ꝺ":"D","Ǳ":"DZ","Ǆ":"DZ","ǲ":"Dz","ǅ":"Dz","Ⓔ":"E","Ｅ":"E","È":"E","É":"E","Ê":"E","Ề":"E","Ế":"E","Ễ":"E","Ể":"E","Ẽ":"E","Ē":"E","Ḕ":"E","Ḗ":"E","Ĕ":"E","Ė":"E","Ë":"E","Ẻ":"E","Ě":"E","Ȅ":"E","Ȇ":"E","Ẹ":"E","Ệ":"E","Ȩ":"E","Ḝ":"E","Ę":"E","Ḙ":"E","Ḛ":"E","Ɛ":"E","Ǝ":"E","Ⓕ":"F","Ｆ":"F","Ḟ":"F","Ƒ":"F","Ꝼ":"F","Ⓖ":"G","Ｇ":"G","Ǵ":"G","Ĝ":"G","Ḡ":"G","Ğ":"G","Ġ":"G","Ǧ":"G","Ģ":"G","Ǥ":"G","Ɠ":"G","Ꞡ":"G","Ᵹ":"G","Ꝿ":"G","Ⓗ":"H","Ｈ":"H","Ĥ":"H","Ḣ":"H","Ḧ":"H","Ȟ":"H","Ḥ":"H","Ḩ":"H","Ḫ":"H","Ħ":"H","Ⱨ":"H","Ⱶ":"H","Ɥ":"H","Ⓘ":"I","Ｉ":"I","Ì":"I","Í":"I","Î":"I","Ĩ":"I","Ī":"I","Ĭ":"I","İ":"I","Ï":"I","Ḯ":"I","Ỉ":"I","Ǐ":"I","Ȉ":"I","Ȋ":"I","Ị":"I","Į":"I","Ḭ":"I","Ɨ":"I","Ⓙ":"J","Ｊ":"J","Ĵ":"J","Ɉ":"J","Ⓚ":"K","Ｋ":"K","Ḱ":"K","Ǩ":"K","Ḳ":"K","Ķ":"K","Ḵ":"K","Ƙ":"K","Ⱪ":"K","Ꝁ":"K","Ꝃ":"K","Ꝅ":"K","Ꞣ":"K","Ⓛ":"L","Ｌ":"L","Ŀ":"L","Ĺ":"L","Ľ":"L","Ḷ":"L","Ḹ":"L","Ļ":"L","Ḽ":"L","Ḻ":"L","Ł":"L","Ƚ":"L","Ɫ":"L","Ⱡ":"L","Ꝉ":"L","Ꝇ":"L","Ꞁ":"L","Ǉ":"LJ","ǈ":"Lj","Ⓜ":"M","Ｍ":"M","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ɯ":"M","Ⓝ":"N","Ｎ":"N","Ǹ":"N","Ń":"N","Ñ":"N","Ṅ":"N","Ň":"N","Ṇ":"N","Ņ":"N","Ṋ":"N","Ṉ":"N","Ƞ":"N","Ɲ":"N","Ꞑ":"N","Ꞥ":"N","Ǌ":"NJ","ǋ":"Nj","Ⓞ":"O","Ｏ":"O","Ò":"O","Ó":"O","Ô":"O","Ồ":"O","Ố":"O","Ỗ":"O","Ổ":"O","Õ":"O","Ṍ":"O","Ȭ":"O","Ṏ":"O","Ō":"O","Ṑ":"O","Ṓ":"O","Ŏ":"O","Ȯ":"O","Ȱ":"O","Ö":"O","Ȫ":"O","Ỏ":"O","Ő":"O","Ǒ":"O","Ȍ":"O","Ȏ":"O","Ơ":"O","Ờ":"O","Ớ":"O","Ỡ":"O","Ở":"O","Ợ":"O","Ọ":"O","Ộ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Ɔ":"O","Ɵ":"O","Ꝋ":"O","Ꝍ":"O","Œ":"OE","Ƣ":"OI","Ꝏ":"OO","Ȣ":"OU","Ⓟ":"P","Ｐ":"P","Ṕ":"P","Ṗ":"P","Ƥ":"P","Ᵽ":"P","Ꝑ":"P","Ꝓ":"P","Ꝕ":"P","Ⓠ":"Q","Ｑ":"Q","Ꝗ":"Q","Ꝙ":"Q","Ɋ":"Q","Ⓡ":"R","Ｒ":"R","Ŕ":"R","Ṙ":"R","Ř":"R","Ȑ":"R","Ȓ":"R","Ṛ":"R","Ṝ":"R","Ŗ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꝛ":"R","Ꞧ":"R","Ꞃ":"R","Ⓢ":"S","Ｓ":"S","ẞ":"S","Ś":"S","Ṥ":"S","Ŝ":"S","Ṡ":"S","Š":"S","Ṧ":"S","Ṣ":"S","Ṩ":"S","Ș":"S","Ş":"S","Ȿ":"S","Ꞩ":"S","Ꞅ":"S","Ⓣ":"T","Ｔ":"T","Ṫ":"T","Ť":"T","Ṭ":"T","Ț":"T","Ţ":"T","Ṱ":"T","Ṯ":"T","Ŧ":"T","Ƭ":"T","Ʈ":"T","Ⱦ":"T","Ꞇ":"T","Ꜩ":"TZ","Ⓤ":"U","Ｕ":"U","Ù":"U","Ú":"U","Û":"U","Ũ":"U","Ṹ":"U","Ū":"U","Ṻ":"U","Ŭ":"U","Ü":"U","Ǜ":"U","Ǘ":"U","Ǖ":"U","Ǚ":"U","Ủ":"U","Ů":"U","Ű":"U","Ǔ":"U","Ȕ":"U","Ȗ":"U","Ư":"U","Ừ":"U","Ứ":"U","Ữ":"U","Ử":"U","Ự":"U","Ụ":"U","Ṳ":"U","Ų":"U","Ṷ":"U","Ṵ":"U","Ʉ":"U","Ⓥ":"V","Ｖ":"V","Ṽ":"V","Ṿ":"V","Ʋ":"V","Ꝟ":"V","Ʌ":"V","Ꝡ":"VY","Ⓦ":"W","Ｗ":"W","Ẁ":"W","Ẃ":"W","Ŵ":"W","Ẇ":"W","Ẅ":"W","Ẉ":"W","Ⱳ":"W","Ⓧ":"X","Ｘ":"X","Ẋ":"X","Ẍ":"X","Ⓨ":"Y","Ｙ":"Y","Ỳ":"Y","Ý":"Y","Ŷ":"Y","Ỹ":"Y","Ȳ":"Y","Ẏ":"Y","Ÿ":"Y","Ỷ":"Y","Ỵ":"Y","Ƴ":"Y","Ɏ":"Y","Ỿ":"Y","Ⓩ":"Z","Ｚ":"Z","Ź":"Z","Ẑ":"Z","Ż":"Z","Ž":"Z","Ẓ":"Z","Ẕ":"Z","Ƶ":"Z","Ȥ":"Z","Ɀ":"Z","Ⱬ":"Z","Ꝣ":"Z","ⓐ":"a","ａ":"a","ẚ":"a","à":"a","á":"a","â":"a","ầ":"a","ấ":"a","ẫ":"a","ẩ":"a","ã":"a","ā":"a","ă":"a","ằ":"a","ắ":"a","ẵ":"a","ẳ":"a","ȧ":"a","ǡ":"a","ä":"a","ǟ":"a","ả":"a","å":"a","ǻ":"a","ǎ":"a","ȁ":"a","ȃ":"a","ạ":"a","ậ":"a","ặ":"a","ḁ":"a","ą":"a","ⱥ":"a","ɐ":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ⓑ":"b","ｂ":"b","ḃ":"b","ḅ":"b","ḇ":"b","ƀ":"b","ƃ":"b","ɓ":"b","ⓒ":"c","ｃ":"c","ć":"c","ĉ":"c","ċ":"c","č":"c","ç":"c","ḉ":"c","ƈ":"c","ȼ":"c","ꜿ":"c","ↄ":"c","ⓓ":"d","ｄ":"d","ḋ":"d","ď":"d","ḍ":"d","ḑ":"d","ḓ":"d","ḏ":"d","đ":"d","ƌ":"d","ɖ":"d","ɗ":"d","ꝺ":"d","ǳ":"dz","ǆ":"dz","ⓔ":"e","ｅ":"e","è":"e","é":"e","ê":"e","ề":"e","ế":"e","ễ":"e","ể":"e","ẽ":"e","ē":"e","ḕ":"e","ḗ":"e","ĕ":"e","ė":"e","ë":"e","ẻ":"e","ě":"e","ȅ":"e","ȇ":"e","ẹ":"e","ệ":"e","ȩ":"e","ḝ":"e","ę":"e","ḙ":"e","ḛ":"e","ɇ":"e","ɛ":"e","ǝ":"e","ⓕ":"f","ｆ":"f","ḟ":"f","ƒ":"f","ꝼ":"f","ⓖ":"g","ｇ":"g","ǵ":"g","ĝ":"g","ḡ":"g","ğ":"g","ġ":"g","ǧ":"g","ģ":"g","ǥ":"g","ɠ":"g","ꞡ":"g","ᵹ":"g","ꝿ":"g","ⓗ":"h","ｈ":"h","ĥ":"h","ḣ":"h","ḧ":"h","ȟ":"h","ḥ":"h","ḩ":"h","ḫ":"h","ẖ":"h","ħ":"h","ⱨ":"h","ⱶ":"h","ɥ":"h","ƕ":"hv","ⓘ":"i","ｉ":"i","ì":"i","í":"i","î":"i","ĩ":"i","ī":"i","ĭ":"i","ï":"i","ḯ":"i","ỉ":"i","ǐ":"i","ȉ":"i","ȋ":"i","ị":"i","į":"i","ḭ":"i","ɨ":"i","ı":"i","ⓙ":"j","ｊ":"j","ĵ":"j","ǰ":"j","ɉ":"j","ⓚ":"k","ｋ":"k","ḱ":"k","ǩ":"k","ḳ":"k","ķ":"k","ḵ":"k","ƙ":"k","ⱪ":"k","ꝁ":"k","ꝃ":"k","ꝅ":"k","ꞣ":"k","ⓛ":"l","ｌ":"l","ŀ":"l","ĺ":"l","ľ":"l","ḷ":"l","ḹ":"l","ļ":"l","ḽ":"l","ḻ":"l","ſ":"l","ł":"l","ƚ":"l","ɫ":"l","ⱡ":"l","ꝉ":"l","ꞁ":"l","ꝇ":"l","ǉ":"lj","ⓜ":"m","ｍ":"m","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ɯ":"m","ⓝ":"n","ｎ":"n","ǹ":"n","ń":"n","ñ":"n","ṅ":"n","ň":"n","ṇ":"n","ņ":"n","ṋ":"n","ṉ":"n","ƞ":"n","ɲ":"n","ŉ":"n","ꞑ":"n","ꞥ":"n","ǌ":"nj","ⓞ":"o","ｏ":"o","ò":"o","ó":"o","ô":"o","ồ":"o","ố":"o","ỗ":"o","ổ":"o","õ":"o","ṍ":"o","ȭ":"o","ṏ":"o","ō":"o","ṑ":"o","ṓ":"o","ŏ":"o","ȯ":"o","ȱ":"o","ö":"o","ȫ":"o","ỏ":"o","ő":"o","ǒ":"o","ȍ":"o","ȏ":"o","ơ":"o","ờ":"o","ớ":"o","ỡ":"o","ở":"o","ợ":"o","ọ":"o","ộ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","ɔ":"o","ꝋ":"o","ꝍ":"o","ɵ":"o","œ":"oe","ƣ":"oi","ȣ":"ou","ꝏ":"oo","ⓟ":"p","ｐ":"p","ṕ":"p","ṗ":"p","ƥ":"p","ᵽ":"p","ꝑ":"p","ꝓ":"p","ꝕ":"p","ⓠ":"q","ｑ":"q","ɋ":"q","ꝗ":"q","ꝙ":"q","ⓡ":"r","ｒ":"r","ŕ":"r","ṙ":"r","ř":"r","ȑ":"r","ȓ":"r","ṛ":"r","ṝ":"r","ŗ":"r","ṟ":"r","ɍ":"r","ɽ":"r","ꝛ":"r","ꞧ":"r","ꞃ":"r","ⓢ":"s","ｓ":"s","ß":"s","ś":"s","ṥ":"s","ŝ":"s","ṡ":"s","š":"s","ṧ":"s","ṣ":"s","ṩ":"s","ș":"s","ş":"s","ȿ":"s","ꞩ":"s","ꞅ":"s","ẛ":"s","ⓣ":"t","ｔ":"t","ṫ":"t","ẗ":"t","ť":"t","ṭ":"t","ț":"t","ţ":"t","ṱ":"t","ṯ":"t","ŧ":"t","ƭ":"t","ʈ":"t","ⱦ":"t","ꞇ":"t","ꜩ":"tz","ⓤ":"u","ｕ":"u","ù":"u","ú":"u","û":"u","ũ":"u","ṹ":"u","ū":"u","ṻ":"u","ŭ":"u","ü":"u","ǜ":"u","ǘ":"u","ǖ":"u","ǚ":"u","ủ":"u","ů":"u","ű":"u","ǔ":"u","ȕ":"u","ȗ":"u","ư":"u","ừ":"u","ứ":"u","ữ":"u","ử":"u","ự":"u","ụ":"u","ṳ":"u","ų":"u","ṷ":"u","ṵ":"u","ʉ":"u","ⓥ":"v","ｖ":"v","ṽ":"v","ṿ":"v","ʋ":"v","ꝟ":"v","ʌ":"v","ꝡ":"vy","ⓦ":"w","ｗ":"w","ẁ":"w","ẃ":"w","ŵ":"w","ẇ":"w","ẅ":"w","ẘ":"w","ẉ":"w","ⱳ":"w","ⓧ":"x","ｘ":"x","ẋ":"x","ẍ":"x","ⓨ":"y","ｙ":"y","ỳ":"y","ý":"y","ŷ":"y","ỹ":"y","ȳ":"y","ẏ":"y","ÿ":"y","ỷ":"y","ẙ":"y","ỵ":"y","ƴ":"y","ɏ":"y","ỿ":"y","ⓩ":"z","ｚ":"z","ź":"z","ẑ":"z","ż":"z","ž":"z","ẓ":"z","ẕ":"z","ƶ":"z","ȥ":"z","ɀ":"z","ⱬ":"z","ꝣ":"z","Ά":"Α","Έ":"Ε","Ή":"Η","Ί":"Ι","Ϊ":"Ι","Ό":"Ο","Ύ":"Υ","Ϋ":"Υ","Ώ":"Ω","ά":"α","έ":"ε","ή":"η","ί":"ι","ϊ":"ι","ΐ":"ι","ό":"ο","ύ":"υ","ϋ":"υ","ΰ":"υ","ώ":"ω","ς":"σ","’":"'"}}),u.define("select2/data/base",["../utils"],function(n){function s(e,t){s.__super__.constructor.call(this)}return n.Extend(s,n.Observable),s.prototype.current=function(e){throw new Error("The `current` method must be defined in child classes.")},s.prototype.query=function(e,t){throw new Error("The `query` method must be defined in child classes.")},s.prototype.bind=function(e,t){},s.prototype.destroy=function(){},s.prototype.generateResultId=function(e,t){e=e.id+"-result-";return e+=n.generateChars(4),null!=t.id?e+="-"+t.id.toString():e+="-"+n.generateChars(4),e},s}),u.define("select2/data/select",["./base","../utils","jquery"],function(e,a,l){function n(e,t){this.$element=e,this.options=t,n.__super__.constructor.call(this)}return a.Extend(n,e),n.prototype.current=function(e){var t=this;e(Array.prototype.map.call(this.$element[0].querySelectorAll(":checked"),function(e){return t.item(l(e))}))},n.prototype.select=function(i){var e,r=this;if(i.selected=!0,null!=i.element&&"option"===i.element.tagName.toLowerCase())return i.element.selected=!0,void this.$element.trigger("input").trigger("change");this.$element.prop("multiple")?this.current(function(e){var t=[];(i=[i]).push.apply(i,e);for(var n=0;n<i.length;n++){var s=i[n].id;-1===t.indexOf(s)&&t.push(s)}r.$element.val(t),r.$element.trigger("input").trigger("change")}):(e=i.id,this.$element.val(e),this.$element.trigger("input").trigger("change"))},n.prototype.unselect=function(i){var r=this;if(this.$element.prop("multiple")){if(i.selected=!1,null!=i.element&&"option"===i.element.tagName.toLowerCase())return i.element.selected=!1,void this.$element.trigger("input").trigger("change");this.current(function(e){for(var t=[],n=0;n<e.length;n++){var s=e[n].id;s!==i.id&&-1===t.indexOf(s)&&t.push(s)}r.$element.val(t),r.$element.trigger("input").trigger("change")})}},n.prototype.bind=function(e,t){var n=this;(this.container=e).on("select",function(e){n.select(e.data)}),e.on("unselect",function(e){n.unselect(e.data)})},n.prototype.destroy=function(){this.$element.find("*").each(function(){a.RemoveData(this)})},n.prototype.query=function(t,e){var n=[],s=this;this.$element.children().each(function(){var e;"option"!==this.tagName.toLowerCase()&&"optgroup"!==this.tagName.toLowerCase()||(e=l(this),e=s.item(e),null!==(e=s.matches(t,e))&&n.push(e))}),e({results:n})},n.prototype.addOptions=function(e){this.$element.append(e)},n.prototype.option=function(e){var t;e.children?(t=document.createElement("optgroup")).label=e.text:void 0!==(t=document.createElement("option")).textContent?t.textContent=e.text:t.innerText=e.text,void 0!==e.id&&(t.value=e.id),e.disabled&&(t.disabled=!0),e.selected&&(t.selected=!0),e.title&&(t.title=e.title);e=this._normalizeItem(e);return e.element=t,a.StoreData(t,"data",e),l(t)},n.prototype.item=function(e){var t={};if(null!=(t=a.GetData(e[0],"data")))return t;var n=e[0];if("option"===n.tagName.toLowerCase())t={id:e.val(),text:e.text(),disabled:e.prop("disabled"),selected:e.prop("selected"),title:e.prop("title")};else if("optgroup"===n.tagName.toLowerCase()){t={text:e.prop("label"),children:[],title:e.prop("title")};for(var s=e.children("option"),i=[],r=0;r<s.length;r++){var o=l(s[r]),o=this.item(o);i.push(o)}t.children=i}return(t=this._normalizeItem(t)).element=e[0],a.StoreData(e[0],"data",t),t},n.prototype._normalizeItem=function(e){e!==Object(e)&&(e={id:e,text:e});return null!=(e=l.extend({},{text:""},e)).id&&(e.id=e.id.toString()),null!=e.text&&(e.text=e.text.toString()),null==e._resultId&&e.id&&null!=this.container&&(e._resultId=this.generateResultId(this.container,e)),l.extend({},{selected:!1,disabled:!1},e)},n.prototype.matches=function(e,t){return this.options.get("matcher")(e,t)},n}),u.define("select2/data/array",["./select","../utils","jquery"],function(e,t,c){function s(e,t){this._dataToConvert=t.get("data")||[],s.__super__.constructor.call(this,e,t)}return t.Extend(s,e),s.prototype.bind=function(e,t){s.__super__.bind.call(this,e,t),this.addOptions(this.convertToOptions(this._dataToConvert))},s.prototype.select=function(n){var e=this.$element.find("option").filter(function(e,t){return t.value==n.id.toString()});0===e.length&&(e=this.option(n),this.addOptions(e)),s.__super__.select.call(this,n)},s.prototype.convertToOptions=function(e){var t=this,n=this.$element.find("option"),s=n.map(function(){return t.item(c(this)).id}).get(),i=[];for(var r=0;r<e.length;r++){var o,a,l=this._normalizeItem(e[r]);0<=s.indexOf(l.id)?(o=n.filter(function(e){return function(){return c(this).val()==e.id}}(l)),a=this.item(o),a=c.extend(!0,{},l,a),a=this.option(a),o.replaceWith(a)):(a=this.option(l),l.children&&(l=this.convertToOptions(l.children),a.append(l)),i.push(a))}return i},s}),u.define("select2/data/ajax",["./array","../utils","jquery"],function(e,t,r){function n(e,t){this.ajaxOptions=this._applyDefaults(t.get("ajax")),null!=this.ajaxOptions.processResults&&(this.processResults=this.ajaxOptions.processResults),n.__super__.constructor.call(this,e,t)}return t.Extend(n,e),n.prototype._applyDefaults=function(e){var t={data:function(e){return r.extend({},e,{q:e.term})},transport:function(e,t,n){e=r.ajax(e);return e.then(t),e.fail(n),e}};return r.extend({},t,e,!0)},n.prototype.processResults=function(e){return e},n.prototype.query=function(t,n){var s=this;null!=this._request&&("function"==typeof this._request.abort&&this._request.abort(),this._request=null);var i=r.extend({type:"GET"},this.ajaxOptions);function e(){var e=i.transport(i,function(e){e=s.processResults(e,t);s.options.get("debug")&&window.console&&console.error&&(e&&e.results&&Array.isArray(e.results)||console.error("Select2: The AJAX results did not return an array in the `results` key of the response.")),n(e)},function(){"status"in e&&(0===e.status||"0"===e.status)||s.trigger("results:message",{message:"errorLoading"})});s._request=e}"function"==typeof i.url&&(i.url=i.url.call(this.$element,t)),"function"==typeof i.data&&(i.data=i.data.call(this.$element,t)),this.ajaxOptions.delay&&null!=t.term?(this._queryTimeout&&window.clearTimeout(this._queryTimeout),this._queryTimeout=window.setTimeout(e,this.ajaxOptions.delay)):e()},n}),u.define("select2/data/tags",["jquery"],function(t){function e(e,t,n){var s=n.get("tags"),i=n.get("createTag");void 0!==i&&(this.createTag=i);i=n.get("insertTag");if(void 0!==i&&(this.insertTag=i),e.call(this,t,n),Array.isArray(s))for(var r=0;r<s.length;r++){var o=s[r],o=this._normalizeItem(o),o=this.option(o);this.$element.append(o)}}return e.prototype.query=function(e,c,u){var d=this;this._removeOldTags(),null!=c.term&&null==c.page?e.call(this,c,function e(t,n){for(var s=t.results,i=0;i<s.length;i++){var r=s[i],o=null!=r.children&&!e({results:r.children},!0);if((r.text||"").toUpperCase()===(c.term||"").toUpperCase()||o)return!n&&(t.data=s,void u(t))}if(n)return!0;var a,l=d.createTag(c);null!=l&&((a=d.option(l)).attr("data-select2-tag","true"),d.addOptions([a]),d.insertTag(s,l)),t.results=s,u(t)}):e.call(this,c,u)},e.prototype.createTag=function(e,t){if(null==t.term)return null;t=t.term.trim();return""===t?null:{id:t,text:t}},e.prototype.insertTag=function(e,t,n){t.unshift(n)},e.prototype._removeOldTags=function(e){this.$element.find("option[data-select2-tag]").each(function(){this.selected||t(this).remove()})},e}),u.define("select2/data/tokenizer",["jquery"],function(c){function e(e,t,n){var s=n.get("tokenizer");void 0!==s&&(this.tokenizer=s),e.call(this,t,n)}return e.prototype.bind=function(e,t,n){e.call(this,t,n),this.$search=t.dropdown.$search||t.selection.$search||n.find(".select2-search__field")},e.prototype.query=function(e,t,n){var s=this;t.term=t.term||"";var i=this.tokenizer(t,this.options,function(e){var t,n=s._normalizeItem(e);s.$element.find("option").filter(function(){return c(this).val()===n.id}).length||((t=s.option(n)).attr("data-select2-tag",!0),s._removeOldTags(),s.addOptions([t])),t=n,s.trigger("select",{data:t})});i.term!==t.term&&(this.$search.length&&(this.$search.val(i.term),this.$search.trigger("focus")),t.term=i.term),e.call(this,t,n)},e.prototype.tokenizer=function(e,t,n,s){for(var i=n.get("tokenSeparators")||[],r=t.term,o=0,a=this.createTag||function(e){return{id:e.term,text:e.term}};o<r.length;){var l=r[o];-1!==i.indexOf(l)?(l=r.substr(0,o),null!=(l=a(c.extend({},t,{term:l})))?(s(l),r=r.substr(o+1)||"",o=0):o++):o++}return{term:r}},e}),u.define("select2/data/minimumInputLength",[],function(){function e(e,t,n){this.minimumInputLength=n.get("minimumInputLength"),e.call(this,t,n)}return e.prototype.query=function(e,t,n){t.term=t.term||"",t.term.length<this.minimumInputLength?this.trigger("results:message",{message:"inputTooShort",args:{minimum:this.minimumInputLength,input:t.term,params:t}}):e.call(this,t,n)},e}),u.define("select2/data/maximumInputLength",[],function(){function e(e,t,n){this.maximumInputLength=n.get("maximumInputLength"),e.call(this,t,n)}return e.prototype.query=function(e,t,n){t.term=t.term||"",0<this.maximumInputLength&&t.term.length>this.maximumInputLength?this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:t.term,params:t}}):e.call(this,t,n)},e}),u.define("select2/data/maximumSelectionLength",[],function(){function e(e,t,n){this.maximumSelectionLength=n.get("maximumSelectionLength"),e.call(this,t,n)}return e.prototype.bind=function(e,t,n){var s=this;e.call(this,t,n),t.on("select",function(){s._checkIfMaximumSelected()})},e.prototype.query=function(e,t,n){var s=this;this._checkIfMaximumSelected(function(){e.call(s,t,n)})},e.prototype._checkIfMaximumSelected=function(e,t){var n=this;this.current(function(e){e=null!=e?e.length:0;0<n.maximumSelectionLength&&e>=n.maximumSelectionLength?n.trigger("results:message",{message:"maximumSelected",args:{maximum:n.maximumSelectionLength}}):t&&t()})},e}),u.define("select2/dropdown",["jquery","./utils"],function(t,e){function n(e,t){this.$element=e,this.options=t,n.__super__.constructor.call(this)}return e.Extend(n,e.Observable),n.prototype.render=function(){var e=t('<span class="select2-dropdown"><span class="select2-results"></span></span>');return e.attr("dir",this.options.get("dir")),this.$dropdown=e},n.prototype.bind=function(){},n.prototype.position=function(e,t){},n.prototype.destroy=function(){this.$dropdown.remove()},n}),u.define("select2/dropdown/search",["jquery"],function(r){function e(){}return e.prototype.render=function(e){var t=e.call(this),n=this.options.get("translations").get("search"),e=r('<span class="select2-search select2-search--dropdown"><input class="select2-search__field" type="search" tabindex="-1" autocorrect="off" autocapitalize="none" spellcheck="false" role="searchbox" aria-autocomplete="list" /></span>');return this.$searchContainer=e,this.$search=e.find("input"),this.$search.prop("autocomplete",this.options.get("autocomplete")),this.$search.attr("aria-label",n()),t.prepend(e),t},e.prototype.bind=function(e,t,n){var s=this,i=t.id+"-results";e.call(this,t,n),this.$search.on("keydown",function(e){s.trigger("keypress",e),s._keyUpPrevented=e.isDefaultPrevented()}),this.$search.on("input",function(e){r(this).off("keyup")}),this.$search.on("keyup input",function(e){s.handleSearch(e)}),t.on("open",function(){s.$search.attr("tabindex",0),s.$search.attr("aria-controls",i),s.$search.trigger("focus"),window.setTimeout(function(){s.$search.trigger("focus")},0)}),t.on("close",function(){s.$search.attr("tabindex",-1),s.$search.removeAttr("aria-controls"),s.$search.removeAttr("aria-activedescendant"),s.$search.val(""),s.$search.trigger("blur")}),t.on("focus",function(){t.isOpen()||s.$search.trigger("focus")}),t.on("results:all",function(e){null!=e.query.term&&""!==e.query.term||(s.showSearch(e)?s.$searchContainer[0].classList.remove("select2-search--hide"):s.$searchContainer[0].classList.add("select2-search--hide"))}),t.on("results:focus",function(e){e.data._resultId?s.$search.attr("aria-activedescendant",e.data._resultId):s.$search.removeAttr("aria-activedescendant")})},e.prototype.handleSearch=function(e){var t;this._keyUpPrevented||(t=this.$search.val(),this.trigger("query",{term:t})),this._keyUpPrevented=!1},e.prototype.showSearch=function(e,t){return!0},e}),u.define("select2/dropdown/hidePlaceholder",[],function(){function e(e,t,n,s){this.placeholder=this.normalizePlaceholder(n.get("placeholder")),e.call(this,t,n,s)}return e.prototype.append=function(e,t){t.results=this.removePlaceholder(t.results),e.call(this,t)},e.prototype.normalizePlaceholder=function(e,t){return t="string"==typeof t?{id:"",text:t}:t},e.prototype.removePlaceholder=function(e,t){for(var n=t.slice(0),s=t.length-1;0<=s;s--){var i=t[s];this.placeholder.id===i.id&&n.splice(s,1)}return n},e}),u.define("select2/dropdown/infiniteScroll",["jquery"],function(n){function e(e,t,n,s){this.lastParams={},e.call(this,t,n,s),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return e.prototype.append=function(e,t){this.$loadingMore.remove(),this.loading=!1,e.call(this,t),this.showLoadingMore(t)&&(this.$results.append(this.$loadingMore),this.loadMoreIfNeeded())},e.prototype.bind=function(e,t,n){var s=this;e.call(this,t,n),t.on("query",function(e){s.lastParams=e,s.loading=!0}),t.on("query:append",function(e){s.lastParams=e,s.loading=!0}),this.$results.on("scroll",this.loadMoreIfNeeded.bind(this))},e.prototype.loadMoreIfNeeded=function(){var e=n.contains(document.documentElement,this.$loadingMore[0]);!this.loading&&e&&(e=this.$results.offset().top+this.$results.outerHeight(!1),this.$loadingMore.offset().top+this.$loadingMore.outerHeight(!1)<=e+50&&this.loadMore())},e.prototype.loadMore=function(){this.loading=!0;var e=n.extend({},{page:1},this.lastParams);e.page++,this.trigger("query:append",e)},e.prototype.showLoadingMore=function(e,t){return t.pagination&&t.pagination.more},e.prototype.createLoadingMore=function(){var e=n('<li class="select2-results__option select2-results__option--load-more"role="option" aria-disabled="true"></li>'),t=this.options.get("translations").get("loadingMore");return e.html(t(this.lastParams)),e},e}),u.define("select2/dropdown/attachBody",["jquery","../utils"],function(u,o){function e(e,t,n){this.$dropdownParent=u(n.get("dropdownParent")||document.body),e.call(this,t,n)}return e.prototype.bind=function(e,t,n){var s=this;e.call(this,t,n),t.on("open",function(){s._showDropdown(),s._attachPositioningHandler(t),s._bindContainerResultHandlers(t)}),t.on("close",function(){s._hideDropdown(),s._detachPositioningHandler(t)}),this.$dropdownContainer.on("mousedown",function(e){e.stopPropagation()})},e.prototype.destroy=function(e){e.call(this),this.$dropdownContainer.remove()},e.prototype.position=function(e,t,n){t.attr("class",n.attr("class")),t[0].classList.remove("select2"),t[0].classList.add("select2-container--open"),t.css({position:"absolute",top:-999999}),this.$container=n},e.prototype.render=function(e){var t=u("<span></span>"),e=e.call(this);return t.append(e),this.$dropdownContainer=t},e.prototype._hideDropdown=function(e){this.$dropdownContainer.detach()},e.prototype._bindContainerResultHandlers=function(e,t){var n;this._containerResultsHandlersBound||(n=this,t.on("results:all",function(){n._positionDropdown(),n._resizeDropdown()}),t.on("results:append",function(){n._positionDropdown(),n._resizeDropdown()}),t.on("results:message",function(){n._positionDropdown(),n._resizeDropdown()}),t.on("select",function(){n._positionDropdown(),n._resizeDropdown()}),t.on("unselect",function(){n._positionDropdown(),n._resizeDropdown()}),this._containerResultsHandlersBound=!0)},e.prototype._attachPositioningHandler=function(e,t){var n=this,s="scroll.select2."+t.id,i="resize.select2."+t.id,r="orientationchange.select2."+t.id,t=this.$container.parents().filter(o.hasScroll);t.each(function(){o.StoreData(this,"select2-scroll-position",{x:u(this).scrollLeft(),y:u(this).scrollTop()})}),t.on(s,function(e){var t=o.GetData(this,"select2-scroll-position");u(this).scrollTop(t.y)}),u(window).on(s+" "+i+" "+r,function(e){n._positionDropdown(),n._resizeDropdown()})},e.prototype._detachPositioningHandler=function(e,t){var n="scroll.select2."+t.id,s="resize.select2."+t.id,t="orientationchange.select2."+t.id;this.$container.parents().filter(o.hasScroll).off(n),u(window).off(n+" "+s+" "+t)},e.prototype._positionDropdown=function(){var e=u(window),t=this.$dropdown[0].classList.contains("select2-dropdown--above"),n=this.$dropdown[0].classList.contains("select2-dropdown--below"),s=null,i=this.$container.offset();i.bottom=i.top+this.$container.outerHeight(!1);var r={height:this.$container.outerHeight(!1)};r.top=i.top,r.bottom=i.top+r.height;var o=this.$dropdown.outerHeight(!1),a=e.scrollTop(),l=e.scrollTop()+e.height(),c=a<i.top-o,e=l>i.bottom+o,a={left:i.left,top:r.bottom},l=this.$dropdownParent;"static"===l.css("position")&&(l=l.offsetParent());i={top:0,left:0};(u.contains(document.body,l[0])||l[0].isConnected)&&(i=l.offset()),a.top-=i.top,a.left-=i.left,t||n||(s="below"),e||!c||t?!c&&e&&t&&(s="below"):s="above",("above"==s||t&&"below"!==s)&&(a.top=r.top-i.top-o),null!=s&&(this.$dropdown[0].classList.remove("select2-dropdown--below"),this.$dropdown[0].classList.remove("select2-dropdown--above"),this.$dropdown[0].classList.add("select2-dropdown--"+s),this.$container[0].classList.remove("select2-container--below"),this.$container[0].classList.remove("select2-container--above"),this.$container[0].classList.add("select2-container--"+s)),this.$dropdownContainer.css(a)},e.prototype._resizeDropdown=function(){var e={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(e.minWidth=e.width,e.position="relative",e.width="auto"),this.$dropdown.css(e)},e.prototype._showDropdown=function(e){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},e}),u.define("select2/dropdown/minimumResultsForSearch",[],function(){function e(e,t,n,s){this.minimumResultsForSearch=n.get("minimumResultsForSearch"),this.minimumResultsForSearch<0&&(this.minimumResultsForSearch=1/0),e.call(this,t,n,s)}return e.prototype.showSearch=function(e,t){return!(function e(t){for(var n=0,s=0;s<t.length;s++){var i=t[s];i.children?n+=e(i.children):n++}return n}(t.data.results)<this.minimumResultsForSearch)&&e.call(this,t)},e}),u.define("select2/dropdown/selectOnClose",["../utils"],function(s){function e(){}return e.prototype.bind=function(e,t,n){var s=this;e.call(this,t,n),t.on("close",function(e){s._handleSelectOnClose(e)})},e.prototype._handleSelectOnClose=function(e,t){if(t&&null!=t.originalSelect2Event){var n=t.originalSelect2Event;if("select"===n._type||"unselect"===n._type)return}n=this.getHighlightedResults();n.length<1||(null!=(n=s.GetData(n[0],"data")).element&&n.element.selected||null==n.element&&n.selected||this.trigger("select",{data:n}))},e}),u.define("select2/dropdown/closeOnSelect",[],function(){function e(){}return e.prototype.bind=function(e,t,n){var s=this;e.call(this,t,n),t.on("select",function(e){s._selectTriggered(e)}),t.on("unselect",function(e){s._selectTriggered(e)})},e.prototype._selectTriggered=function(e,t){var n=t.originalEvent;n&&(n.ctrlKey||n.metaKey)||this.trigger("close",{originalEvent:n,originalSelect2Event:t})},e}),u.define("select2/dropdown/dropdownCss",["../utils"],function(n){function e(){}return e.prototype.render=function(e){var t=e.call(this),e=this.options.get("dropdownCssClass")||"";return-1!==e.indexOf(":all:")&&(e=e.replace(":all:",""),n.copyNonInternalCssClasses(t[0],this.$element[0])),t.addClass(e),t},e}),u.define("select2/dropdown/tagsSearchHighlight",["../utils"],function(s){function e(){}return e.prototype.highlightFirstItem=function(e){var t=this.$results.find(".select2-results__option--selectable:not(.select2-results__option--selected)");if(0<t.length){var n=t.first(),t=s.GetData(n[0],"data").element;if(t&&t.getAttribute&&"true"===t.getAttribute("data-select2-tag"))return void n.trigger("mouseenter")}e.call(this)},e}),u.define("select2/i18n/en",[],function(){return{errorLoading:function(){return"The results could not be loaded."},inputTooLong:function(e){var t=e.input.length-e.maximum,e="Please delete "+t+" character";return 1!=t&&(e+="s"),e},inputTooShort:function(e){return"Please enter "+(e.minimum-e.input.length)+" or more characters"},loadingMore:function(){return"Loading more results…"},maximumSelected:function(e){var t="You can only select "+e.maximum+" item";return 1!=e.maximum&&(t+="s"),t},noResults:function(){return"No results found"},searching:function(){return"Searching…"},removeAllItems:function(){return"Remove all items"},removeItem:function(){return"Remove item"},search:function(){return"Search"}}}),u.define("select2/defaults",["jquery","./results","./selection/single","./selection/multiple","./selection/placeholder","./selection/allowClear","./selection/search","./selection/selectionCss","./selection/eventRelay","./utils","./translation","./diacritics","./data/select","./data/array","./data/ajax","./data/tags","./data/tokenizer","./data/minimumInputLength","./data/maximumInputLength","./data/maximumSelectionLength","./dropdown","./dropdown/search","./dropdown/hidePlaceholder","./dropdown/infiniteScroll","./dropdown/attachBody","./dropdown/minimumResultsForSearch","./dropdown/selectOnClose","./dropdown/closeOnSelect","./dropdown/dropdownCss","./dropdown/tagsSearchHighlight","./i18n/en"],function(l,r,o,a,c,u,d,p,h,f,g,t,m,y,v,_,b,$,w,x,A,D,S,E,O,C,L,T,q,I,e){function n(){this.reset()}return n.prototype.apply=function(e){var t;null==(e=l.extend(!0,{},this.defaults,e)).dataAdapter&&(null!=e.ajax?e.dataAdapter=v:null!=e.data?e.dataAdapter=y:e.dataAdapter=m,0<e.minimumInputLength&&(e.dataAdapter=f.Decorate(e.dataAdapter,$)),0<e.maximumInputLength&&(e.dataAdapter=f.Decorate(e.dataAdapter,w)),0<e.maximumSelectionLength&&(e.dataAdapter=f.Decorate(e.dataAdapter,x)),e.tags&&(e.dataAdapter=f.Decorate(e.dataAdapter,_)),null==e.tokenSeparators&&null==e.tokenizer||(e.dataAdapter=f.Decorate(e.dataAdapter,b))),null==e.resultsAdapter&&(e.resultsAdapter=r,null!=e.ajax&&(e.resultsAdapter=f.Decorate(e.resultsAdapter,E)),null!=e.placeholder&&(e.resultsAdapter=f.Decorate(e.resultsAdapter,S)),e.selectOnClose&&(e.resultsAdapter=f.Decorate(e.resultsAdapter,L)),e.tags&&(e.resultsAdapter=f.Decorate(e.resultsAdapter,I))),null==e.dropdownAdapter&&(e.multiple?e.dropdownAdapter=A:(t=f.Decorate(A,D),e.dropdownAdapter=t),0!==e.minimumResultsForSearch&&(e.dropdownAdapter=f.Decorate(e.dropdownAdapter,C)),e.closeOnSelect&&(e.dropdownAdapter=f.Decorate(e.dropdownAdapter,T)),null!=e.dropdownCssClass&&(e.dropdownAdapter=f.Decorate(e.dropdownAdapter,q)),e.dropdownAdapter=f.Decorate(e.dropdownAdapter,O)),null==e.selectionAdapter&&(e.multiple?e.selectionAdapter=a:e.selectionAdapter=o,null!=e.placeholder&&(e.selectionAdapter=f.Decorate(e.selectionAdapter,c)),e.allowClear&&(e.selectionAdapter=f.Decorate(e.selectionAdapter,u)),e.multiple&&(e.selectionAdapter=f.Decorate(e.selectionAdapter,d)),null!=e.selectionCssClass&&(e.selectionAdapter=f.Decorate(e.selectionAdapter,p)),e.selectionAdapter=f.Decorate(e.selectionAdapter,h)),e.language=this._resolveLanguage(e.language),e.language.push("en");for(var n=[],s=0;s<e.language.length;s++){var i=e.language[s];-1===n.indexOf(i)&&n.push(i)}return e.language=n,e.translations=this._processTranslations(e.language,e.debug),e},n.prototype.reset=function(){function a(e){return e.replace(/[^\u0000-\u007E]/g,function(e){return t[e]||e})}this.defaults={amdLanguageBase:"./i18n/",autocomplete:"off",closeOnSelect:!0,debug:!1,dropdownAutoWidth:!1,escapeMarkup:f.escapeMarkup,language:{},matcher:function e(t,n){if(null==t.term||""===t.term.trim())return n;if(n.children&&0<n.children.length){for(var s=l.extend(!0,{},n),i=n.children.length-1;0<=i;i--)null==e(t,n.children[i])&&s.children.splice(i,1);return 0<s.children.length?s:e(t,s)}var r=a(n.text).toUpperCase(),o=a(t.term).toUpperCase();return-1<r.indexOf(o)?n:null},minimumInputLength:0,maximumInputLength:0,maximumSelectionLength:0,minimumResultsForSearch:0,selectOnClose:!1,scrollAfterSelect:!1,sorter:function(e){return e},templateResult:function(e){return e.text},templateSelection:function(e){return e.text},theme:"default",width:"resolve"}},n.prototype.applyFromElement=function(e,t){var n=e.language,s=this.defaults.language,i=t.prop("lang"),t=t.closest("[lang]").prop("lang"),t=Array.prototype.concat.call(this._resolveLanguage(i),this._resolveLanguage(n),this._resolveLanguage(s),this._resolveLanguage(t));return e.language=t,e},n.prototype._resolveLanguage=function(e){if(!e)return[];if(l.isEmptyObject(e))return[];if(l.isPlainObject(e))return[e];for(var t,n=Array.isArray(e)?e:[e],s=[],i=0;i<n.length;i++)s.push(n[i]),"string"==typeof n[i]&&0<n[i].indexOf("-")&&(t=n[i].split("-")[0],s.push(t));return s},n.prototype._processTranslations=function(e,t){for(var n=new g,s=0;s<e.length;s++){var i=new g,r=e[s];if("string"==typeof r)try{i=g.loadPath(r)}catch(e){try{r=this.defaults.amdLanguageBase+r,i=g.loadPath(r)}catch(e){t&&window.console&&console.warn&&console.warn('Select2: The language file for "'+r+'" could not be automatically loaded. A fallback will be used instead.')}}else i=l.isPlainObject(r)?new g(r):r;n.extend(i)}return n},n.prototype.set=function(e,t){var n={};n[l.camelCase(e)]=t;n=f._convertData(n);l.extend(!0,this.defaults,n)},new n}),u.define("select2/options",["jquery","./defaults","./utils"],function(c,n,u){function e(e,t){this.options=e,null!=t&&this.fromElement(t),null!=t&&(this.options=n.applyFromElement(this.options,t)),this.options=n.apply(this.options)}return e.prototype.fromElement=function(e){var t=["select2"];null==this.options.multiple&&(this.options.multiple=e.prop("multiple")),null==this.options.disabled&&(this.options.disabled=e.prop("disabled")),null==this.options.autocomplete&&e.prop("autocomplete")&&(this.options.autocomplete=e.prop("autocomplete")),null==this.options.dir&&(e.prop("dir")?this.options.dir=e.prop("dir"):e.closest("[dir]").prop("dir")?this.options.dir=e.closest("[dir]").prop("dir"):this.options.dir="ltr"),e.prop("disabled",this.options.disabled),e.prop("multiple",this.options.multiple),u.GetData(e[0],"select2Tags")&&(this.options.debug&&window.console&&console.warn&&console.warn('Select2: The `data-select2-tags` attribute has been changed to use the `data-data` and `data-tags="true"` attributes and will be removed in future versions of Select2.'),u.StoreData(e[0],"data",u.GetData(e[0],"select2Tags")),u.StoreData(e[0],"tags",!0)),u.GetData(e[0],"ajaxUrl")&&(this.options.debug&&window.console&&console.warn&&console.warn("Select2: The `data-ajax-url` attribute has been changed to `data-ajax--url` and support for the old attribute will be removed in future versions of Select2."),e.attr("ajax--url",u.GetData(e[0],"ajaxUrl")),u.StoreData(e[0],"ajax-Url",u.GetData(e[0],"ajaxUrl")));var n={};function s(e,t){return t.toUpperCase()}for(var i=0;i<e[0].attributes.length;i++){var r=e[0].attributes[i].name,o="data-";r.substr(0,o.length)==o&&(r=r.substring(o.length),o=u.GetData(e[0],r),n[r.replace(/-([a-z])/g,s)]=o)}c.fn.jquery&&"1."==c.fn.jquery.substr(0,2)&&e[0].dataset&&(n=c.extend(!0,{},e[0].dataset,n));var a,l=c.extend(!0,{},u.GetData(e[0]),n);for(a in l=u._convertData(l))-1<t.indexOf(a)||(c.isPlainObject(this.options[a])?c.extend(this.options[a],l[a]):this.options[a]=l[a]);return this},e.prototype.get=function(e){return this.options[e]},e.prototype.set=function(e,t){this.options[e]=t},e}),u.define("select2/core",["jquery","./options","./utils","./keys"],function(t,i,r,s){var o=function(e,t){null!=r.GetData(e[0],"select2")&&r.GetData(e[0],"select2").destroy(),this.$element=e,this.id=this._generateId(e),t=t||{},this.options=new i(t,e),o.__super__.constructor.call(this);var n=e.attr("tabindex")||0;r.StoreData(e[0],"old-tabindex",n),e.attr("tabindex","-1");t=this.options.get("dataAdapter");this.dataAdapter=new t(e,this.options);n=this.render();this._placeContainer(n);t=this.options.get("selectionAdapter");this.selection=new t(e,this.options),this.$selection=this.selection.render(),this.selection.position(this.$selection,n);t=this.options.get("dropdownAdapter");this.dropdown=new t(e,this.options),this.$dropdown=this.dropdown.render(),this.dropdown.position(this.$dropdown,n);n=this.options.get("resultsAdapter");this.results=new n(e,this.options,this.dataAdapter),this.$results=this.results.render(),this.results.position(this.$results,this.$dropdown);var s=this;this._bindAdapters(),this._registerDomEvents(),this._registerDataEvents(),this._registerSelectionEvents(),this._registerDropdownEvents(),this._registerResultsEvents(),this._registerEvents(),this.dataAdapter.current(function(e){s.trigger("selection:update",{data:e})}),e[0].classList.add("select2-hidden-accessible"),e.attr("aria-hidden","true"),this._syncAttributes(),r.StoreData(e[0],"select2",this),e.data("select2",this)};return r.Extend(o,r.Observable),o.prototype._generateId=function(e){return"select2-"+(null!=e.attr("id")?e.attr("id"):null!=e.attr("name")?e.attr("name")+"-"+r.generateChars(2):r.generateChars(4)).replace(/(:|\.|\[|\]|,)/g,"")},o.prototype._placeContainer=function(e){e.insertAfter(this.$element);var t=this._resolveWidth(this.$element,this.options.get("width"));null!=t&&e.css("width",t)},o.prototype._resolveWidth=function(e,t){var n=/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;if("resolve"==t){var s=this._resolveWidth(e,"style");return null!=s?s:this._resolveWidth(e,"element")}if("element"==t){s=e.outerWidth(!1);return s<=0?"auto":s+"px"}if("style"!=t)return"computedstyle"!=t?t:window.getComputedStyle(e[0]).width;e=e.attr("style");if("string"!=typeof e)return null;for(var i=e.split(";"),r=0,o=i.length;r<o;r+=1){var a=i[r].replace(/\s/g,"").match(n);if(null!==a&&1<=a.length)return a[1]}return null},o.prototype._bindAdapters=function(){this.dataAdapter.bind(this,this.$container),this.selection.bind(this,this.$container),this.dropdown.bind(this,this.$container),this.results.bind(this,this.$container)},o.prototype._registerDomEvents=function(){var t=this;this.$element.on("change.select2",function(){t.dataAdapter.current(function(e){t.trigger("selection:update",{data:e})})}),this.$element.on("focus.select2",function(e){t.trigger("focus",e)}),this._syncA=r.bind(this._syncAttributes,this),this._syncS=r.bind(this._syncSubtree,this),this._observer=new window.MutationObserver(function(e){t._syncA(),t._syncS(e)}),this._observer.observe(this.$element[0],{attributes:!0,childList:!0,subtree:!1})},o.prototype._registerDataEvents=function(){var n=this;this.dataAdapter.on("*",function(e,t){n.trigger(e,t)})},o.prototype._registerSelectionEvents=function(){var n=this,s=["toggle","focus"];this.selection.on("toggle",function(){n.toggleDropdown()}),this.selection.on("focus",function(e){n.focus(e)}),this.selection.on("*",function(e,t){-1===s.indexOf(e)&&n.trigger(e,t)})},o.prototype._registerDropdownEvents=function(){var n=this;this.dropdown.on("*",function(e,t){n.trigger(e,t)})},o.prototype._registerResultsEvents=function(){var n=this;this.results.on("*",function(e,t){n.trigger(e,t)})},o.prototype._registerEvents=function(){var n=this;this.on("open",function(){n.$container[0].classList.add("select2-container--open")}),this.on("close",function(){n.$container[0].classList.remove("select2-container--open")}),this.on("enable",function(){n.$container[0].classList.remove("select2-container--disabled")}),this.on("disable",function(){n.$container[0].classList.add("select2-container--disabled")}),this.on("blur",function(){n.$container[0].classList.remove("select2-container--focus")}),this.on("query",function(t){n.isOpen()||n.trigger("open",{}),this.dataAdapter.query(t,function(e){n.trigger("results:all",{data:e,query:t})})}),this.on("query:append",function(t){this.dataAdapter.query(t,function(e){n.trigger("results:append",{data:e,query:t})})}),this.on("keypress",function(e){var t=e.which;n.isOpen()?t===s.ESC||t===s.UP&&e.altKey?(n.close(e),e.preventDefault()):t===s.ENTER||t===s.TAB?(n.trigger("results:select",{}),e.preventDefault()):t===s.SPACE&&e.ctrlKey?(n.trigger("results:toggle",{}),e.preventDefault()):t===s.UP?(n.trigger("results:previous",{}),e.preventDefault()):t===s.DOWN&&(n.trigger("results:next",{}),e.preventDefault()):(t===s.ENTER||t===s.SPACE||t===s.DOWN&&e.altKey)&&(n.open(),e.preventDefault())})},o.prototype._syncAttributes=function(){this.options.set("disabled",this.$element.prop("disabled")),this.isDisabled()?(this.isOpen()&&this.close(),this.trigger("disable",{})):this.trigger("enable",{})},o.prototype._isChangeMutation=function(e){var t=this;if(e.addedNodes&&0<e.addedNodes.length){for(var n=0;n<e.addedNodes.length;n++)if(e.addedNodes[n].selected)return!0}else{if(e.removedNodes&&0<e.removedNodes.length)return!0;if(Array.isArray(e))return e.some(function(e){return t._isChangeMutation(e)})}return!1},o.prototype._syncSubtree=function(e){var e=this._isChangeMutation(e),t=this;e&&this.dataAdapter.current(function(e){t.trigger("selection:update",{data:e})})},o.prototype.trigger=function(e,t){var n=o.__super__.trigger,s={open:"opening",close:"closing",select:"selecting",unselect:"unselecting",clear:"clearing"};if(void 0===t&&(t={}),e in s){var i=s[e],s={prevented:!1,name:e,args:t};if(n.call(this,i,s),s.prevented)return void(t.prevented=!0)}n.call(this,e,t)},o.prototype.toggleDropdown=function(){this.isDisabled()||(this.isOpen()?this.close():this.open())},o.prototype.open=function(){this.isOpen()||this.isDisabled()||this.trigger("query",{})},o.prototype.close=function(e){this.isOpen()&&this.trigger("close",{originalEvent:e})},o.prototype.isEnabled=function(){return!this.isDisabled()},o.prototype.isDisabled=function(){return this.options.get("disabled")},o.prototype.isOpen=function(){return this.$container[0].classList.contains("select2-container--open")},o.prototype.hasFocus=function(){return this.$container[0].classList.contains("select2-container--focus")},o.prototype.focus=function(e){this.hasFocus()||(this.$container[0].classList.add("select2-container--focus"),this.trigger("focus",{}))},o.prototype.enable=function(e){this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("enable")` method has been deprecated and will be removed in later Select2 versions. Use $element.prop("disabled") instead.');e=!(e=null==e||0===e.length?[!0]:e)[0];this.$element.prop("disabled",e)},o.prototype.data=function(){this.options.get("debug")&&0<arguments.length&&window.console&&console.warn&&console.warn('Select2: Data can no longer be set using `select2("data")`. You should consider setting the value instead using `$element.val()`.');var t=[];return this.dataAdapter.current(function(e){t=e}),t},o.prototype.val=function(e){if(this.options.get("debug")&&window.console&&console.warn&&console.warn('Select2: The `select2("val")` method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead.'),null==e||0===e.length)return this.$element.val();e=e[0];Array.isArray(e)&&(e=e.map(function(e){return e.toString()})),this.$element.val(e).trigger("input").trigger("change")},o.prototype.destroy=function(){r.RemoveData(this.$container[0]),this.$container.remove(),this._observer.disconnect(),this._observer=null,this._syncA=null,this._syncS=null,this.$element.off(".select2"),this.$element.attr("tabindex",r.GetData(this.$element[0],"old-tabindex")),this.$element[0].classList.remove("select2-hidden-accessible"),this.$element.attr("aria-hidden","false"),r.RemoveData(this.$element[0]),this.$element.removeData("select2"),this.dataAdapter.destroy(),this.selection.destroy(),this.dropdown.destroy(),this.results.destroy(),this.dataAdapter=null,this.selection=null,this.dropdown=null,this.results=null},o.prototype.render=function(){var e=t('<span class="select2 select2-container"><span class="selection"></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>');return e.attr("dir",this.options.get("dir")),this.$container=e,this.$container[0].classList.add("select2-container--"+this.options.get("theme")),r.StoreData(e[0],"element",this.$element),e},o}),u.define("jquery-mousewheel",["jquery"],function(e){return e}),u.define("jquery.select2",["jquery","jquery-mousewheel","./select2/core","./select2/defaults","./select2/utils"],function(i,e,r,t,o){var a;return null==i.fn.select2&&(a=["open","close","destroy"],i.fn.select2=function(t){if("object"==typeof(t=t||{}))return this.each(function(){var e=i.extend(!0,{},t);new r(i(this),e)}),this;if("string"!=typeof t)throw new Error("Invalid arguments for Select2: "+t);var n,s=Array.prototype.slice.call(arguments,1);return this.each(function(){var e=o.GetData(this,"select2");null==e&&window.console&&console.error&&console.error("The select2('"+t+"') method was called on an element that is not using Select2."),n=e[t].apply(e,s)}),-1<a.indexOf(t)?this:n}),null==i.fn.select2.defaults&&(i.fn.select2.defaults=t),r}),{define:u.define,require:u.require});function b(e,t){return i.call(e,t)}function l(e,t){var n,s,i,r,o,a,l,c,u,d,p=t&&t.split("/"),h=y.map,f=h&&h["*"]||{};if(e){for(t=(e=e.split("/")).length-1,y.nodeIdCompat&&_.test(e[t])&&(e[t]=e[t].replace(_,"")),"."===e[0].charAt(0)&&p&&(e=p.slice(0,p.length-1).concat(e)),c=0;c<e.length;c++)"."===(d=e[c])?(e.splice(c,1),--c):".."===d&&(0===c||1===c&&".."===e[2]||".."===e[c-1]||0<c&&(e.splice(c-1,2),c-=2));e=e.join("/")}if((p||f)&&h){for(c=(n=e.split("/")).length;0<c;--c){if(s=n.slice(0,c).join("/"),p)for(u=p.length;0<u;--u)if(i=h[p.slice(0,u).join("/")],i=i&&i[s]){r=i,o=c;break}if(r)break;!a&&f&&f[s]&&(a=f[s],l=c)}!r&&a&&(r=a,o=l),r&&(n.splice(0,o,r),e=n.join("/"))}return e}function w(t,n){return function(){var e=a.call(arguments,0);return"string"!=typeof e[0]&&1===e.length&&e.push(null),o.apply(p,e.concat([t,n]))}}function x(e){var t;if(b(m,e)&&(t=m[e],delete m[e],v[e]=!0,r.apply(p,t)),!b(g,e)&&!b(v,e))throw new Error("No "+e);return g[e]}function c(e){var t,n=e?e.indexOf("!"):-1;return-1<n&&(t=e.substring(0,n),e=e.substring(n+1,e.length)),[t,e]}function A(e){return e?c(e):[]}var u=s.require("jquery.select2");return t.fn.select2.amd=s,u});
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/lib/popup/js/classie.js?ver=4fca74de5e3fa981b9659807f09e9e55 
!function(s){"use strict";function e(s){return new RegExp("(^|\\s+)"+s+"(\\s+|$)")}function n(s,e){var n=a(s,e)?c:t;n(s,e)}var a,t,c;"classList"in document.documentElement?(a=function(s,e){return s.classList.contains(e)},t=function(s,e){s.classList.add(e)},c=function(s,e){s.classList.remove(e)}):(a=function(s,n){return e(n).test(s.className)},t=function(s,e){a(s,e)||(s.className=s.className+" "+e)},c=function(s,n){s.className=s.className.replace(e(n)," ")});var i={hasClass:a,addClass:t,removeClass:c,toggleClass:n,has:a,add:t,remove:c,toggle:n};"function"==typeof define&&define.amd?define(i):s.classie=i}(window);
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/lib/popup/js/modalEffects.js?ver=4fca74de5e3fa981b9659807f09e9e55 
var ModalEffects=function(){!function(){var e=document.querySelector(".md-overlay");[].slice.call(document.querySelectorAll(".md-trigger")).forEach(function(t,c){function n(e){classie.remove(i,"md-show"),e&&classie.remove(document.documentElement,"md-perspective")}function s(){n(classie.has(t,"md-setperspective"))}var i=document.querySelector("#"+t.getAttribute("data-modal"));t.addEventListener("click",function(c){classie.add(i,"md-show"),e.removeEventListener("click",s),e.addEventListener("click",s),classie.has(t,"md-setperspective")&&setTimeout(function(){classie.add(document.documentElement,"md-perspective")},25)})})}()}();
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/2co.min.js?ver=4fca74de5e3fa981b9659807f09e9e55 
function p(a){return function(){return a}}function ajax2co(a){var b,c=!1;a.jsonpCallback=a.jsonpCallback||"jsonCallback",a.url=a.url+a.jsonp+"="+a.jsonpCallback+"&"+a.data,window[a.jsonpCallback]=function(){c=!0,b=arguments[0]};var d,e=document.head||document.getElementsByTagName("head")[0]||document.documentElement;d=document.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(){(!d.readyState||/loaded|complete/.test(d.readyState))&&(d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=void 0,c?a.success(b):a.error&&a.error())},e.insertBefore(d,e.firstChild)}!function(){function e(a){try{if(navigator.plugins&&navigator.plugins.length)for(var b=0;b<navigator.plugins.length;b++){var c=navigator.plugins[b];if(c.name.indexOf(a)>=0)return c.name+(c.description?"|"+c.description:"")}}catch(d){}return""}function v(a){var b=new Date,c=new Date,i=[p("TF1"),p("015"),function(){return ScriptEngineMajorVersion()},function(){return ScriptEngineMinorVersion()},function(){return ScriptEngineBuildVersion()},function(){return f("{7790769C-0471-11D2-AF11-00C04FA35D02}")},function(){return f("{89820200-ECBD-11CF-8B85-00AA005B4340}")},function(){return f("{283807B5-2C60-11D0-A31D-00AA00B92C03}")},function(){return f("{4F216970-C90C-11D1-B5C7-0000F8051515}")},function(){return f("{44BBA848-CC51-11CF-AAFA-00AA00B6015C}")},function(){return f("{9381D8F2-0288-11D0-9501-00AA00B911A5}")},function(){return f("{4F216970-C90C-11D1-B5C7-0000F8051515}")},function(){return f("{5A8D6EE0-3E18-11D0-821E-444553540000}")},function(){return f("{89820200-ECBD-11CF-8B85-00AA005B4383}")},function(){return f("{08B0E5C0-4FCB-11CF-AAA5-00401C608555}")},function(){return f("{45EA75A0-A269-11D1-B5BF-0000F8051515}")},function(){return f("{DE5AED00-A4BF-11D1-9948-00C04F98BBC9}")},function(){return f("{22D6F312-B0F6-11D0-94AB-0080C74C7E95}")},function(){return f("{44BBA842-CC51-11CF-AAFA-00AA00B6015B}")},function(){return f("{3AF36230-A269-11D1-B5BF-0000F8051515}")},function(){return f("{44BBA840-CC51-11CF-AAFA-00AA00B6015C}")},function(){return f("{CC2A9BA0-3BDD-11D0-821E-444553540000}")},function(){return f("{08B0E5C0-4FCB-11CF-AAA5-00401C608500}")},function(){return eval("navigator.appCodeName")},function(){return eval("navigator.appName")},function(){return eval("navigator.appVersion")},function(){return s(["navigator.productSub","navigator.appMinorVersion"])},function(){return eval("navigator.browserLanguage")},function(){return eval("navigator.cookieEnabled")},function(){return s(["navigator.oscpu","navigator.cpuClass"])},function(){return eval("navigator.onLine")},function(){return eval("navigator.platform")},function(){return eval("navigator.systemLanguage")},function(){return eval("navigator.userAgent")},function(){return s(["navigator.language","navigator.userLanguage"])},function(){return eval("document.defaultCharset")},function(){return eval("document.domain")},function(){return eval("screen.deviceXDPI")},function(){return eval("screen.deviceYDPI")},function(){return eval("screen.fontSmoothingEnabled")},function(){return eval("screen.updateInterval")},function(){return 0!==Math.abs(n-o)},function(){return w(b)},p("@UTC@"),function(){var a=0;return a=0,w(b)&&(a=Math.abs(n-o)),a=-(b.getTimezoneOffset()+a)/60},function(){return new Date(2005,5,7,21,33,44,888).toLocaleString()},function(){return eval("screen.width")},function(){return eval("screen.height")},function(){return l.Acrobat},function(){return l.Flash},function(){return l.QuickTime},function(){return l["Java Plug-in"]},function(){return l.Director},function(){return l.Office},p("@CT@"),function(){return n},function(){return o},function(){return b.toLocaleString()},function(){return eval("screen.colorDepth")},function(){return eval("window.screen.availWidth")},function(){return eval("window.screen.availHeight")},function(){return eval("window.screen.availLeft")},function(){return eval("window.screen.availTop")},function(){return e("Acrobat")},function(){return e("Adobe SVG")},function(){return e("Authorware")},function(){return e("Citrix ICA")},function(){return e("Director")},function(){return e("Flash")},function(){return e("MapGuide")},function(){return e("MetaStream")},function(){return e("PDFViewer")},function(){return e("QuickTime")},function(){return e("RealOne")},function(){return e("RealPlayer Enterprise")},function(){return e("RealPlayer Plugin")},function(){return e("Seagate Software Report")},function(){return e("Silverlight")},function(){return e("Windows Media")},function(){return e("iPIX")},function(){return e("nppdf.so")},function(){var a=document.createElement("span");a.innerHTML="&nbsp;",a.style.position="absolute",a.style.left="-9999px",document.body.appendChild(a);var b=a.offsetHeight;return document.body.removeChild(a),b}];y();for(var h="",d=0;d<i.length;d++){a&&(h+=t(i[d].toString(),'"',"'",!0),h+="=");var j;try{j=i[d](this)}catch(k){j=""}h+=a?j:escape(j),h+=";",a&&(h+="\\n")}return h=t(h,escape("@UTC@"),(new Date).getTime()),h=t(h,escape("@CT@"),(new Date).getTime()-c.getTime()),window.f1b5?window.f1b5(h):h}function t(a,b,c,d){"boolean"!=typeof d&&(d=!1);for(var e,f=!0;(e=a.indexOf(b))>=0&&(d||f);)a=a.substr(0,e)+c+a.substr(e+b.length),f=!1;return a}function w(a){var b=Math.min(n,o);return 0!==Math.abs(n-o)&&a.getTimezoneOffset()===b}function y(){for(var a=["Acrobat","Flash","QuickTime","Java Plug-in","Director","Office"],b=0;b<a.length;b++){var c=a[b],d=l,e=c,f=c;c="";try{if(navigator.plugins&&navigator.plugins.length){var g=RegExp(f+".* ([0-9._]+)");for(f=0;f<navigator.plugins.length;f++){var h=g.exec(navigator.plugins[f].name);null===h&&(h=g.exec(navigator.plugins[f].description)),h&&(c=h[1])}}else if(window.ActiveXObject&&u[f])try{var i=new ActiveXObject(u[f][0]);c=u[f][1](i)}catch(j){c=""}}catch(k){c=k.message}d[e]=c}}function s(a){for(var b=0;b<a.length;b++)try{var c=eval(a[b]);if(c)return c}catch(i){}return""}function f(a){var b="";try{"undefined"!=typeof m.a.getComponentVersion&&(b=m.a.getComponentVersion(a,"ComponentID"))}catch(c){a=c.message.length,a=a>40?40:a,b=escape(c.message.substr(0,a))}return b}var m={},n=new Date(2005,0,15).getTimezoneOffset(),o=new Date(2005,6,15).getTimezoneOffset(),l=[],u={Flash:["ShockwaveFlash.ShockwaveFlash",function(a){return a.getVariable("$version")}],Director:["SWCtl.SWCtl",function(a){return a.ShockwaveVersion("")}]};try{m.a=document.createElement("span"),"undefined"!=typeof m.a.addBehavior&&m.a.addBehavior("#default#clientCaps")}catch(z){}l={},m.jscall=function(a){try{if(!a)return v();var b;a:{var c;try{c=document.getElementById(a)}catch(d){}if(null===c||"undefined"==typeof c)try{c=document.getElementsByName(a)[0]}catch(e){}if(null===c||"undefined"==typeof c)for(var f=0;f<document.forms.length;f++)for(var g=document.forms[f],h=0;h<g.elements.length;h++){var i=g[h];if(i.name===a||i.id===a){b=i;break a}}b=c}if(null!==b)try{b.value=v()}catch(j){b.value=escape(j.message)}}catch(k){}},window.parm4=m;var r=navigator.userAgent.toLowerCase();"Gecko"===navigator.product&&parseInt(r.substring(r.indexOf("rv:")+3,r.indexOf(")",r.indexOf("rv:")+3)).split(".")[0])<=2&&window.parm4.jscall()}(),System={},window.System={__namespace:!0,__typeName:"Sys",getName:function(){return"Sys"},__upperCaseTypes:{}},System.Type=function(){function a(){var a=new String;a=arguments[0],this.FullName=a;var b=new Array;a&&(b=a.split("."),this.Name=b[b.length-1],this.Namespace=b.slice(0,b.length-2).join("."))}this.Name=new String("name"),this.Namespace=new String,this.FullName=new String,this.ToSting=function(){return this.FullName},a.apply(this,arguments)},System.Type.Inherits=function(a,b){for(var c in b)"__typeName"!=c&&"GetType"!=c&&(a[c]=b[c]);return b},System.Type.RegisterNamespace=function(a){if("undefined"!=typeof Type&&"function"==typeof Type.registerNamespace)Type.registerNamespace(a);else for(var b=window,c=a.split("."),d=0;d<c.length;d++){var e=c[d],f=b[e];f||(f=b[e]={}),f.__typeName=a,f.__namespace=!0,b=f}},System.Type.RegisterClass=function(typeName,baseType,interfaceTypes){if("undefined"!=typeof Type&&"function"==typeof Type.registerClass)Type.registerClass(typeName,baseType,interfaceTypes);else{var parsedName=eval(typeName);parsedName.__typeName=typeName,parsedName.__class=!0}var o=eval(typeName);o.prototype.GetType=function(){return new System.Type(typeName)}},System.Type.RegisterInterface=function(a,b){},System.Type.RegisterEnum=function(type,flags){if("undefined"!=typeof Type&&"function"==typeof Type.registerEnum)Type.registerEnum(type,flags);else{var o=eval(type);for(var i in o.prototype)o[i]=o.prototype[i];o.__enum=!0,o.__flags=flags}},System.Type.RegisterProperty=function(a){me[a];me[a]=function(b){return 0==arguments.length?me[a].get():void(1==arguments.length&&me[a].set(b))}},System.Type.RegisterNamespace("System"),System.Type.RegisterClass("System.Type"),System.Extensions=function(){this.Apply=function(){var a=!1;if("object"==typeof Response&&(a=!0),!a){this.d=function(){return document.getElementById(arguments[0])};try{System.Web.UI.HtmlControls.FindControl&&(this.d=function(){return System.Web.UI.HtmlControls.FindControl.apply(this,arguments)})}catch(b){}this.$c=function(){return System.Web.UI.HtmlControls.FindControlsByClass.apply(this,arguments)}}}},System.Type.RegisterClass("System.Extensions"),System.Extensions=new System.Extensions,System.Random=function(){this.Next=function(a,b){switch(arguments.length){case 0:b=Math.pow(2,31),a=0;break;case 1:b=arguments[0],a=0;break;case 2:break;default:return 0}var c=a;return b>a&&(c=Math.floor(Math.random()*(b-a))+a),c},this.InitializeClass=function(){},this.InitializeClass.apply(this,arguments)},System.Type.RegisterClass("System.Random"),System.Array=function(){this.Initialize=function(){},this.Initialize.apply(this,arguments)},System.Type.RegisterClass("System.Array"),System.Array.Reverse=function(a,b,c){b=b?b:0,c=c?c:a.length;for(var d=a.slice(b,b+c).reverse(),e=0;c>e;e++)a[e+b]=d[e]},System.Array._Copy1=function(a,b,c){for(var d=0;c>d;d++)b[d]=a[d]},System.Array._Copy2=function(a,b,c,d,e){for(var f=0;e>f;f++)c[d+f]=a[b+f]},System.Array.Copy=function(){3==arguments.length&&System.Array._Copy1.apply(this,arguments),5==arguments.length&&System.Array._Copy2.apply(this,arguments)},System.Array.FillMultiDimensional=function(a,b,c){var d;if(b.length>0)for(d=0;d<a.length;d++){var e=new Array(b[0]),f=b.slice(1);System.Array.FillMultiDimensional(e,f,c),a[d]=e}else for(d=0;d<a.length;d++)a[d]=c;return a},System.Array.GetMultiDimensional=function(a,b){var c=new Array(a[0]);return System.Array.FillMultiDimensional(c,a.slice(1),b)},System.Array.Clone=function(a){for(var b=a.slice(0,a.length),c=0;c<a.length;c++)b[c]=a[c];return b},System.Buffer=function(){this.Initialize=function(){},this.Initialize.apply(this,arguments)},System.Type.RegisterClass("System.Buffer"),System.Buffer.BlockCopy=function(a,b,c,d,e){for(var f=0;e>f;f++)c[d+f]=a[b+f]},System.Byte=function(){for(var a=new Array,b=0;b<arguments.length;b++)a.push(arguments[b]);return System.Array.GetMultiDimensional(a,0)},System.Type.RegisterClass("System.Byte"),System.Extensions.Apply.apply(this),System.Type.RegisterNamespace("System.Text"),System.Text.Encoding=function(){},System.Text.UTF8Encoder=function(){this.GetBytes=function(a){for(var b=new Array,c=new Number,d=0;d<a.length;d++)c=a.charCodeAt(d),128>c?b.push(c):2048>c?(b.push(192|c>>6),b.push(128|63&c)):65536>c?(b.push(224|c>>12),b.push(128|c>>6&63),b.push(128|63&c)):2097152>c?(b.push(240|c>>18),b.push(128|c>>12&63),b.push(128|c>>6&63),b.push(128|63&c)):b.push(63);return b},this.InitializeClass=function(){},this.InitializeClass()},System.Type.RegisterClass("System.Text.UTF8Encoder"),System.Text.Encoding.UTF8=new System.Text.UTF8Encoder,System.Type.RegisterNamespace("System.Convert"),System.Convert.Base64Array=function(){this.S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",this.CA=new Array,this.IA=new Array,this.InitializeClass=function(){for(var a=new String,b=0;b<this.S.length;b++)a=this.S.charAt(b),this.CA[b]=a,this.IA[a]=b},this.InitializeClass()},System.Convert.ToBase64String=function(a,b){var c=new System.Convert.Base64Array,d=a?a.length:0;if(0==d)return new Array(0);for(var e=3*Math.floor(d/3),f=(d-1)/3+1<<2,g=f+(b?(f-1)/76<<1:0),h=new Array(g),i=0,j=0,k=0;e>i;){var l=(255&a[i++])<<16|(255&a[i++])<<8|255&a[i++];h[j++]=c.CA[l>>>18&63],h[j++]=c.CA[l>>>12&63],h[j++]=c.CA[l>>>6&63],h[j++]=c.CA[63&l],b&&19==++k&&g-2>j&&(h[j++]="\r",h[j++]="\n",k=0)}var m=d-e;if(m>0){var n=(255&a[e])<<10|(2==m?(255&a[d-1])<<2:0);h[g-4]=c.CA[n>>12],h[g-3]=c.CA[n>>>6&63],h[g-2]=2==m?c.CA[63&n]:"=",h[g-1]="="}return h.join("")},System.Convert.FromBase64String=function(a,b){var c=new System.Convert.Base64Array;if(b){var d=new RegExp("[^"+c.S+"]","g");a=a.replace(d,"")}var e=a.length;if(0==e)return new Array(0);for(var f,g=0,h=e-1,i="="==a.charAt(h)?"="==a.charAt(h-1)?2:1:0,j=h-g+1,k="\r"==a.charAt(76)?j/78:0,l=e>76?k<<1:0,m=(6*(j-l)>>3)-i,n=new Array(m),o=0,p=3*Math.floor(m/3),q=0;p>o;)f=c.IA[a.charAt(g++)]<<18|c.IA[a.charAt(g++)]<<12|c.IA[a.charAt(g++)]<<6|c.IA[a.charAt(g++)],n[o++]=f>>16,n[o++]=(65535&f)>>8,n[o++]=255&f,l>0&&19==++q&&(g+=2,q=0);if(m>o){f=0;for(var r=0;h-i>=g;r++)f|=c.IA[a.charAt(g++)]<<18-6*r;for(var s=16;m>o;s-=8){var t=Math.pow(2,s+8)-1;n[o++]=(f&t)>>s}}return n},System.Type.RegisterNamespace("System"),System.BigInt=function(){},System.BigInt._Utils=function(){function a(a,b){var c=j(0,(a.length>b?a.length:b)*B,0);return n(c,a),c}function b(b,c,d){var e=a(b,d.length);return z(e,y(c,2),y(d,2),0),y(e,1)}function c(a,b){for(var c=1,d=0;;){if(1==a)return c;if(0==a)return 0;if(d-=c*Math.floor(b/a),b%=a,1==b)return d;if(0==b)return 0;c-=d*Math.floor(a/b),a%=b}}function d(a){return a[a.length-1]>>B-1&1}function e(a,b,c){var d,e=a.length,f=b.length;for(k=f>e+c?e+c:f,d=f-1-c;e>d&&d>=0;d++)if(a[d]>0)return 1;for(d=e-1+c;f>d;d++)if(b[d]>0)return 0;for(d=k-1;d>=c;d--){if(a[d-c]>b[d])return 1;if(a[d-c]<b[d])return 0}return 0}function f(a,b){var c,d=a.length<b.length?a.length:b.length;for(c=a.length;c<b.length;c++)if(b[c])return 0;for(c=b.length;c<a.length;c++)if(a[c])return 1;for(c=d-1;c>=0;c--){if(a[c]>b[c])return 1;if(a[c]<b[c])return 0}return 0}function g(a,b,c,f){var g,h,i,j,k,l,m,p;for(n(f,a),h=b.length;0==b[h-1];h--);for(p=b[h-1],m=0;p;m++)p>>=1;for(m=B-m,r(b,m),r(f,m),g=f.length;0==f[g-1]&&g>h;g--);for(o(c,0);!e(b,f,g-h);)subShift_(f,b,g-h),c[g-h]++;for(i=g-1;i>=h;i--){for(f[i]==b[h-1]?c[i-h]=C:c[i-h]=Math.floor((f[i]*D+f[i-1])/b[h-1]);k=(h>1?b[h-2]:0)*c[i-h],l=k>>B,k&=C,j=l+c[i-h]*b[h-1],l=j>>B,j&=C,l==f[i]?j==f[i-1]?k>(i>1?f[i-2]:0):j>f[i-1]:l>f[i];)c[i-h]--;v(f,b,-c[i-h],i-h),d(f)&&(addShift_(f,b,i-h),c[i-h]--)}q(b,m),q(f,m)}function h(a){var b,c,d,e;for(c=a.length,d=0,b=0;c>b;b++)d+=a[b],e=0,0>d&&(e=-(d>>B),d+=e*D),a[b]=d&C,d=(d>>B)-e}function i(a,b){var c,d=0;for(c=a.length-1;c>=0;c--)d=(d*D+a[c])%b;return d}function j(a,b,c){var d;return d=Math.ceil(b/B)+1,d=c>d?c:d,buff=new Array(d),o(buff,a),buff}function l(a){var b;for(b=0;b<a.length;b++)if(a[b])return 0;return 1}function m(a){return buff=new Array(a.length),n(buff,a),buff}function n(a,b){var c,d=a.length<b.length?a.length:b.length;for(c=0;d>c;c++)a[c]=b[c];for(c=d;c<a.length;c++)a[c]=0}function o(a,b){var c,d;for(d=b,c=0;c<a.length;c++)a[c]=d&C,d>>=B}function p(a,b){var c,d,e,f;for(a[0]+=b,d=a.length,e=0,c=0;d>c;c++)if(e+=a[c],f=0,0>e&&(f=-(e>>B),e+=f*D),a[c]=e&C,e=(e>>B)-f,!e)return}function q(a,b){var c,d=Math.floor(b/B);if(d){for(c=0;c<a.length-d;c++)a[c]=a[c+d];for(;c<a.length;c++)a[c]=0;b%=B}for(c=0;c<a.length-1;c++)a[c]=C&(a[c+1]<<B-b|a[c]>>b);a[c]>>=b}function r(a,b){var c,d=Math.floor(b/B);if(d){for(c=a.length;c>=d;c--)a[c]=a[c-d];for(;c>=0;c--)a[c]=0;b%=B}if(b){for(c=a.length-1;c>0;c--)a[c]=C&(a[c]<<b|a[c-1]>>B-b);a[c]=C&a[c]<<b}}function s(a,b){var c,d,e,f;if(b)for(d=a.length,e=0,c=0;d>c;c++)e+=a[c]*b,f=0,0>e&&(f=-(e>>B),e+=f*D),a[c]=e&C,e=(e>>B)-f}function u(a,b){var c,d,e=0;for(c=a.length-1;c>=0;c--)d=e*D+a[c],a[c]=Math.floor(d/b),e=d%b;return e}function v(a,b,c,d){var e,f,g,h;for(g=a.length<d+b.length?a.length:d+b.length,h=a.length,f=0,e=d;g>e;e++)f+=a[e]+c*b[e-d],a[e]=f&C,f>>=B;for(e=g;f&&h>e;e++)f+=a[e],a[e]=f&C,f>>=B}function w(a,b){s4.length!=a.length?s4=m(a):n(s4,a),s5.length!=a.length&&(s5=m(a)),g(s4,b,s5,a)}function x(a,b,c){var d;for(s0.length!=2*a.length&&(s0=new Array(2*a.length)),o(s0,0),d=0;d<b.length;d++)b[d]&&v(s0,a,b[d],d);w(s0,c),n(a,s0)}function y(a,b){var c,d;for(c=a.length;c>0&&!a[c-1];c--);return d=new Array(c+b),n(d,a),d}function z(a,b,d){var e,f,g,h;if(s7.length!=d.length&&(s7=m(d)),0!=(1&d[0])){for(o(s7,0),g=d.length;g>0&&!d[g-1];g--);for(h=D-c(i(d,D),D),s7[g]=1,x(a,s7,d),s3.length!=a.length?s3=m(a):n(s3,a),e=b.length-1;e>0&!b[e];e--);if(0==b[e])return void o(a,1);for(f=1<<B-1;f&&!(b[e]&f);f>>=1);for(;;){if(!(f>>=1)){if(e--,0>e)return void A(a,one,d,h);f=1<<B-1}A(a,a,d,h),f&b[e]&&A(a,s3,d,h)}}else for(n(s7,a),o(a,1);!equalsInt(b,0);)1&b[0]&&x(a,s7,d),u(b,2),squareMod_(s7,d)}function A(a,b,c,d){var e,g,h,i,j,k,l=c.length,m=b.length;for(sa.length!=l&&(sa=new Array(l)),o(sa,0);l>0&&0==c[l-1];l--);for(;m>0&&0==b[m-1];m--);for(k=sa.length-1,e=0;l>e;e++){for(j=sa[0]+a[e]*b[0],i=(j&C)*d&C,h=j+i*c[0]>>B,j=a[e],g=1;m-4>g;)h+=sa[g]+i*c[g]+j*b[g],sa[g-1]=h&C,h>>=B,g++,h+=sa[g]+i*c[g]+j*b[g],sa[g-1]=h&C,h>>=B,g++,h+=sa[g]+i*c[g]+j*b[g],sa[g-1]=h&C,h>>=B,g++,h+=sa[g]+i*c[g]+j*b[g],sa[g-1]=h&C,h>>=B,g++,h+=sa[g]+i*c[g]+j*b[g],sa[g-1]=h&C,h>>=B,g++;for(;m>g;)h+=sa[g]+i*c[g]+j*b[g],sa[g-1]=h&C,h>>=B,g++;for(;l-4>g;)h+=sa[g]+i*c[g],sa[g-1]=h&C,h>>=B,g++,h+=sa[g]+i*c[g],sa[g-1]=h&C,h>>=B,g++,h+=sa[g]+i*c[g],sa[g-1]=h&C,h>>=B,g++,h+=sa[g]+i*c[g],sa[g-1]=h&C,h>>=B,g++,h+=sa[g]+i*c[g],sa[g-1]=h&C,h>>=B,g++;for(;l>g;)h+=sa[g]+i*c[g],sa[g-1]=h&C,h>>=B,g++;for(;k>g;)h+=sa[g],sa[g-1]=h&C,h>>=B,g++;sa[g-1]=h&C}f(c,sa)||sub_(sa,c),n(a,sa)}var B=0,C=0,D=0;t=new Array(0),ss=t,s0=t,s1=t,s2=t,s3=t,s4=t,s5=t,s6=t,s7=t,T=t,sa=t,mr_x1=t,mr_r=t,mr_a=t,eg_v=t,eg_u=t,eg_A=t,eg_B=t,eg_C=t,eg_D=t,md_q1=t,md_q2=t,md_q3=t,md_r=t,md_r1=t,md_r2=t,md_tt=t,primes=t,pows=t,s_i=t,s_i2=t,s_R=t,s_rm=t,s_q=t,s_n1=t,s_a=t,s_r2=t,s_n=t,s_b=t,s_d=t,s_x1=t,s_x2=t,s_aa=t,rpprb=t,this.ToArray=function(a,b){var c,d,e=new Array;if(s6.length!=a.length?s6=m(a):n(s6,a),-1==b)for(c=0;c<a.length;c++)e.push(a[c]);else for(;!l(s6);)d=u(s6,b),e.push(d);return 0==e.length&&e.push(0),e},this.FromArray=function(a,b,c){var d,e,f,g,h,i=a.length;for(f=j(0,b*i,0),e=0;i>e&&(d=a[e],!(d>=b||0>d));e++)s(f,b),p(f,d);for(i=f.length;i>0&&!f[i-1];i--);for(i=c>i+1?c:i+1,g=new Array(i),h=i<f.length?i:f.length,e=0;h>e;e++)g[e]=f[e];for(;i>e;e++)g[e]=0;return g};var E=f;f=function(a,b){return 1==E(a,b)},this.ToBytes=function(a){return this.ToArray(a,256)},this.FromBytes=function(a){return this.FromArray(a,256,0)},this._initialize=function(){for(this.ElementSize=B,this.ElementMask=C,this.ElementRadix=D,D=C+1,digitsStr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \\'\"+-",B=0;1<<B+1>1<<B;B++);B>>=1,C=(1<<B)-1,D=C+1,one=j(1,1,1),this.Clone=m,this.Expand=a,this.MoreThan=f,this.MoreThanShitf=e,this.FromInt=j,this.InverseModInt=c,this.IsZero=l,this.ModInt=i,this.IsNegative=d,this.PowMod=b,this.Trim=y,this.AddInt_=p,this.Clone_=n,this.CloneInt_=o,this.Mod_=w,this.MultiplyMod_=x,this.PowMod_=z,this.Carry_=h,this.Divide_=g,this.DivideInt_=u,this.LeftShift_=r,this.LinCombShift_=v,this.MontMultiply_=A,this.MultiplyInt_=s,this.RightShift_=q},this._initialize.apply(this,arguments)},System.BigInt.Utils=new System.BigInt._Utils,System.Type.RegisterNamespace("System.Convert"),System.Convert.Base64Array=function(){this.S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",this.CA=new Array,this.IA=new Array,this.InitializeClass=function(){for(var a=new String,b=0;b<this.S.length;b++)a=this.S.charAt(b),this.CA[b]=a,this.IA[a]=b},this.InitializeClass()},System.Convert.ToBase64String=function(a,b){var c=new System.Convert.Base64Array,d=a?a.length:0;if(0==d)return new Array(0);for(var e=3*Math.floor(d/3),f=(d-1)/3+1<<2,g=f+(b?(f-1)/76<<1:0),h=new Array(g),i=0,j=0,k=0;e>i;){var l=(255&a[i++])<<16|(255&a[i++])<<8|255&a[i++];h[j++]=c.CA[l>>>18&63],h[j++]=c.CA[l>>>12&63],h[j++]=c.CA[l>>>6&63],h[j++]=c.CA[63&l],b&&19==++k&&g-2>j&&(h[j++]="\r",h[j++]="\n",k=0)}var m=d-e;if(m>0){var n=(255&a[e])<<10|(2==m?(255&a[d-1])<<2:0);h[g-4]=c.CA[n>>12],h[g-3]=c.CA[n>>>6&63],h[g-2]=2==m?c.CA[63&n]:"=",h[g-1]="="}return h.join("")},System.Convert.FromBase64String=function(a,b){var c=new System.Convert.Base64Array;if(b){var d=new RegExp("[^"+c.S+"]","g");a=a.replace(d,"")}var e=a.length;if(0==e)return new Array(0);for(var f,g=0,h=e-1,i="="==a.charAt(h)?"="==a.charAt(h-1)?2:1:0,j=h-g+1,k="\r"==a.charAt(76)?j/78:0,l=e>76?k<<1:0,m=(6*(j-l)>>3)-i,n=new Array(m),o=0,p=3*Math.floor(m/3),q=0;p>o;)f=c.IA[a.charAt(g++)]<<18|c.IA[a.charAt(g++)]<<12|c.IA[a.charAt(g++)]<<6|c.IA[a.charAt(g++)],n[o++]=f>>16,n[o++]=(65535&f)>>8,n[o++]=255&f,l>0&&19==++q&&(g+=2,q=0);if(m>o){f=0;for(var r=0;h-i>=g;r++)f|=c.IA[a.charAt(g++)]<<18-6*r;for(var s=16;m>o;s-=8){var t=Math.pow(2,s+8)-1;n[o++]=(f&t)>>s}}return n},System.Type.RegisterNamespace("System.Security.Cryptography"),System.Security.Cryptography.CryptographicException=function(a){this.message=a;var b=Error.create(this.message,{name:this.GetType().FullName});return b.popStackFrame(),b},System.Type.RegisterClass("System.Security.Cryptography.CryptographicException"),System.Security.Cryptography.CryptographicException=function(a){this.message=a,this.toString=function(){return this.name+": "+this.message};var b=Error.create(this.message,{name:this.GetType().FullName});return b.popStackFrame(),b},System.Type.RegisterClass("System.Security.Cryptography.CryptographicException"),System.Security.Cryptography.ICryptoTransform=function(a,b,c){function d(a,b){var c;l?(c=k.Encrypt(k.Key,a,System.Security.Cryptography.CipherMode.ECB),System.Buffer.BlockCopy(c,0,b,0,m)):(c=k.Decrypt(k.Key,a,System.Security.Cryptography.CipherMode.ECB),System.Buffer.BlockCopy(c,0,b,0,m))}function e(a,b){var c=0;if(l){for(c=0;m>c;c++)n[c]^=a[c];d(n,b),System.Buffer.BlockCopy(b,0,n,0,m)}else{for(System.Buffer.BlockCopy(a,0,o,0,m),d(a,b),c=0;m>c;c++)b[c]^=n[c];System.Buffer.BlockCopy(o,0,n,0,m)}}function f(a,b){var c=0,e=0;if(l)for(c=0;q>c;c++){for(d(n,o),e=0;p>e;e++)b[e+c]=o[e]^a[e+c];System.Buffer.BlockCopy(n,p,n,0,m-p),System.Buffer.BlockCopy(b,c,n,m-p,p)}else for(c=0;q>c;c++)for(l=!0,d(n,o),l=!1,System.Buffer.BlockCopy(n,p,n,0,m-p),System.Buffer.BlockCopy(a,c,n,m-p,p),e=0;p>e;e++)b[e+c]=o[e]^a[e+c]}function g(a,b){throw"OFB isn't supported"}function h(a,b){throw"CTS  isn't supported"}function i(a,b,c,d){null==j&&(j=new System.Security.Cryptography.RNGCryptoServiceProvider);var e=new System.Byte(c);d?j.GetBytes(e):j.GetNonZeroBytes(e),System.Buffer.BlockCopy(e,0,a,b,c)}var j,k=null,l=!1,m=0,n=new Array,o=new Array,p=0,q=0;this.InputBlockSize=0,this.OutputBlockSize=0,this.CanTransformMultipleBlocks=!0,this.CanReuseTransform=!1,this._Transform=function(a,b){switch(k.Mode){case System.Security.Cryptography.CipherMode.ECB:d(a,b);break;case System.Security.Cryptography.CipherMode.CBC:e(a,b);break;case System.Security.Cryptography.CipherMode.CFB:f(a,b);break;case System.Security.Cryptography.CipherMode.OFB:g(a,b);break;case System.Security.Cryptography.CipherMode.CTS:h(a,b);break;default:var c="Unkown CipherMode"+k.Mode;throw c}},this._Padding=function(a,b,c){var d=m-c,e=d>0?d:m,f=new System.Byte(e),g=1,h=new Array,j=0;switch(k.Padding){case System.Security.Cryptography.PaddingMode.None:if(0!=d)throw new System.Security.Cryptography.CryptographicException("Invalid block length");case System.Security.Cryptography.PaddingMode.Zeros:for(j=0;j<f.length;j++)f[j]=0;0==d&&(g=2);break;case System.Security.Cryptography.PaddingMode.ANSIX923:f[f.length-1]=e,0==d&&(g=2);break;case System.Security.Cryptography.PaddingMode.ISO10126:i(f,0,f.length-1,!0),f[f.length-1]=e,0==d&&(g=2);break;case System.Security.Cryptography.PaddingMode.PKCS7:for(j=0;j<f.length;j++)f[j]=e;0==d&&(g=2);break;case System.Security.Cryptography.PaddingMode.RsaEsPkcs:i(f,1,f.length-2,!1),f[0]=0,f[f.length-2]=2,f[f.length-1]=0,0==d&&(g=2);break;case System.Security.Cryptography.PaddingMode.RsaEsOaep:var l=new System.Security.Cryptography.PKCS1Padding,n=new System.Security.Cryptography.PKCS1MaskGenerationMethod,o=new System.Security.Cryptography.SHA1CryptoServiceProvider,p=new System.Security.Cryptography.RNGCryptoServiceProvider;h=l.RsaEsOaepEncrypt(k,o,n,p,a)}var q=new System.Byte(m*g),r=new System.Byte(m*g);0==h.length?(System.Buffer.BlockCopy(a,b,q,0,c),(d>0||0==d&&2==g)&&System.Buffer.BlockCopy(f,0,q,c,e)):System.Buffer.BlockCopy(h,b,q,0,c+e);var s={};return s.blocksCount=g,s.iBuffer=q,s.oBuffer=r,s},this.Initialize=function(a,b){k=a,l=b,k&&(m=k.BlockSize>>3,this.InputBlockSize=m,this.OutputBlockSize=m,n=new System.Byte(m),System.Buffer.BlockCopy(k.IV,0,n,0,Math.min(m,k.IV.length)),o=new System.Byte(m),p=k.FeedbackSize>>3,0!=p&&(q=m/p),workBuff=new System.Byte(m),workout=new System.Byte(m))},this.Initialize.apply(this,arguments)},System.Type.RegisterClass("System.Security.Cryptography.ICryptoTransform"),System.Security.Cryptography.RNGCryptoServiceProvider=function(){var a;this.GetNonZeroBytes=function(b){for(var c=b.length,d=0;c>d;d++)b[d]=a.Next(1,256)},this.Initialize=function(){a=new System.Random},this.Initialize.apply(this,arguments)},System.Type.RegisterClass("System.Security.Cryptography.RNGCryptoServiceProvider"),System.Security.Cryptography.CipherMode=function(){},System.Security.Cryptography.CipherMode.prototype={CBC:1,ECB:2,OFB:3,CFB:4,CTS:5},System.Type.RegisterEnum("System.Security.Cryptography.CipherMode"),System.Security.Cryptography.PaddingMode=function(){},System.Security.Cryptography.PaddingMode.prototype={None:1,PKCS7:2,Zeros:3,ANSIX923:4,ISO10126:5,RsaEsPkcs:6,RsaEsOaep:7},System.Type.RegisterEnum("System.Security.Cryptography.PaddingMode"),System.Security.Cryptography.CryptoStreamMode=function(){},System.Security.Cryptography.CryptoStreamMode.prototype={Read:0,Write:1},System.Type.RegisterEnum("System.Security.Cryptography.CryptoStreamMode"),System.Type.RegisterNamespace("System.Security.Cryptography"),System.Security.Cryptography.RSAManaged=function(){},System.Security.Cryptography.RSAParameters=function(){this.Exponent=new Array,this.Modulus=new Array,this.D=new Array,this.DP=new Array,this.DQ=new Array,this.InverseQ=new Array,this.P=new Array,this.Q=new Array,this.Clone=function(a){var b=new System.Security.Cryptography.RSAParameters;return System.Array.Copy(this.Exponent,b.Exponent,this.Exponent.length),System.Array.Copy(this.Modulus,b.Modulus,this.Modulus.length),a&&(this.D&&System.Array.Copy(this.D,b.D,this.D.length),this.DP&&System.Array.Copy(this.DP,b.DP,this.DP.length),this.DQ&&System.Array.Copy(this.DQ,b.DQ,this.DQ.length),this.InverseQ&&System.Array.Copy(this.InverseQ,b.InverseQ,this.InverseQ.length),this.P&&System.Array.Copy(this.P,b.P,this.P.length),this.Q&&System.Array.Copy(this.Q,b.Q,this.Q.length)),b},this.Initialize=function(){},this.Initialize.apply(this,arguments)},System.Security.Cryptography.RSACryptoServiceProvider=function(){function a(){return null==f&&(f=NewKeyPair.call(this,!0)),f}function b(a,b){var b=new RegExp("<"+b+">(.*?)</"+b+">","gi"),c=a.match(b);if(!c)return null;var d=c[0].replace(b,"$1"),e=System.Convert.FromBase64String(d);return e}function c(a,b,c){this.Padding=b?System.Security.Cryptography.PaddingMode.RsaEsOaep:System.Security.Cryptography.PaddingMode.RsaEsPkcs,this.Mode=System.Security.Cryptography.CipherMode.ECB;var d=new System.Security.Cryptography.ICryptoTransform(this,!0),e=c?d._Padding(a,0,a.length).iBuffer:d._PaddingRemove(a,0,a.length);return e}function d(a,b){var c=System.Array.Clone(a);System.Array.Reverse(c);for(var d=h.FromBytes(b.Exponent),e=h.FromBytes(b.Modulus),f=(h.FromBytes(b.D),h.FromBytes(c)),g=h.PowMod(f,d,e),i=h.ToBytes(g),j=this.KeySize/8,k=i.length;j>k;k++)i.push(0);return System.Array.Reverse(i),i}function e(a,b,e){for(var f,g=this.KeySize/8-(e?41:11),h=new Array,i=0;i<b.length/g;i++){f=b.slice(i*g,(i+1)*g),System.Array.Reverse(f);var j=c.call(this,f,e,!0),k=d.call(this,j,a);h=h.concat(k)}return h}this.KeySize=512,this.BlockSize=512,this.FeedbackSize=512,this.IV=new Array,this.HashSize=160;var f=null,g=null,h=System.BigInt.Utils;this.ImportParameters=function(a){f=a.Clone(!0),g=null,this.KeySize=8*f.Modulus.length,this.BlockSize=this.KeySize,this.FeedbackSize=this.KeySize},this.FromXmlString=function(a){var c=new System.Security.Cryptography.RSAParameters,d=new RegExp("\\s","gi");a=a.replace(d,""),c.Exponent=b(a,"Exponent"),c.Modulus=b(a,"Modulus"),c.D=b(a,"D"),c.DP=b(a,"DP"),c.DQ=b(a,"DQ"),c.InverseQ=b(a,"InverseQ"),c.P=b(a,"P"),c.Q=b(a,"Q"),this.ImportParameters(c)},this.Encrypt=function(b,c){var d,f=a.call(this),g=f.Modulus.length;if(!c&&b.length>g-11)throw d="The data to be encrypted exceeds the maximum for this modulus of "+f.digitSize+" bytes. Maximum data size is "+(f.digitSize-11)+" bytes.",Trace.Write(d),new System.Security.Cryptography.CryptographicException(d);if(c&&b.length>g-42)throw d="The data to be encrypted exceeds the maximum for this modulus of "+f.digitSize+" bytes. Maximum data size is "+(f.digitSize-42)+" bytes.",Trace.Write(d),new System.Security.Cryptography.CryptographicException(d);return e.call(this,f,b,c)},this.Initialize=function(){1==arguments.length&&"number"==typeof arguments[0]&&(this.KeySize=arguments[0],this.BlockSize=this.KeySize,this.FeedbackSize=this.KeySize)},this.Initialize.apply(this,arguments)};var TCO=new function(){this.loadPubKey=function(a,b){var c=e(),d=document.createElement("script"),f=document.head||document.getElementsByTagName("head")[0]||document.documentElement;"sandbox"===a?d.src="https://sandbox.2checkout.com/checkout/api/script/publickey/"+c:d.src="https://www.2checkout.com/checkout/api/script/publickey/"+c,d.onload=d.onreadystatechange=function(){(!d.readyState||/loaded|complete/.test(d.readyState))&&(d.onload=d.onreadystatechange=null,f&&d.parentNode&&f.removeChild(d),d=void 0,"function"==typeof b&&b())},f.insertBefore(d,f.firstChild)},this.requestToken=function(d,e,g){var h=new m;if(h.fillTokenRequest(g,e),b(h,e)){publishableKey=f(h.publishableKey);var j=i();sellerId=h.sellerId;var k=encodeURI('{"sellerId" : "'+sellerId+'", "publicKey" : "'+publishableKey+'" , "userPref" : "'+j+'"}'),n=tokenRequestUrl+"1/"+sellerId+"/rs/preTokenService?",o="tcoJsonp",p="jsonCallback";l(n,o,p,k)||(k=encodeURI('{"sellerId" : "'+sellerId+'", "publicKey" : "'+publishableKey+'" , "userPref" : ""}')),ajax2co({url:n,type:h.httpMethod,contentType:"application/json",data:"payload="+k,processData:!1,jsonpCallback:p,dataType:"jsonp",jsonp:o,success:function(b,f,g){null!==b.response?(h.preToken=b.response.preToken,a(d,e,h)):null!==b.exception?c(e,b.exception.errorMsg,b.exception.errorCode):c(e)},error:function(a){c(e)}})}};var a=function(a,b,d){try{sellerId=d.sellerId;var e=encodeURI('{"sellerId":"'+sellerId+'","paymentMethod":"'+d.generatePaymentDetail()+'"}');ajax2co({url:d.tcoUrl+"1/"+sellerId+"/rs/tokenService?",contentType:"application/json",type:d.httpMethod,data:"payload="+e,processData:!1,jsonpCallback:"jsonCallback",dataType:"jsonp",jsonp:"tcoJsonp",success:function(d,e,f){null!==d.response?a(d,e,f):null!==d.exception?c(b,d.exception.errorMsg,d.exception.errorCode):c(b)},error:function(a){c(b)}})}catch(f){c(b)}},b=function(a,b){var e=!0;return a.expMonth=1===a.expMonth.toString().length?"0"+a.expMonth:a.expMonth,a.expYear=a.expYear.toString().length<4?"20"+a.expYear:a.expYear,a.cardNum=a.cardNum.replace(/[^0-9]+/g,""),a.cvv=a.cvv.replace(/[^0-9]+/g,""),d(a.cardNum)&&d(a.cvv)&&d(a.expMonth)&&d(a.expYear)?"undefined"==typeof publicKey&&(e=!1,c(b,"Missing publicKey.js",401)):(e=!1,c(b,"Missing Card Data",401)),e},c=function(a,b,c){"undefined"==typeof b&&"undefined"==typeof c&&(b="Unable to process the request",c=200),data={errorCode:c,
errorMsg:b},a(data)},d=function(a){return!isNaN(parseFloat(a))&&isFinite(a)},e=function(){var a=new Date,b=Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds());return b},f=function(a){var b,c,d,e,f,h,i,j="",k=0;for(a=g(a);k<a.length;)b=a.charCodeAt(k++),c=a.charCodeAt(k++),d=a.charCodeAt(k++),e=b>>2,f=(3&b)<<4|c>>4,h=(15&c)<<2|d>>6,i=63&d,isNaN(c)?h=i=64:isNaN(d)&&(i=64),j=j+n.charAt(e)+n.charAt(f)+n.charAt(h)+n.charAt(i);return j},g=function(a){a=a.replace(/\r\n/g,"\n");for(var b="",c=0;c<a.length;c++){var d=a.charCodeAt(c);128>d?b+=String.fromCharCode(d):d>127&&2048>d?(b+=String.fromCharCode(d>>6|192),b+=String.fromCharCode(63&d|128)):(b+=String.fromCharCode(d>>12|224),b+=String.fromCharCode(d>>6&63|128),b+=String.fromCharCode(63&d|128))}return b},h=function(a){var b="2048",c="<RSAKeyValue><Modulus>"+publicKey.m+"</Modulus><Exponent>"+publicKey.e+"</Exponent></RSAKeyValue>",d=new System.Security.Cryptography.RSACryptoServiceProvider(parseInt(b,10));d.FromXmlString(c);var e=System.Text.Encoding.UTF8.GetBytes(a),f=d.Encrypt(e,!1),g=System.Convert.ToBase64String(f);return g},i=function(){j(),parm4.jscall("2co_user_prefs");var a=document.getElementById("2co_user_prefs").value;return k(),f(a)},j=function(){if(!document.getElementById("2co_user_prefs")){var a=document.body||document.getElementsByTagName("body")[0],b=document.createElement("input");b.setAttribute("type","hidden"),b.setAttribute("id","2co_user_prefs"),a.appendChild(b)}},k=function(){var a=document.getElementById("2co_user_prefs");(a||a.parentNode)&&a.parentNode.removeChild(a)},l=function(a,b,c,d){var e=a+b+"="+c+"&"+d;return e.length<2048},m=function(){this.tcoUrl=tokenRequestUrl,this.cardType="CC",this.httpMethod="GET",this.sellerId="",this.pubAccessKey="",this.cardNum="",this.expMonth="",this.expYear="",this.cvv="",this.preToken="",this.generatePaymentDetail=function(){var a='{"paymentMethod":{"cardNum":"'+this.cardNum+'", "expMonth":"'+this.expMonth+'", "expYear":"'+this.expYear+'", "cvv":"'+this.cvv+'", "cardType":"'+this.cardType+'"}, "pubAccessKey":"'+this.publishableKey+'", "preToken":"'+this.preToken+'"}',b=h(a);return f(b)},this.fillTokenRequest=function(a,b){if("object"==typeof a)a.sellerId&&a.publishableKey&&a.ccNo&&a.expMonth&&a.expYear&&a.cvv?(this.sellerId=a.sellerId,this.publishableKey=a.publishableKey,this.cardNum=a.ccNo,this.expMonth=a.expMonth,this.expYear=a.expYear,this.cvv=a.cvv):c(b,"Missing Form Fields",401);else{var d=document.getElementById(a);d.sellerId&&d.publishableKey&&d.ccNo&&d.expMonth&&d.expYear&&d.cvv?(this.sellerId=d.sellerId.value,this.publishableKey=d.publishableKey.value,this.cardNum=d.ccNo.value,this.expMonth=d.expMonth.value,this.expYear=d.expYear.value,this.cvv=d.cvv.value):c(b,"Missing Form Fields",401)}}},n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("")};
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/pagination.js?ver=4fca74de5e3fa981b9659807f09e9e55 
jQuery(window).load(function() {
    "use strict";
	jQuery(document).on('click', '.lp-filter-pagination ul li a', function(e){
		e.preventDefault();
		jQuery('html, body').animate({scrollTop:0},500);
		var docHeight = jQuery( document ).height();
		jQuery( "body" ).prepend( '<div id="full-overlay"></div>' );
		jQuery('#full-overlay').css('height',docHeight+'px');
		jQuery('#content-grids').html(' ');
		jQuery('.solitaire-infinite-scroll').remove();
		jQuery('.lp-filter-pagination').hide('');
		jQuery('#content-grids').addClass('content-loading');
		var $this = jQuery(this);
		var navURL = $this.attr('href');
		jQuery.ajax({
                    type: "POST",
                    url: navURL,
                    success: function(response){
						
						jQuery('.page-container .content-grids-wraps').find('#content-grids').html('');
                        var $newElements = jQuery(response).find('#content-grids').html();
                        //var $newElements = jQuery(response).html();
						jQuery('.page-container .content-grids-wraps #content-grids').html($newElements);
						jQuery('.lp-filter-pagination').html('');
						jQuery('.lp-filter-pagination').html(jQuery(response).find('.lp-filter-pagination').html());
						jQuery( ".all-list-map" ).trigger('click');
						jQuery('#full-overlay').remove();
						jQuery('.lp-filter-pagination').show('');
						jQuery('#content-grids').removeClass('content-loading');
					}
					});
		});
		
		/* 
		jQuery(document).on('click', '.lp-filter-pagination-ajx ul li a', function(e){
		e.preventDefault();
		var $this = jQuery(this);
		var navURL = $this.attr('href');
		jQuery.ajax({
                    type: "POST",
                    url: navURL,
                    success: function(response){
						
						jQuery('.page-container .content-grids-wraps').find('#content-grids').html('');
                        var $newElements = jQuery(response).find('#content-grids').html();
                        //var $newElements = jQuery(response).html();
						jQuery('.page-container .content-grids-wraps #content-grids').html($newElements);
						jQuery('.lp-filter-pagination-ajx').html('');
						jQuery('.lp-filter-pagination-ajx').html(jQuery(response).find('.lp-filter-pagination').html());
						jQuery( ".all-list-map" ).trigger('click');
					}
					});
		});
		 */
		
		
	});
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/jquery.nicescroll.min.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/* jquery.nicescroll 3.6.0 InuYaksa*2014 MIT http://nicescroll.areaaperta.com */(function(f){"function"===typeof define&&define.amd?define(["jquery"],f):f(jQuery)})(function(f){var y=!1,D=!1,N=0,O=2E3,x=0,H=["webkit","ms","moz","o"],s=window.requestAnimationFrame||!1,t=window.cancelAnimationFrame||!1;if(!s)for(var P in H){var E=H[P];s||(s=window[E+"RequestAnimationFrame"]);t||(t=window[E+"CancelAnimationFrame"]||window[E+"CancelRequestAnimationFrame"])}var v=window.MutationObserver||window.WebKitMutationObserver||!1,I={zindex:"auto",cursoropacitymin:0,cursoropacitymax:1,cursorcolor:"#424242",
cursorwidth:"5px",cursorborder:"1px solid #fff",cursorborderradius:"5px",scrollspeed:60,mousescrollstep:24,touchbehavior:!1,hwacceleration:!0,usetransition:!0,boxzoom:!1,dblclickzoom:!0,gesturezoom:!0,grabcursorenabled:!0,autohidemode:!0,background:"",iframeautoresize:!0,cursorminheight:32,preservenativescrolling:!0,railoffset:!1,railhoffset:!1,bouncescroll:!0,spacebarenabled:!0,railpadding:{top:0,right:0,left:0,bottom:0},disableoutline:!0,horizrailenabled:!0,railalign:"right",railvalign:"bottom",
enabletranslate3d:!0,enablemousewheel:!0,enablekeyboard:!0,smoothscroll:!0,sensitiverail:!0,enablemouselockapi:!0,cursorfixedheight:!1,directionlockdeadzone:6,hidecursordelay:400,nativeparentscrolling:!0,enablescrollonselection:!0,overflowx:!0,overflowy:!0,cursordragspeed:.3,rtlmode:"auto",cursordragontouch:!1,oneaxismousemode:"auto",scriptpath:function(){var f=document.getElementsByTagName("script"),f=f[f.length-1].src.split("?")[0];return 0<f.split("/").length?f.split("/").slice(0,-1).join("/")+
"/":""}(),preventmultitouchscrolling:!0},F=!1,Q=function(){if(F)return F;var f=document.createElement("DIV"),c=f.style,h=navigator.userAgent,m=navigator.platform,d={haspointerlock:"pointerLockElement"in document||"webkitPointerLockElement"in document||"mozPointerLockElement"in document};d.isopera="opera"in window;d.isopera12=d.isopera&&"getUserMedia"in navigator;d.isoperamini="[object OperaMini]"===Object.prototype.toString.call(window.operamini);d.isie="all"in document&&"attachEvent"in f&&!d.isopera;
d.isieold=d.isie&&!("msInterpolationMode"in c);d.isie7=d.isie&&!d.isieold&&(!("documentMode"in document)||7==document.documentMode);d.isie8=d.isie&&"documentMode"in document&&8==document.documentMode;d.isie9=d.isie&&"performance"in window&&9<=document.documentMode;d.isie10=d.isie&&"performance"in window&&10==document.documentMode;d.isie11="msRequestFullscreen"in f&&11<=document.documentMode;d.isie9mobile=/iemobile.9/i.test(h);d.isie9mobile&&(d.isie9=!1);d.isie7mobile=!d.isie9mobile&&d.isie7&&/iemobile/i.test(h);
d.ismozilla="MozAppearance"in c;d.iswebkit="WebkitAppearance"in c;d.ischrome="chrome"in window;d.ischrome22=d.ischrome&&d.haspointerlock;d.ischrome26=d.ischrome&&"transition"in c;d.cantouch="ontouchstart"in document.documentElement||"ontouchstart"in window;d.hasmstouch=window.MSPointerEvent||!1;d.hasw3ctouch=window.PointerEvent||!1;d.ismac=/^mac$/i.test(m);d.isios=d.cantouch&&/iphone|ipad|ipod/i.test(m);d.isios4=d.isios&&!("seal"in Object);d.isios7=d.isios&&"webkitHidden"in document;d.isandroid=/android/i.test(h);
d.haseventlistener="addEventListener"in f;d.trstyle=!1;d.hastransform=!1;d.hastranslate3d=!1;d.transitionstyle=!1;d.hastransition=!1;d.transitionend=!1;m=["transform","msTransform","webkitTransform","MozTransform","OTransform"];for(h=0;h<m.length;h++)if("undefined"!=typeof c[m[h]]){d.trstyle=m[h];break}d.hastransform=!!d.trstyle;d.hastransform&&(c[d.trstyle]="translate3d(1px,2px,3px)",d.hastranslate3d=/translate3d/.test(c[d.trstyle]));d.transitionstyle=!1;d.prefixstyle="";d.transitionend=!1;for(var m=
"transition webkitTransition msTransition MozTransition OTransition OTransition KhtmlTransition".split(" "),n=" -webkit- -ms- -moz- -o- -o -khtml-".split(" "),p="transitionend webkitTransitionEnd msTransitionEnd transitionend otransitionend oTransitionEnd KhtmlTransitionEnd".split(" "),h=0;h<m.length;h++)if(m[h]in c){d.transitionstyle=m[h];d.prefixstyle=n[h];d.transitionend=p[h];break}d.ischrome26&&(d.prefixstyle=n[1]);d.hastransition=d.transitionstyle;a:{h=["-webkit-grab","-moz-grab","grab"];if(d.ischrome&&
!d.ischrome22||d.isie)h=[];for(m=0;m<h.length;m++)if(n=h[m],c.cursor=n,c.cursor==n){c=n;break a}c="url(//mail.google.com/mail/images/2/openhand.cur),n-resize"}d.cursorgrabvalue=c;d.hasmousecapture="setCapture"in f;d.hasMutationObserver=!1!==v;return F=d},R=function(k,c){function h(){var b=a.doc.css(e.trstyle);return b&&"matrix"==b.substr(0,6)?b.replace(/^.*\((.*)\)$/g,"$1").replace(/px/g,"").split(/, +/):!1}function m(){var b=a.win;if("zIndex"in b)return b.zIndex();for(;0<b.length&&9!=b[0].nodeType;){var g=
b.css("zIndex");if(!isNaN(g)&&0!=g)return parseInt(g);b=b.parent()}return!1}function d(b,g,q){g=b.css(g);b=parseFloat(g);return isNaN(b)?(b=w[g]||0,q=3==b?q?a.win.outerHeight()-a.win.innerHeight():a.win.outerWidth()-a.win.innerWidth():1,a.isie8&&b&&(b+=1),q?b:0):b}function n(b,g,q,c){a._bind(b,g,function(a){a=a?a:window.event;var c={original:a,target:a.target||a.srcElement,type:"wheel",deltaMode:"MozMousePixelScroll"==a.type?0:1,deltaX:0,deltaZ:0,preventDefault:function(){a.preventDefault?a.preventDefault():
a.returnValue=!1;return!1},stopImmediatePropagation:function(){a.stopImmediatePropagation?a.stopImmediatePropagation():a.cancelBubble=!0}};"mousewheel"==g?(c.deltaY=-.025*a.wheelDelta,a.wheelDeltaX&&(c.deltaX=-.025*a.wheelDeltaX)):c.deltaY=a.detail;return q.call(b,c)},c)}function p(b,g,c){var d,e;0==b.deltaMode?(d=-Math.floor(a.opt.mousescrollstep/54*b.deltaX),e=-Math.floor(a.opt.mousescrollstep/54*b.deltaY)):1==b.deltaMode&&(d=-Math.floor(b.deltaX*a.opt.mousescrollstep),e=-Math.floor(b.deltaY*a.opt.mousescrollstep));
g&&a.opt.oneaxismousemode&&0==d&&e&&(d=e,e=0,c&&(0>d?a.getScrollLeft()>=a.page.maxw:0>=a.getScrollLeft())&&(e=d,d=0));d&&(a.scrollmom&&a.scrollmom.stop(),a.lastdeltax+=d,a.debounced("mousewheelx",function(){var b=a.lastdeltax;a.lastdeltax=0;a.rail.drag||a.doScrollLeftBy(b)},15));if(e){if(a.opt.nativeparentscrolling&&c&&!a.ispage&&!a.zoomactive)if(0>e){if(a.getScrollTop()>=a.page.maxh)return!0}else if(0>=a.getScrollTop())return!0;a.scrollmom&&a.scrollmom.stop();a.lastdeltay+=e;a.debounced("mousewheely",
function(){var b=a.lastdeltay;a.lastdeltay=0;a.rail.drag||a.doScrollBy(b)},15)}b.stopImmediatePropagation();return b.preventDefault()}var a=this;this.version="3.6.0";this.name="nicescroll";this.me=c;this.opt={doc:f("body"),win:!1};f.extend(this.opt,I);this.opt.snapbackspeed=80;if(k)for(var G in a.opt)"undefined"!=typeof k[G]&&(a.opt[G]=k[G]);this.iddoc=(this.doc=a.opt.doc)&&this.doc[0]?this.doc[0].id||"":"";this.ispage=/^BODY|HTML/.test(a.opt.win?a.opt.win[0].nodeName:this.doc[0].nodeName);this.haswrapper=
!1!==a.opt.win;this.win=a.opt.win||(this.ispage?f(window):this.doc);this.docscroll=this.ispage&&!this.haswrapper?f(window):this.win;this.body=f("body");this.iframe=this.isfixed=this.viewport=!1;this.isiframe="IFRAME"==this.doc[0].nodeName&&"IFRAME"==this.win[0].nodeName;this.istextarea="TEXTAREA"==this.win[0].nodeName;this.forcescreen=!1;this.canshowonmouseevent="scroll"!=a.opt.autohidemode;this.page=this.view=this.onzoomout=this.onzoomin=this.onscrollcancel=this.onscrollend=this.onscrollstart=this.onclick=
this.ongesturezoom=this.onkeypress=this.onmousewheel=this.onmousemove=this.onmouseup=this.onmousedown=!1;this.scroll={x:0,y:0};this.scrollratio={x:0,y:0};this.cursorheight=20;this.scrollvaluemax=0;this.isrtlmode="auto"==this.opt.rtlmode?"rtl"==(this.win[0]==window?this.body:this.win).css("direction"):!0===this.opt.rtlmode;this.observerbody=this.observerremover=this.observer=this.scrollmom=this.scrollrunning=!1;do this.id="ascrail"+O++;while(document.getElementById(this.id));this.hasmousefocus=this.hasfocus=
this.zoomactive=this.zoom=this.selectiondrag=this.cursorfreezed=this.cursor=this.rail=!1;this.visibility=!0;this.hidden=this.locked=this.railslocked=!1;this.cursoractive=!0;this.wheelprevented=!1;this.overflowx=a.opt.overflowx;this.overflowy=a.opt.overflowy;this.nativescrollingarea=!1;this.checkarea=0;this.events=[];this.saved={};this.delaylist={};this.synclist={};this.lastdeltay=this.lastdeltax=0;this.detected=Q();var e=f.extend({},this.detected);this.ishwscroll=(this.canhwscroll=e.hastransform&&
a.opt.hwacceleration)&&a.haswrapper;this.hasreversehr=this.isrtlmode&&!e.iswebkit;this.istouchcapable=!1;!e.cantouch||e.isios||e.isandroid||!e.iswebkit&&!e.ismozilla||(this.istouchcapable=!0,e.cantouch=!1);a.opt.enablemouselockapi||(e.hasmousecapture=!1,e.haspointerlock=!1);this.debounced=function(b,g,c){var d=a.delaylist[b];a.delaylist[b]=g;d||setTimeout(function(){var g=a.delaylist[b];a.delaylist[b]=!1;g.call(a)},c)};var r=!1;this.synched=function(b,g){a.synclist[b]=g;(function(){r||(s(function(){r=
!1;for(var b in a.synclist){var g=a.synclist[b];g&&g.call(a);a.synclist[b]=!1}}),r=!0)})();return b};this.unsynched=function(b){a.synclist[b]&&(a.synclist[b]=!1)};this.css=function(b,g){for(var c in g)a.saved.css.push([b,c,b.css(c)]),b.css(c,g[c])};this.scrollTop=function(b){return"undefined"==typeof b?a.getScrollTop():a.setScrollTop(b)};this.scrollLeft=function(b){return"undefined"==typeof b?a.getScrollLeft():a.setScrollLeft(b)};var A=function(a,g,c,d,e,f,h){this.st=a;this.ed=g;this.spd=c;this.p1=
d||0;this.p2=e||1;this.p3=f||0;this.p4=h||1;this.ts=(new Date).getTime();this.df=this.ed-this.st};A.prototype={B2:function(a){return 3*a*a*(1-a)},B3:function(a){return 3*a*(1-a)*(1-a)},B4:function(a){return(1-a)*(1-a)*(1-a)},getNow:function(){var a=1-((new Date).getTime()-this.ts)/this.spd,g=this.B2(a)+this.B3(a)+this.B4(a);return 0>a?this.ed:this.st+Math.round(this.df*g)},update:function(a,g){this.st=this.getNow();this.ed=a;this.spd=g;this.ts=(new Date).getTime();this.df=this.ed-this.st;return this}};
if(this.ishwscroll){this.doc.translate={x:0,y:0,tx:"0px",ty:"0px"};e.hastranslate3d&&e.isios&&this.doc.css("-webkit-backface-visibility","hidden");this.getScrollTop=function(b){if(!b){if(b=h())return 16==b.length?-b[13]:-b[5];if(a.timerscroll&&a.timerscroll.bz)return a.timerscroll.bz.getNow()}return a.doc.translate.y};this.getScrollLeft=function(b){if(!b){if(b=h())return 16==b.length?-b[12]:-b[4];if(a.timerscroll&&a.timerscroll.bh)return a.timerscroll.bh.getNow()}return a.doc.translate.x};this.notifyScrollEvent=
function(a){var g=document.createEvent("UIEvents");g.initUIEvent("scroll",!1,!0,window,1);g.niceevent=!0;a.dispatchEvent(g)};var K=this.isrtlmode?1:-1;e.hastranslate3d&&a.opt.enabletranslate3d?(this.setScrollTop=function(b,g){a.doc.translate.y=b;a.doc.translate.ty=-1*b+"px";a.doc.css(e.trstyle,"translate3d("+a.doc.translate.tx+","+a.doc.translate.ty+",0px)");g||a.notifyScrollEvent(a.win[0])},this.setScrollLeft=function(b,g){a.doc.translate.x=b;a.doc.translate.tx=b*K+"px";a.doc.css(e.trstyle,"translate3d("+
a.doc.translate.tx+","+a.doc.translate.ty+",0px)");g||a.notifyScrollEvent(a.win[0])}):(this.setScrollTop=function(b,g){a.doc.translate.y=b;a.doc.translate.ty=-1*b+"px";a.doc.css(e.trstyle,"translate("+a.doc.translate.tx+","+a.doc.translate.ty+")");g||a.notifyScrollEvent(a.win[0])},this.setScrollLeft=function(b,g){a.doc.translate.x=b;a.doc.translate.tx=b*K+"px";a.doc.css(e.trstyle,"translate("+a.doc.translate.tx+","+a.doc.translate.ty+")");g||a.notifyScrollEvent(a.win[0])})}else this.getScrollTop=
function(){return a.docscroll.scrollTop()},this.setScrollTop=function(b){return a.docscroll.scrollTop(b)},this.getScrollLeft=function(){return a.detected.ismozilla&&a.isrtlmode?Math.abs(a.docscroll.scrollLeft()):a.docscroll.scrollLeft()},this.setScrollLeft=function(b){return a.docscroll.scrollLeft(a.detected.ismozilla&&a.isrtlmode?-b:b)};this.getTarget=function(a){return a?a.target?a.target:a.srcElement?a.srcElement:!1:!1};this.hasParent=function(a,g){if(!a)return!1;for(var c=a.target||a.srcElement||
a||!1;c&&c.id!=g;)c=c.parentNode||!1;return!1!==c};var w={thin:1,medium:3,thick:5};this.getDocumentScrollOffset=function(){return{top:window.pageYOffset||document.documentElement.scrollTop,left:window.pageXOffset||document.documentElement.scrollLeft}};this.getOffset=function(){if(a.isfixed){var b=a.win.offset(),g=a.getDocumentScrollOffset();b.top-=g.top;b.left-=g.left;return b}b=a.win.offset();if(!a.viewport)return b;g=a.viewport.offset();return{top:b.top-g.top,left:b.left-g.left}};this.updateScrollBar=
function(b){if(a.ishwscroll)a.rail.css({height:a.win.innerHeight()-(a.opt.railpadding.top+a.opt.railpadding.bottom)}),a.railh&&a.railh.css({width:a.win.innerWidth()-(a.opt.railpadding.left+a.opt.railpadding.right)});else{var g=a.getOffset(),c=g.top,e=g.left-(a.opt.railpadding.left+a.opt.railpadding.right),c=c+d(a.win,"border-top-width",!0),e=e+(a.rail.align?a.win.outerWidth()-d(a.win,"border-right-width")-a.rail.width:d(a.win,"border-left-width")),f=a.opt.railoffset;f&&(f.top&&(c+=f.top),a.rail.align&&
f.left&&(e+=f.left));a.railslocked||a.rail.css({top:c,left:e,height:(b?b.h:a.win.innerHeight())-(a.opt.railpadding.top+a.opt.railpadding.bottom)});a.zoom&&a.zoom.css({top:c+1,left:1==a.rail.align?e-20:e+a.rail.width+4});if(a.railh&&!a.railslocked){c=g.top;e=g.left;if(f=a.opt.railhoffset)f.top&&(c+=f.top),f.left&&(e+=f.left);b=a.railh.align?c+d(a.win,"border-top-width",!0)+a.win.innerHeight()-a.railh.height:c+d(a.win,"border-top-width",!0);e+=d(a.win,"border-left-width");a.railh.css({top:b-(a.opt.railpadding.top+
a.opt.railpadding.bottom),left:e,width:a.railh.width})}}};this.doRailClick=function(b,g,c){var e;a.railslocked||(a.cancelEvent(b),g?(g=c?a.doScrollLeft:a.doScrollTop,e=c?(b.pageX-a.railh.offset().left-a.cursorwidth/2)*a.scrollratio.x:(b.pageY-a.rail.offset().top-a.cursorheight/2)*a.scrollratio.y,g(e)):(g=c?a.doScrollLeftBy:a.doScrollBy,e=c?a.scroll.x:a.scroll.y,b=c?b.pageX-a.railh.offset().left:b.pageY-a.rail.offset().top,c=c?a.view.w:a.view.h,g(e>=b?c:-c)))};a.hasanimationframe=s;a.hascancelanimationframe=
t;a.hasanimationframe?a.hascancelanimationframe||(t=function(){a.cancelAnimationFrame=!0}):(s=function(a){return setTimeout(a,15-Math.floor(+new Date/1E3)%16)},t=clearInterval);this.init=function(){a.saved.css=[];if(e.isie7mobile||e.isoperamini)return!0;e.hasmstouch&&a.css(a.ispage?f("html"):a.win,{"-ms-touch-action":"none"});a.zindex="auto";a.zindex=a.ispage||"auto"!=a.opt.zindex?a.opt.zindex:m()||"auto";!a.ispage&&"auto"!=a.zindex&&a.zindex>x&&(x=a.zindex);a.isie&&0==a.zindex&&"auto"==a.opt.zindex&&
(a.zindex="auto");if(!a.ispage||!e.cantouch&&!e.isieold&&!e.isie9mobile){var b=a.docscroll;a.ispage&&(b=a.haswrapper?a.win:a.doc);e.isie9mobile||a.css(b,{"overflow-y":"hidden"});a.ispage&&e.isie7&&("BODY"==a.doc[0].nodeName?a.css(f("html"),{"overflow-y":"hidden"}):"HTML"==a.doc[0].nodeName&&a.css(f("body"),{"overflow-y":"hidden"}));!e.isios||a.ispage||a.haswrapper||a.css(f("body"),{"-webkit-overflow-scrolling":"touch"});var g=f(document.createElement("div"));g.css({position:"relative",top:0,"float":"right",
width:a.opt.cursorwidth,height:"0px","background-color":a.opt.cursorcolor,border:a.opt.cursorborder,"background-clip":"padding-box","-webkit-border-radius":a.opt.cursorborderradius,"-moz-border-radius":a.opt.cursorborderradius,"border-radius":a.opt.cursorborderradius});g.hborder=parseFloat(g.outerHeight()-g.innerHeight());g.addClass("nicescroll-cursors");a.cursor=g;var c=f(document.createElement("div"));c.attr("id",a.id);c.addClass("nicescroll-rails nicescroll-rails-vr");var d,h,k=["left","right",
"top","bottom"],J;for(J in k)h=k[J],(d=a.opt.railpadding[h])?c.css("padding-"+h,d+"px"):a.opt.railpadding[h]=0;c.append(g);c.width=Math.max(parseFloat(a.opt.cursorwidth),g.outerWidth());c.css({width:c.width+"px",zIndex:a.zindex,background:a.opt.background,cursor:"default"});c.visibility=!0;c.scrollable=!0;c.align="left"==a.opt.railalign?0:1;a.rail=c;g=a.rail.drag=!1;!a.opt.boxzoom||a.ispage||e.isieold||(g=document.createElement("div"),a.bind(g,"click",a.doZoom),a.bind(g,"mouseenter",function(){a.zoom.css("opacity",
a.opt.cursoropacitymax)}),a.bind(g,"mouseleave",function(){a.zoom.css("opacity",a.opt.cursoropacitymin)}),a.zoom=f(g),a.zoom.css({cursor:"pointer","z-index":a.zindex,backgroundImage:"url("+a.opt.scriptpath+"zoomico.png)",height:18,width:18,backgroundPosition:"0px 0px"}),a.opt.dblclickzoom&&a.bind(a.win,"dblclick",a.doZoom),e.cantouch&&a.opt.gesturezoom&&(a.ongesturezoom=function(b){1.5<b.scale&&a.doZoomIn(b);.8>b.scale&&a.doZoomOut(b);return a.cancelEvent(b)},a.bind(a.win,"gestureend",a.ongesturezoom)));
a.railh=!1;var l;a.opt.horizrailenabled&&(a.css(b,{"overflow-x":"hidden"}),g=f(document.createElement("div")),g.css({position:"absolute",top:0,height:a.opt.cursorwidth,width:"0px","background-color":a.opt.cursorcolor,border:a.opt.cursorborder,"background-clip":"padding-box","-webkit-border-radius":a.opt.cursorborderradius,"-moz-border-radius":a.opt.cursorborderradius,"border-radius":a.opt.cursorborderradius}),e.isieold&&g.css({overflow:"hidden"}),g.wborder=parseFloat(g.outerWidth()-g.innerWidth()),
g.addClass("nicescroll-cursors"),a.cursorh=g,l=f(document.createElement("div")),l.attr("id",a.id+"-hr"),l.addClass("nicescroll-rails nicescroll-rails-hr"),l.height=Math.max(parseFloat(a.opt.cursorwidth),g.outerHeight()),l.css({height:l.height+"px",zIndex:a.zindex,background:a.opt.background}),l.append(g),l.visibility=!0,l.scrollable=!0,l.align="top"==a.opt.railvalign?0:1,a.railh=l,a.railh.drag=!1);a.ispage?(c.css({position:"fixed",top:"0px",height:"100%"}),c.align?c.css({right:"0px"}):c.css({left:"0px"}),
a.body.append(c),a.railh&&(l.css({position:"fixed",left:"0px",width:"100%"}),l.align?l.css({bottom:"0px"}):l.css({top:"0px"}),a.body.append(l))):(a.ishwscroll?("static"==a.win.css("position")&&a.css(a.win,{position:"relative"}),b="HTML"==a.win[0].nodeName?a.body:a.win,f(b).scrollTop(0).scrollLeft(0),a.zoom&&(a.zoom.css({position:"absolute",top:1,right:0,"margin-right":c.width+4}),b.append(a.zoom)),c.css({position:"absolute",top:0}),c.align?c.css({right:0}):c.css({left:0}),b.append(c),l&&(l.css({position:"absolute",
left:0,bottom:0}),l.align?l.css({bottom:0}):l.css({top:0}),b.append(l))):(a.isfixed="fixed"==a.win.css("position"),b=a.isfixed?"fixed":"absolute",a.isfixed||(a.viewport=a.getViewport(a.win[0])),a.viewport&&(a.body=a.viewport,0==/fixed|absolute/.test(a.viewport.css("position"))&&a.css(a.viewport,{position:"relative"})),c.css({position:b}),a.zoom&&a.zoom.css({position:b}),a.updateScrollBar(),a.body.append(c),a.zoom&&a.body.append(a.zoom),a.railh&&(l.css({position:b}),a.body.append(l))),e.isios&&a.css(a.win,
{"-webkit-tap-highlight-color":"rgba(0,0,0,0)","-webkit-touch-callout":"none"}),e.isie&&a.opt.disableoutline&&a.win.attr("hideFocus","true"),e.iswebkit&&a.opt.disableoutline&&a.win.css({outline:"none"}));!1===a.opt.autohidemode?(a.autohidedom=!1,a.rail.css({opacity:a.opt.cursoropacitymax}),a.railh&&a.railh.css({opacity:a.opt.cursoropacitymax})):!0===a.opt.autohidemode||"leave"===a.opt.autohidemode?(a.autohidedom=f().add(a.rail),e.isie8&&(a.autohidedom=a.autohidedom.add(a.cursor)),a.railh&&(a.autohidedom=
a.autohidedom.add(a.railh)),a.railh&&e.isie8&&(a.autohidedom=a.autohidedom.add(a.cursorh))):"scroll"==a.opt.autohidemode?(a.autohidedom=f().add(a.rail),a.railh&&(a.autohidedom=a.autohidedom.add(a.railh))):"cursor"==a.opt.autohidemode?(a.autohidedom=f().add(a.cursor),a.railh&&(a.autohidedom=a.autohidedom.add(a.cursorh))):"hidden"==a.opt.autohidemode&&(a.autohidedom=!1,a.hide(),a.railslocked=!1);if(e.isie9mobile)a.scrollmom=new L(a),a.onmangotouch=function(){var b=a.getScrollTop(),c=a.getScrollLeft();
if(b==a.scrollmom.lastscrolly&&c==a.scrollmom.lastscrollx)return!0;var g=b-a.mangotouch.sy,e=c-a.mangotouch.sx;if(0!=Math.round(Math.sqrt(Math.pow(e,2)+Math.pow(g,2)))){var d=0>g?-1:1,f=0>e?-1:1,q=+new Date;a.mangotouch.lazy&&clearTimeout(a.mangotouch.lazy);80<q-a.mangotouch.tm||a.mangotouch.dry!=d||a.mangotouch.drx!=f?(a.scrollmom.stop(),a.scrollmom.reset(c,b),a.mangotouch.sy=b,a.mangotouch.ly=b,a.mangotouch.sx=c,a.mangotouch.lx=c,a.mangotouch.dry=d,a.mangotouch.drx=f,a.mangotouch.tm=q):(a.scrollmom.stop(),
a.scrollmom.update(a.mangotouch.sx-e,a.mangotouch.sy-g),a.mangotouch.tm=q,g=Math.max(Math.abs(a.mangotouch.ly-b),Math.abs(a.mangotouch.lx-c)),a.mangotouch.ly=b,a.mangotouch.lx=c,2<g&&(a.mangotouch.lazy=setTimeout(function(){a.mangotouch.lazy=!1;a.mangotouch.dry=0;a.mangotouch.drx=0;a.mangotouch.tm=0;a.scrollmom.doMomentum(30)},100)))}},c=a.getScrollTop(),l=a.getScrollLeft(),a.mangotouch={sy:c,ly:c,dry:0,sx:l,lx:l,drx:0,lazy:!1,tm:0},a.bind(a.docscroll,"scroll",a.onmangotouch);else{if(e.cantouch||
a.istouchcapable||a.opt.touchbehavior||e.hasmstouch){a.scrollmom=new L(a);a.ontouchstart=function(b){if(b.pointerType&&2!=b.pointerType&&"touch"!=b.pointerType)return!1;a.hasmoving=!1;if(!a.railslocked){var c;if(e.hasmstouch)for(c=b.target?b.target:!1;c;){var g=f(c).getNiceScroll();if(0<g.length&&g[0].me==a.me)break;if(0<g.length)return!1;if("DIV"==c.nodeName&&c.id==a.id)break;c=c.parentNode?c.parentNode:!1}a.cancelScroll();if((c=a.getTarget(b))&&/INPUT/i.test(c.nodeName)&&/range/i.test(c.type))return a.stopPropagation(b);
!("clientX"in b)&&"changedTouches"in b&&(b.clientX=b.changedTouches[0].clientX,b.clientY=b.changedTouches[0].clientY);a.forcescreen&&(g=b,b={original:b.original?b.original:b},b.clientX=g.screenX,b.clientY=g.screenY);a.rail.drag={x:b.clientX,y:b.clientY,sx:a.scroll.x,sy:a.scroll.y,st:a.getScrollTop(),sl:a.getScrollLeft(),pt:2,dl:!1};if(a.ispage||!a.opt.directionlockdeadzone)a.rail.drag.dl="f";else{var g=f(window).width(),d=f(window).height(),q=Math.max(document.body.scrollWidth,document.documentElement.scrollWidth),
h=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight),d=Math.max(0,h-d),g=Math.max(0,q-g);a.rail.drag.ck=!a.rail.scrollable&&a.railh.scrollable?0<d?"v":!1:a.rail.scrollable&&!a.railh.scrollable?0<g?"h":!1:!1;a.rail.drag.ck||(a.rail.drag.dl="f")}a.opt.touchbehavior&&a.isiframe&&e.isie&&(g=a.win.position(),a.rail.drag.x+=g.left,a.rail.drag.y+=g.top);a.hasmoving=!1;a.lastmouseup=!1;a.scrollmom.reset(b.clientX,b.clientY);if(!e.cantouch&&!this.istouchcapable&&!b.pointerType){if(!c||
!/INPUT|SELECT|TEXTAREA/i.test(c.nodeName))return!a.ispage&&e.hasmousecapture&&c.setCapture(),a.opt.touchbehavior?(c.onclick&&!c._onclick&&(c._onclick=c.onclick,c.onclick=function(b){if(a.hasmoving)return!1;c._onclick.call(this,b)}),a.cancelEvent(b)):a.stopPropagation(b);/SUBMIT|CANCEL|BUTTON/i.test(f(c).attr("type"))&&(pc={tg:c,click:!1},a.preventclick=pc)}}};a.ontouchend=function(b){if(!a.rail.drag)return!0;if(2==a.rail.drag.pt){if(b.pointerType&&2!=b.pointerType&&"touch"!=b.pointerType)return!1;
a.scrollmom.doMomentum();a.rail.drag=!1;if(a.hasmoving&&(a.lastmouseup=!0,a.hideCursor(),e.hasmousecapture&&document.releaseCapture(),!e.cantouch))return a.cancelEvent(b)}else if(1==a.rail.drag.pt)return a.onmouseup(b)};var n=a.opt.touchbehavior&&a.isiframe&&!e.hasmousecapture;a.ontouchmove=function(b,c){if(!a.rail.drag||b.targetTouches&&a.opt.preventmultitouchscrolling&&1<b.targetTouches.length||b.pointerType&&2!=b.pointerType&&"touch"!=b.pointerType)return!1;if(2==a.rail.drag.pt){if(e.cantouch&&
e.isios&&"undefined"==typeof b.original)return!0;a.hasmoving=!0;a.preventclick&&!a.preventclick.click&&(a.preventclick.click=a.preventclick.tg.onclick||!1,a.preventclick.tg.onclick=a.onpreventclick);b=f.extend({original:b},b);"changedTouches"in b&&(b.clientX=b.changedTouches[0].clientX,b.clientY=b.changedTouches[0].clientY);if(a.forcescreen){var g=b;b={original:b.original?b.original:b};b.clientX=g.screenX;b.clientY=g.screenY}var d,g=d=0;n&&!c&&(d=a.win.position(),g=-d.left,d=-d.top);var q=b.clientY+
d;d=q-a.rail.drag.y;var h=b.clientX+g,u=h-a.rail.drag.x,k=a.rail.drag.st-d;a.ishwscroll&&a.opt.bouncescroll?0>k?k=Math.round(k/2):k>a.page.maxh&&(k=a.page.maxh+Math.round((k-a.page.maxh)/2)):(0>k&&(q=k=0),k>a.page.maxh&&(k=a.page.maxh,q=0));var l;a.railh&&a.railh.scrollable&&(l=a.isrtlmode?u-a.rail.drag.sl:a.rail.drag.sl-u,a.ishwscroll&&a.opt.bouncescroll?0>l?l=Math.round(l/2):l>a.page.maxw&&(l=a.page.maxw+Math.round((l-a.page.maxw)/2)):(0>l&&(h=l=0),l>a.page.maxw&&(l=a.page.maxw,h=0)));g=!1;if(a.rail.drag.dl)g=
!0,"v"==a.rail.drag.dl?l=a.rail.drag.sl:"h"==a.rail.drag.dl&&(k=a.rail.drag.st);else{d=Math.abs(d);var u=Math.abs(u),z=a.opt.directionlockdeadzone;if("v"==a.rail.drag.ck){if(d>z&&u<=.3*d)return a.rail.drag=!1,!0;u>z&&(a.rail.drag.dl="f",f("body").scrollTop(f("body").scrollTop()))}else if("h"==a.rail.drag.ck){if(u>z&&d<=.3*u)return a.rail.drag=!1,!0;d>z&&(a.rail.drag.dl="f",f("body").scrollLeft(f("body").scrollLeft()))}}a.synched("touchmove",function(){a.rail.drag&&2==a.rail.drag.pt&&(a.prepareTransition&&
a.prepareTransition(0),a.rail.scrollable&&a.setScrollTop(k),a.scrollmom.update(h,q),a.railh&&a.railh.scrollable?(a.setScrollLeft(l),a.showCursor(k,l)):a.showCursor(k),e.isie10&&document.selection.clear())});e.ischrome&&a.istouchcapable&&(g=!1);if(g)return a.cancelEvent(b)}else if(1==a.rail.drag.pt)return a.onmousemove(b)}}a.onmousedown=function(b,c){if(!a.rail.drag||1==a.rail.drag.pt){if(a.railslocked)return a.cancelEvent(b);a.cancelScroll();a.rail.drag={x:b.clientX,y:b.clientY,sx:a.scroll.x,sy:a.scroll.y,
pt:1,hr:!!c};var g=a.getTarget(b);!a.ispage&&e.hasmousecapture&&g.setCapture();a.isiframe&&!e.hasmousecapture&&(a.saved.csspointerevents=a.doc.css("pointer-events"),a.css(a.doc,{"pointer-events":"none"}));a.hasmoving=!1;return a.cancelEvent(b)}};a.onmouseup=function(b){if(a.rail.drag){if(1!=a.rail.drag.pt)return!0;e.hasmousecapture&&document.releaseCapture();a.isiframe&&!e.hasmousecapture&&a.doc.css("pointer-events",a.saved.csspointerevents);a.rail.drag=!1;a.hasmoving&&a.triggerScrollEnd();return a.cancelEvent(b)}};
a.onmousemove=function(b){if(a.rail.drag&&1==a.rail.drag.pt){if(e.ischrome&&0==b.which)return a.onmouseup(b);a.cursorfreezed=!0;a.hasmoving=!0;if(a.rail.drag.hr){a.scroll.x=a.rail.drag.sx+(b.clientX-a.rail.drag.x);0>a.scroll.x&&(a.scroll.x=0);var c=a.scrollvaluemaxw;a.scroll.x>c&&(a.scroll.x=c)}else a.scroll.y=a.rail.drag.sy+(b.clientY-a.rail.drag.y),0>a.scroll.y&&(a.scroll.y=0),c=a.scrollvaluemax,a.scroll.y>c&&(a.scroll.y=c);a.synched("mousemove",function(){a.rail.drag&&1==a.rail.drag.pt&&(a.showCursor(),
a.rail.drag.hr?a.hasreversehr?a.doScrollLeft(a.scrollvaluemaxw-Math.round(a.scroll.x*a.scrollratio.x),a.opt.cursordragspeed):a.doScrollLeft(Math.round(a.scroll.x*a.scrollratio.x),a.opt.cursordragspeed):a.doScrollTop(Math.round(a.scroll.y*a.scrollratio.y),a.opt.cursordragspeed))});return a.cancelEvent(b)}};if(e.cantouch||a.opt.touchbehavior)a.onpreventclick=function(b){if(a.preventclick)return a.preventclick.tg.onclick=a.preventclick.click,a.preventclick=!1,a.cancelEvent(b)},a.bind(a.win,"mousedown",
a.ontouchstart),a.onclick=e.isios?!1:function(b){return a.lastmouseup?(a.lastmouseup=!1,a.cancelEvent(b)):!0},a.opt.grabcursorenabled&&e.cursorgrabvalue&&(a.css(a.ispage?a.doc:a.win,{cursor:e.cursorgrabvalue}),a.css(a.rail,{cursor:e.cursorgrabvalue}));else{var p=function(b){if(a.selectiondrag){if(b){var c=a.win.outerHeight();b=b.pageY-a.selectiondrag.top;0<b&&b<c&&(b=0);b>=c&&(b-=c);a.selectiondrag.df=b}0!=a.selectiondrag.df&&(a.doScrollBy(2*-Math.floor(a.selectiondrag.df/6)),a.debounced("doselectionscroll",
function(){p()},50))}};a.hasTextSelected="getSelection"in document?function(){return 0<document.getSelection().rangeCount}:"selection"in document?function(){return"None"!=document.selection.type}:function(){return!1};a.onselectionstart=function(b){a.ispage||(a.selectiondrag=a.win.offset())};a.onselectionend=function(b){a.selectiondrag=!1};a.onselectiondrag=function(b){a.selectiondrag&&a.hasTextSelected()&&a.debounced("selectionscroll",function(){p(b)},250)}}e.hasw3ctouch?(a.css(a.rail,{"touch-action":"none"}),
a.css(a.cursor,{"touch-action":"none"}),a.bind(a.win,"pointerdown",a.ontouchstart),a.bind(document,"pointerup",a.ontouchend),a.bind(document,"pointermove",a.ontouchmove)):e.hasmstouch?(a.css(a.rail,{"-ms-touch-action":"none"}),a.css(a.cursor,{"-ms-touch-action":"none"}),a.bind(a.win,"MSPointerDown",a.ontouchstart),a.bind(document,"MSPointerUp",a.ontouchend),a.bind(document,"MSPointerMove",a.ontouchmove),a.bind(a.cursor,"MSGestureHold",function(a){a.preventDefault()}),a.bind(a.cursor,"contextmenu",
function(a){a.preventDefault()})):this.istouchcapable&&(a.bind(a.win,"touchstart",a.ontouchstart),a.bind(document,"touchend",a.ontouchend),a.bind(document,"touchcancel",a.ontouchend),a.bind(document,"touchmove",a.ontouchmove));if(a.opt.cursordragontouch||!e.cantouch&&!a.opt.touchbehavior)a.rail.css({cursor:"default"}),a.railh&&a.railh.css({cursor:"default"}),a.jqbind(a.rail,"mouseenter",function(){if(!a.ispage&&!a.win.is(":visible"))return!1;a.canshowonmouseevent&&a.showCursor();a.rail.active=!0}),
a.jqbind(a.rail,"mouseleave",function(){a.rail.active=!1;a.rail.drag||a.hideCursor()}),a.opt.sensitiverail&&(a.bind(a.rail,"click",function(b){a.doRailClick(b,!1,!1)}),a.bind(a.rail,"dblclick",function(b){a.doRailClick(b,!0,!1)}),a.bind(a.cursor,"click",function(b){a.cancelEvent(b)}),a.bind(a.cursor,"dblclick",function(b){a.cancelEvent(b)})),a.railh&&(a.jqbind(a.railh,"mouseenter",function(){if(!a.ispage&&!a.win.is(":visible"))return!1;a.canshowonmouseevent&&a.showCursor();a.rail.active=!0}),a.jqbind(a.railh,
"mouseleave",function(){a.rail.active=!1;a.rail.drag||a.hideCursor()}),a.opt.sensitiverail&&(a.bind(a.railh,"click",function(b){a.doRailClick(b,!1,!0)}),a.bind(a.railh,"dblclick",function(b){a.doRailClick(b,!0,!0)}),a.bind(a.cursorh,"click",function(b){a.cancelEvent(b)}),a.bind(a.cursorh,"dblclick",function(b){a.cancelEvent(b)})));e.cantouch||a.opt.touchbehavior?(a.bind(e.hasmousecapture?a.win:document,"mouseup",a.ontouchend),a.bind(document,"mousemove",a.ontouchmove),a.onclick&&a.bind(document,"click",
a.onclick),a.opt.cursordragontouch&&(a.bind(a.cursor,"mousedown",a.onmousedown),a.bind(a.cursor,"mouseup",a.onmouseup),a.cursorh&&a.bind(a.cursorh,"mousedown",function(b){a.onmousedown(b,!0)}),a.cursorh&&a.bind(a.cursorh,"mouseup",a.onmouseup))):(a.bind(e.hasmousecapture?a.win:document,"mouseup",a.onmouseup),a.bind(document,"mousemove",a.onmousemove),a.onclick&&a.bind(document,"click",a.onclick),a.bind(a.cursor,"mousedown",a.onmousedown),a.bind(a.cursor,"mouseup",a.onmouseup),a.railh&&(a.bind(a.cursorh,
"mousedown",function(b){a.onmousedown(b,!0)}),a.bind(a.cursorh,"mouseup",a.onmouseup)),!a.ispage&&a.opt.enablescrollonselection&&(a.bind(a.win[0],"mousedown",a.onselectionstart),a.bind(document,"mouseup",a.onselectionend),a.bind(a.cursor,"mouseup",a.onselectionend),a.cursorh&&a.bind(a.cursorh,"mouseup",a.onselectionend),a.bind(document,"mousemove",a.onselectiondrag)),a.zoom&&(a.jqbind(a.zoom,"mouseenter",function(){a.canshowonmouseevent&&a.showCursor();a.rail.active=!0}),a.jqbind(a.zoom,"mouseleave",
function(){a.rail.active=!1;a.rail.drag||a.hideCursor()})));a.opt.enablemousewheel&&(a.isiframe||a.bind(e.isie&&a.ispage?document:a.win,"mousewheel",a.onmousewheel),a.bind(a.rail,"mousewheel",a.onmousewheel),a.railh&&a.bind(a.railh,"mousewheel",a.onmousewheelhr));a.ispage||e.cantouch||/HTML|^BODY/.test(a.win[0].nodeName)||(a.win.attr("tabindex")||a.win.attr({tabindex:N++}),a.jqbind(a.win,"focus",function(b){y=a.getTarget(b).id||!0;a.hasfocus=!0;a.canshowonmouseevent&&a.noticeCursor()}),a.jqbind(a.win,
"blur",function(b){y=!1;a.hasfocus=!1}),a.jqbind(a.win,"mouseenter",function(b){D=a.getTarget(b).id||!0;a.hasmousefocus=!0;a.canshowonmouseevent&&a.noticeCursor()}),a.jqbind(a.win,"mouseleave",function(){D=!1;a.hasmousefocus=!1;a.rail.drag||a.hideCursor()}))}a.onkeypress=function(b){if(a.railslocked&&0==a.page.maxh)return!0;b=b?b:window.e;var c=a.getTarget(b);if(c&&/INPUT|TEXTAREA|SELECT|OPTION/.test(c.nodeName)&&(!c.getAttribute("type")&&!c.type||!/submit|button|cancel/i.tp)||f(c).attr("contenteditable"))return!0;
if(a.hasfocus||a.hasmousefocus&&!y||a.ispage&&!y&&!D){c=b.keyCode;if(a.railslocked&&27!=c)return a.cancelEvent(b);var g=b.ctrlKey||!1,d=b.shiftKey||!1,e=!1;switch(c){case 38:case 63233:a.doScrollBy(72);e=!0;break;case 40:case 63235:a.doScrollBy(-72);e=!0;break;case 37:case 63232:a.railh&&(g?a.doScrollLeft(0):a.doScrollLeftBy(72),e=!0);break;case 39:case 63234:a.railh&&(g?a.doScrollLeft(a.page.maxw):a.doScrollLeftBy(-72),e=!0);break;case 33:case 63276:a.doScrollBy(a.view.h);e=!0;break;case 34:case 63277:a.doScrollBy(-a.view.h);
e=!0;break;case 36:case 63273:a.railh&&g?a.doScrollPos(0,0):a.doScrollTo(0);e=!0;break;case 35:case 63275:a.railh&&g?a.doScrollPos(a.page.maxw,a.page.maxh):a.doScrollTo(a.page.maxh);e=!0;break;case 32:a.opt.spacebarenabled&&(d?a.doScrollBy(a.view.h):a.doScrollBy(-a.view.h),e=!0);break;case 27:a.zoomactive&&(a.doZoom(),e=!0)}if(e)return a.cancelEvent(b)}};a.opt.enablekeyboard&&a.bind(document,e.isopera&&!e.isopera12?"keypress":"keydown",a.onkeypress);a.bind(document,"keydown",function(b){b.ctrlKey&&
(a.wheelprevented=!0)});a.bind(document,"keyup",function(b){b.ctrlKey||(a.wheelprevented=!1)});a.bind(window,"blur",function(b){a.wheelprevented=!1});a.bind(window,"resize",a.lazyResize);a.bind(window,"orientationchange",a.lazyResize);a.bind(window,"load",a.lazyResize);if(e.ischrome&&!a.ispage&&!a.haswrapper){var r=a.win.attr("style"),c=parseFloat(a.win.css("width"))+1;a.win.css("width",c);a.synched("chromefix",function(){a.win.attr("style",r)})}a.onAttributeChange=function(b){a.lazyResize(a.isieold?
250:30)};!1!==v&&(a.observerbody=new v(function(b){b.forEach(function(b){if("attributes"==b.type)return f("body").hasClass("modal-open")?a.hide():a.show()});if(document.body.scrollHeight!=a.page.maxh)return a.lazyResize(30)}),a.observerbody.observe(document.body,{childList:!0,subtree:!0,characterData:!1,attributes:!0,attributeFilter:["class"]}));a.ispage||a.haswrapper||(!1!==v?(a.observer=new v(function(b){b.forEach(a.onAttributeChange)}),a.observer.observe(a.win[0],{childList:!0,characterData:!1,
attributes:!0,subtree:!1}),a.observerremover=new v(function(b){b.forEach(function(b){if(0<b.removedNodes.length)for(var c in b.removedNodes)if(a&&b.removedNodes[c]==a.win[0])return a.remove()})}),a.observerremover.observe(a.win[0].parentNode,{childList:!0,characterData:!1,attributes:!1,subtree:!1})):(a.bind(a.win,e.isie&&!e.isie9?"propertychange":"DOMAttrModified",a.onAttributeChange),e.isie9&&a.win[0].attachEvent("onpropertychange",a.onAttributeChange),a.bind(a.win,"DOMNodeRemoved",function(b){b.target==
a.win[0]&&a.remove()})));!a.ispage&&a.opt.boxzoom&&a.bind(window,"resize",a.resizeZoom);a.istextarea&&a.bind(a.win,"mouseup",a.lazyResize);a.lazyResize(30)}if("IFRAME"==this.doc[0].nodeName){var M=function(){a.iframexd=!1;var b;try{b="contentDocument"in this?this.contentDocument:this.contentWindow.document}catch(c){a.iframexd=!0,b=!1}if(a.iframexd)return"console"in window&&console.log("NiceScroll error: policy restriced iframe"),!0;a.forcescreen=!0;a.isiframe&&(a.iframe={doc:f(b),html:a.doc.contents().find("html")[0],
body:a.doc.contents().find("body")[0]},a.getContentSize=function(){return{w:Math.max(a.iframe.html.scrollWidth,a.iframe.body.scrollWidth),h:Math.max(a.iframe.html.scrollHeight,a.iframe.body.scrollHeight)}},a.docscroll=f(a.iframe.body));if(!e.isios&&a.opt.iframeautoresize&&!a.isiframe){a.win.scrollTop(0);a.doc.height("");var g=Math.max(b.getElementsByTagName("html")[0].scrollHeight,b.body.scrollHeight);a.doc.height(g)}a.lazyResize(30);e.isie7&&a.css(f(a.iframe.html),{"overflow-y":"hidden"});a.css(f(a.iframe.body),
{"overflow-y":"hidden"});e.isios&&a.haswrapper&&a.css(f(b.body),{"-webkit-transform":"translate3d(0,0,0)"});"contentWindow"in this?a.bind(this.contentWindow,"scroll",a.onscroll):a.bind(b,"scroll",a.onscroll);a.opt.enablemousewheel&&a.bind(b,"mousewheel",a.onmousewheel);a.opt.enablekeyboard&&a.bind(b,e.isopera?"keypress":"keydown",a.onkeypress);if(e.cantouch||a.opt.touchbehavior)a.bind(b,"mousedown",a.ontouchstart),a.bind(b,"mousemove",function(b){return a.ontouchmove(b,!0)}),a.opt.grabcursorenabled&&
e.cursorgrabvalue&&a.css(f(b.body),{cursor:e.cursorgrabvalue});a.bind(b,"mouseup",a.ontouchend);a.zoom&&(a.opt.dblclickzoom&&a.bind(b,"dblclick",a.doZoom),a.ongesturezoom&&a.bind(b,"gestureend",a.ongesturezoom))};this.doc[0].readyState&&"complete"==this.doc[0].readyState&&setTimeout(function(){M.call(a.doc[0],!1)},500);a.bind(this.doc,"load",M)}};this.showCursor=function(b,c){a.cursortimeout&&(clearTimeout(a.cursortimeout),a.cursortimeout=0);if(a.rail){a.autohidedom&&(a.autohidedom.stop().css({opacity:a.opt.cursoropacitymax}),
a.cursoractive=!0);a.rail.drag&&1==a.rail.drag.pt||("undefined"!=typeof b&&!1!==b&&(a.scroll.y=Math.round(1*b/a.scrollratio.y)),"undefined"!=typeof c&&(a.scroll.x=Math.round(1*c/a.scrollratio.x)));a.cursor.css({height:a.cursorheight,top:a.scroll.y});if(a.cursorh){var d=a.hasreversehr?a.scrollvaluemaxw-a.scroll.x:a.scroll.x;!a.rail.align&&a.rail.visibility?a.cursorh.css({width:a.cursorwidth,left:d+a.rail.width}):a.cursorh.css({width:a.cursorwidth,left:d});a.cursoractive=!0}a.zoom&&a.zoom.stop().css({opacity:a.opt.cursoropacitymax})}};
this.hideCursor=function(b){a.cursortimeout||!a.rail||!a.autohidedom||a.hasmousefocus&&"leave"==a.opt.autohidemode||(a.cursortimeout=setTimeout(function(){a.rail.active&&a.showonmouseevent||(a.autohidedom.stop().animate({opacity:a.opt.cursoropacitymin}),a.zoom&&a.zoom.stop().animate({opacity:a.opt.cursoropacitymin}),a.cursoractive=!1);a.cursortimeout=0},b||a.opt.hidecursordelay))};this.noticeCursor=function(b,c,d){a.showCursor(c,d);a.rail.active||a.hideCursor(b)};this.getContentSize=a.ispage?function(){return{w:Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth),h:Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)}}:a.haswrapper?function(){return{w:a.doc.outerWidth()+parseInt(a.win.css("paddingLeft"))+parseInt(a.win.css("paddingRight")),h:a.doc.outerHeight()+parseInt(a.win.css("paddingTop"))+parseInt(a.win.css("paddingBottom"))}}:function(){return{w:a.docscroll[0].scrollWidth,h:a.docscroll[0].scrollHeight}};this.onResize=function(b,c){if(!a||!a.win)return!1;if(!a.haswrapper&&!a.ispage){if("none"==
a.win.css("display"))return a.visibility&&a.hideRail().hideRailHr(),!1;a.hidden||a.visibility||a.showRail().showRailHr()}var d=a.page.maxh,e=a.page.maxw,f=a.view.h,h=a.view.w;a.view={w:a.ispage?a.win.width():parseInt(a.win[0].clientWidth),h:a.ispage?a.win.height():parseInt(a.win[0].clientHeight)};a.page=c?c:a.getContentSize();a.page.maxh=Math.max(0,a.page.h-a.view.h);a.page.maxw=Math.max(0,a.page.w-a.view.w);if(a.page.maxh==d&&a.page.maxw==e&&a.view.w==h&&a.view.h==f){if(a.ispage)return a;d=a.win.offset();
if(a.lastposition&&(e=a.lastposition,e.top==d.top&&e.left==d.left))return a;a.lastposition=d}0==a.page.maxh?(a.hideRail(),a.scrollvaluemax=0,a.scroll.y=0,a.scrollratio.y=0,a.cursorheight=0,a.setScrollTop(0),a.rail.scrollable=!1):(a.page.maxh-=a.opt.railpadding.top+a.opt.railpadding.bottom,a.rail.scrollable=!0);0==a.page.maxw?(a.hideRailHr(),a.scrollvaluemaxw=0,a.scroll.x=0,a.scrollratio.x=0,a.cursorwidth=0,a.setScrollLeft(0),a.railh.scrollable=!1):(a.page.maxw-=a.opt.railpadding.left+a.opt.railpadding.right,
a.railh.scrollable=!0);a.railslocked=a.locked||0==a.page.maxh&&0==a.page.maxw;if(a.railslocked)return a.ispage||a.updateScrollBar(a.view),!1;a.hidden||a.visibility?a.hidden||a.railh.visibility||a.showRailHr():a.showRail().showRailHr();a.istextarea&&a.win.css("resize")&&"none"!=a.win.css("resize")&&(a.view.h-=20);a.cursorheight=Math.min(a.view.h,Math.round(a.view.h/a.page.h*a.view.h));a.cursorheight=a.opt.cursorfixedheight?a.opt.cursorfixedheight:Math.max(a.opt.cursorminheight,a.cursorheight);a.cursorwidth=
Math.min(a.view.w,Math.round(a.view.w/a.page.w*a.view.w));a.cursorwidth=a.opt.cursorfixedheight?a.opt.cursorfixedheight:Math.max(a.opt.cursorminheight,a.cursorwidth);a.scrollvaluemax=a.view.h-a.cursorheight-a.cursor.hborder-(a.opt.railpadding.top+a.opt.railpadding.bottom);a.railh&&(a.railh.width=0<a.page.maxh?a.view.w-a.rail.width:a.view.w,a.scrollvaluemaxw=a.railh.width-a.cursorwidth-a.cursorh.wborder-(a.opt.railpadding.left+a.opt.railpadding.right));a.ispage||a.updateScrollBar(a.view);a.scrollratio=
{x:a.page.maxw/a.scrollvaluemaxw,y:a.page.maxh/a.scrollvaluemax};a.getScrollTop()>a.page.maxh?a.doScrollTop(a.page.maxh):(a.scroll.y=Math.round(a.getScrollTop()*(1/a.scrollratio.y)),a.scroll.x=Math.round(a.getScrollLeft()*(1/a.scrollratio.x)),a.cursoractive&&a.noticeCursor());a.scroll.y&&0==a.getScrollTop()&&a.doScrollTo(Math.floor(a.scroll.y*a.scrollratio.y));return a};this.resize=a.onResize;this.lazyResize=function(b){b=isNaN(b)?30:b;a.debounced("resize",a.resize,b);return a};this.jqbind=function(b,
c,d){a.events.push({e:b,n:c,f:d,q:!0});f(b).bind(c,d)};this.bind=function(b,c,d,f){var h="jquery"in b?b[0]:b;"mousewheel"==c?window.addEventListener||"onwheel"in document?a._bind(h,"wheel",d,f||!1):(b="undefined"!=typeof document.onmousewheel?"mousewheel":"DOMMouseScroll",n(h,b,d,f||!1),"DOMMouseScroll"==b&&n(h,"MozMousePixelScroll",d,f||!1)):h.addEventListener?(e.cantouch&&/mouseup|mousedown|mousemove/.test(c)&&a._bind(h,"mousedown"==c?"touchstart":"mouseup"==c?"touchend":"touchmove",function(a){if(a.touches){if(2>
a.touches.length){var b=a.touches.length?a.touches[0]:a;b.original=a;d.call(this,b)}}else a.changedTouches&&(b=a.changedTouches[0],b.original=a,d.call(this,b))},f||!1),a._bind(h,c,d,f||!1),e.cantouch&&"mouseup"==c&&a._bind(h,"touchcancel",d,f||!1)):a._bind(h,c,function(b){(b=b||window.event||!1)&&b.srcElement&&(b.target=b.srcElement);"pageY"in b||(b.pageX=b.clientX+document.documentElement.scrollLeft,b.pageY=b.clientY+document.documentElement.scrollTop);return!1===d.call(h,b)||!1===f?a.cancelEvent(b):
!0})};e.haseventlistener?(this._bind=function(b,c,d,e){a.events.push({e:b,n:c,f:d,b:e,q:!1});b.addEventListener(c,d,e||!1)},this.cancelEvent=function(a){if(!a)return!1;a=a.original?a.original:a;a.preventDefault();a.stopPropagation();a.preventManipulation&&a.preventManipulation();return!1},this.stopPropagation=function(a){if(!a)return!1;a=a.original?a.original:a;a.stopPropagation();return!1},this._unbind=function(a,c,d,e){a.removeEventListener(c,d,e)}):(this._bind=function(b,c,d,e){a.events.push({e:b,
n:c,f:d,b:e,q:!1});b.attachEvent?b.attachEvent("on"+c,d):b["on"+c]=d},this.cancelEvent=function(a){a=window.event||!1;if(!a)return!1;a.cancelBubble=!0;a.cancel=!0;return a.returnValue=!1},this.stopPropagation=function(a){a=window.event||!1;if(!a)return!1;a.cancelBubble=!0;return!1},this._unbind=function(a,c,d,e){a.detachEvent?a.detachEvent("on"+c,d):a["on"+c]=!1});this.unbindAll=function(){for(var b=0;b<a.events.length;b++){var c=a.events[b];c.q?c.e.unbind(c.n,c.f):a._unbind(c.e,c.n,c.f,c.b)}};this.showRail=
function(){0==a.page.maxh||!a.ispage&&"none"==a.win.css("display")||(a.visibility=!0,a.rail.visibility=!0,a.rail.css("display","block"));return a};this.showRailHr=function(){if(!a.railh)return a;0==a.page.maxw||!a.ispage&&"none"==a.win.css("display")||(a.railh.visibility=!0,a.railh.css("display","block"));return a};this.hideRail=function(){a.visibility=!1;a.rail.visibility=!1;a.rail.css("display","none");return a};this.hideRailHr=function(){if(!a.railh)return a;a.railh.visibility=!1;a.railh.css("display",
"none");return a};this.show=function(){a.hidden=!1;a.railslocked=!1;return a.showRail().showRailHr()};this.hide=function(){a.hidden=!0;a.railslocked=!0;return a.hideRail().hideRailHr()};this.toggle=function(){return a.hidden?a.show():a.hide()};this.remove=function(){a.stop();a.cursortimeout&&clearTimeout(a.cursortimeout);a.doZoomOut();a.unbindAll();e.isie9&&a.win[0].detachEvent("onpropertychange",a.onAttributeChange);!1!==a.observer&&a.observer.disconnect();!1!==a.observerremover&&a.observerremover.disconnect();
!1!==a.observerbody&&a.observerbody.disconnect();a.events=null;a.cursor&&a.cursor.remove();a.cursorh&&a.cursorh.remove();a.rail&&a.rail.remove();a.railh&&a.railh.remove();a.zoom&&a.zoom.remove();for(var b=0;b<a.saved.css.length;b++){var c=a.saved.css[b];c[0].css(c[1],"undefined"==typeof c[2]?"":c[2])}a.saved=!1;a.me.data("__nicescroll","");var d=f.nicescroll;d.each(function(b){if(this&&this.id===a.id){delete d[b];for(var c=++b;c<d.length;c++,b++)d[b]=d[c];d.length--;d.length&&delete d[d.length]}});
for(var h in a)a[h]=null,delete a[h];a=null};this.scrollstart=function(b){this.onscrollstart=b;return a};this.scrollend=function(b){this.onscrollend=b;return a};this.scrollcancel=function(b){this.onscrollcancel=b;return a};this.zoomin=function(b){this.onzoomin=b;return a};this.zoomout=function(b){this.onzoomout=b;return a};this.isScrollable=function(a){a=a.target?a.target:a;if("OPTION"==a.nodeName)return!0;for(;a&&1==a.nodeType&&!/^BODY|HTML/.test(a.nodeName);){var c=f(a),c=c.css("overflowY")||c.css("overflowX")||
c.css("overflow")||"";if(/scroll|auto/.test(c))return a.clientHeight!=a.scrollHeight;a=a.parentNode?a.parentNode:!1}return!1};this.getViewport=function(a){for(a=a&&a.parentNode?a.parentNode:!1;a&&1==a.nodeType&&!/^BODY|HTML/.test(a.nodeName);){var c=f(a);if(/fixed|absolute/.test(c.css("position")))return c;var d=c.css("overflowY")||c.css("overflowX")||c.css("overflow")||"";if(/scroll|auto/.test(d)&&a.clientHeight!=a.scrollHeight||0<c.getNiceScroll().length)return c;a=a.parentNode?a.parentNode:!1}return!1};
this.triggerScrollEnd=function(){if(a.onscrollend){var b=a.getScrollLeft(),c=a.getScrollTop();a.onscrollend.call(a,{type:"scrollend",current:{x:b,y:c},end:{x:b,y:c}})}};this.onmousewheel=function(b){if(!a.wheelprevented){if(a.railslocked)return a.debounced("checkunlock",a.resize,250),!0;if(a.rail.drag)return a.cancelEvent(b);"auto"==a.opt.oneaxismousemode&&0!=b.deltaX&&(a.opt.oneaxismousemode=!1);if(a.opt.oneaxismousemode&&0==b.deltaX&&!a.rail.scrollable)return a.railh&&a.railh.scrollable?a.onmousewheelhr(b):
!0;var c=+new Date,d=!1;a.opt.preservenativescrolling&&a.checkarea+600<c&&(a.nativescrollingarea=a.isScrollable(b),d=!0);a.checkarea=c;if(a.nativescrollingarea)return!0;if(b=p(b,!1,d))a.checkarea=0;return b}};this.onmousewheelhr=function(b){if(!a.wheelprevented){if(a.railslocked||!a.railh.scrollable)return!0;if(a.rail.drag)return a.cancelEvent(b);var c=+new Date,d=!1;a.opt.preservenativescrolling&&a.checkarea+600<c&&(a.nativescrollingarea=a.isScrollable(b),d=!0);a.checkarea=c;return a.nativescrollingarea?
!0:a.railslocked?a.cancelEvent(b):p(b,!0,d)}};this.stop=function(){a.cancelScroll();a.scrollmon&&a.scrollmon.stop();a.cursorfreezed=!1;a.scroll.y=Math.round(a.getScrollTop()*(1/a.scrollratio.y));a.noticeCursor();return a};this.getTransitionSpeed=function(b){var c=Math.round(10*a.opt.scrollspeed);b=Math.min(c,Math.round(b/20*a.opt.scrollspeed));return 20<b?b:0};a.opt.smoothscroll?a.ishwscroll&&e.hastransition&&a.opt.usetransition&&a.opt.smoothscroll?(this.prepareTransition=function(b,c){var d=c?20<
b?b:0:a.getTransitionSpeed(b),f=d?e.prefixstyle+"transform "+d+"ms ease-out":"";a.lasttransitionstyle&&a.lasttransitionstyle==f||(a.lasttransitionstyle=f,a.doc.css(e.transitionstyle,f));return d},this.doScrollLeft=function(b,c){var d=a.scrollrunning?a.newscrolly:a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.scrollrunning?a.newscrollx:a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){var f=a.getScrollTop(),h=a.getScrollLeft();(0>(a.newscrolly-
f)*(c-f)||0>(a.newscrollx-h)*(b-h))&&a.cancelScroll();0==a.opt.bouncescroll&&(0>c?c=0:c>a.page.maxh&&(c=a.page.maxh),0>b?b=0:b>a.page.maxw&&(b=a.page.maxw));if(a.scrollrunning&&b==a.newscrollx&&c==a.newscrolly)return!1;a.newscrolly=c;a.newscrollx=b;a.newscrollspeed=d||!1;if(a.timer)return!1;a.timer=setTimeout(function(){var d=a.getScrollTop(),f=a.getScrollLeft(),h,k;h=b-f;k=c-d;h=Math.round(Math.sqrt(Math.pow(h,2)+Math.pow(k,2)));h=a.newscrollspeed&&1<a.newscrollspeed?a.newscrollspeed:a.getTransitionSpeed(h);
a.newscrollspeed&&1>=a.newscrollspeed&&(h*=a.newscrollspeed);a.prepareTransition(h,!0);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);0<h&&(!a.scrollrunning&&a.onscrollstart&&a.onscrollstart.call(a,{type:"scrollstart",current:{x:f,y:d},request:{x:b,y:c},end:{x:a.newscrollx,y:a.newscrolly},speed:h}),e.transitionend?a.scrollendtrapped||(a.scrollendtrapped=!0,a.bind(a.doc,e.transitionend,a.onScrollTransitionEnd,!1)):(a.scrollendtrapped&&clearTimeout(a.scrollendtrapped),a.scrollendtrapped=
setTimeout(a.onScrollTransitionEnd,h)),a.timerscroll={bz:new A(d,a.newscrolly,h,0,0,.58,1),bh:new A(f,a.newscrollx,h,0,0,.58,1)},a.cursorfreezed||(a.timerscroll.tm=setInterval(function(){a.showCursor(a.getScrollTop(),a.getScrollLeft())},60)));a.synched("doScroll-set",function(){a.timer=0;a.scrollendtrapped&&(a.scrollrunning=!0);a.setScrollTop(a.newscrolly);a.setScrollLeft(a.newscrollx);if(!a.scrollendtrapped)a.onScrollTransitionEnd()})},50)},this.cancelScroll=function(){if(!a.scrollendtrapped)return!0;
var b=a.getScrollTop(),c=a.getScrollLeft();a.scrollrunning=!1;e.transitionend||clearTimeout(e.transitionend);a.scrollendtrapped=!1;a._unbind(a.doc[0],e.transitionend,a.onScrollTransitionEnd);a.prepareTransition(0);a.setScrollTop(b);a.railh&&a.setScrollLeft(c);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);a.timerscroll=!1;a.cursorfreezed=!1;a.showCursor(b,c);return a},this.onScrollTransitionEnd=function(){a.scrollendtrapped&&a._unbind(a.doc[0],e.transitionend,a.onScrollTransitionEnd);
a.scrollendtrapped=!1;a.prepareTransition(0);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);a.timerscroll=!1;var b=a.getScrollTop(),c=a.getScrollLeft();a.setScrollTop(b);a.railh&&a.setScrollLeft(c);a.noticeCursor(!1,b,c);a.cursorfreezed=!1;0>b?b=0:b>a.page.maxh&&(b=a.page.maxh);0>c?c=0:c>a.page.maxw&&(c=a.page.maxw);if(b!=a.newscrolly||c!=a.newscrollx)return a.doScrollPos(c,b,a.opt.snapbackspeed);a.onscrollend&&a.scrollrunning&&a.triggerScrollEnd();a.scrollrunning=!1}):(this.doScrollLeft=
function(b,c){var d=a.scrollrunning?a.newscrolly:a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.scrollrunning?a.newscrollx:a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){function e(){if(a.cancelAnimationFrame)return!0;a.scrollrunning=!0;if(n=1-n)return a.timer=s(e)||1;var b=0,c,d,g=d=a.getScrollTop();if(a.dst.ay){g=a.bzscroll?a.dst.py+a.bzscroll.getNow()*a.dst.ay:a.newscrolly;c=g-d;if(0>c&&g<a.newscrolly||0<c&&g>a.newscrolly)g=a.newscrolly;
a.setScrollTop(g);g==a.newscrolly&&(b=1)}else b=1;d=c=a.getScrollLeft();if(a.dst.ax){d=a.bzscroll?a.dst.px+a.bzscroll.getNow()*a.dst.ax:a.newscrollx;c=d-c;if(0>c&&d<a.newscrollx||0<c&&d>a.newscrollx)d=a.newscrollx;a.setScrollLeft(d);d==a.newscrollx&&(b+=1)}else b+=1;2==b?(a.timer=0,a.cursorfreezed=!1,a.bzscroll=!1,a.scrollrunning=!1,0>g?g=0:g>a.page.maxh&&(g=a.page.maxh),0>d?d=0:d>a.page.maxw&&(d=a.page.maxw),d!=a.newscrollx||g!=a.newscrolly?a.doScrollPos(d,g):a.onscrollend&&a.triggerScrollEnd()):
a.timer=s(e)||1}c="undefined"==typeof c||!1===c?a.getScrollTop(!0):c;if(a.timer&&a.newscrolly==c&&a.newscrollx==b)return!0;a.timer&&t(a.timer);a.timer=0;var f=a.getScrollTop(),h=a.getScrollLeft();(0>(a.newscrolly-f)*(c-f)||0>(a.newscrollx-h)*(b-h))&&a.cancelScroll();a.newscrolly=c;a.newscrollx=b;a.bouncescroll&&a.rail.visibility||(0>a.newscrolly?a.newscrolly=0:a.newscrolly>a.page.maxh&&(a.newscrolly=a.page.maxh));a.bouncescroll&&a.railh.visibility||(0>a.newscrollx?a.newscrollx=0:a.newscrollx>a.page.maxw&&
(a.newscrollx=a.page.maxw));a.dst={};a.dst.x=b-h;a.dst.y=c-f;a.dst.px=h;a.dst.py=f;var k=Math.round(Math.sqrt(Math.pow(a.dst.x,2)+Math.pow(a.dst.y,2)));a.dst.ax=a.dst.x/k;a.dst.ay=a.dst.y/k;var l=0,m=k;0==a.dst.x?(l=f,m=c,a.dst.ay=1,a.dst.py=0):0==a.dst.y&&(l=h,m=b,a.dst.ax=1,a.dst.px=0);k=a.getTransitionSpeed(k);d&&1>=d&&(k*=d);a.bzscroll=0<k?a.bzscroll?a.bzscroll.update(m,k):new A(l,m,k,0,1,0,1):!1;if(!a.timer){(f==a.page.maxh&&c>=a.page.maxh||h==a.page.maxw&&b>=a.page.maxw)&&a.checkContentSize();
var n=1;a.cancelAnimationFrame=!1;a.timer=1;a.onscrollstart&&!a.scrollrunning&&a.onscrollstart.call(a,{type:"scrollstart",current:{x:h,y:f},request:{x:b,y:c},end:{x:a.newscrollx,y:a.newscrolly},speed:k});e();(f==a.page.maxh&&c>=f||h==a.page.maxw&&b>=h)&&a.checkContentSize();a.noticeCursor()}},this.cancelScroll=function(){a.timer&&t(a.timer);a.timer=0;a.bzscroll=!1;a.scrollrunning=!1;return a}):(this.doScrollLeft=function(b,c){var d=a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,
c){var d=a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){var e=b>a.page.maxw?a.page.maxw:b;0>e&&(e=0);var f=c>a.page.maxh?a.page.maxh:c;0>f&&(f=0);a.synched("scroll",function(){a.setScrollTop(f);a.setScrollLeft(e)})},this.cancelScroll=function(){});this.doScrollBy=function(b,c){var d=0,d=c?Math.floor((a.scroll.y-b)*a.scrollratio.y):(a.timer?a.newscrolly:a.getScrollTop(!0))-b;if(a.bouncescroll){var e=Math.round(a.view.h/2);d<-e?d=-e:d>a.page.maxh+e&&(d=a.page.maxh+e)}a.cursorfreezed=
!1;e=a.getScrollTop(!0);if(0>d&&0>=e)return a.noticeCursor();if(d>a.page.maxh&&e>=a.page.maxh)return a.checkContentSize(),a.noticeCursor();a.doScrollTop(d)};this.doScrollLeftBy=function(b,c){var d=0,d=c?Math.floor((a.scroll.x-b)*a.scrollratio.x):(a.timer?a.newscrollx:a.getScrollLeft(!0))-b;if(a.bouncescroll){var e=Math.round(a.view.w/2);d<-e?d=-e:d>a.page.maxw+e&&(d=a.page.maxw+e)}a.cursorfreezed=!1;e=a.getScrollLeft(!0);if(0>d&&0>=e||d>a.page.maxw&&e>=a.page.maxw)return a.noticeCursor();a.doScrollLeft(d)};
this.doScrollTo=function(b,c){c&&Math.round(b*a.scrollratio.y);a.cursorfreezed=!1;a.doScrollTop(b)};this.checkContentSize=function(){var b=a.getContentSize();b.h==a.page.h&&b.w==a.page.w||a.resize(!1,b)};a.onscroll=function(b){a.rail.drag||a.cursorfreezed||a.synched("scroll",function(){a.scroll.y=Math.round(a.getScrollTop()*(1/a.scrollratio.y));a.railh&&(a.scroll.x=Math.round(a.getScrollLeft()*(1/a.scrollratio.x)));a.noticeCursor()})};a.bind(a.docscroll,"scroll",a.onscroll);this.doZoomIn=function(b){if(!a.zoomactive){a.zoomactive=
!0;a.zoomrestore={style:{}};var c="position top left zIndex backgroundColor marginTop marginBottom marginLeft marginRight".split(" "),d=a.win[0].style,h;for(h in c){var k=c[h];a.zoomrestore.style[k]="undefined"!=typeof d[k]?d[k]:""}a.zoomrestore.style.width=a.win.css("width");a.zoomrestore.style.height=a.win.css("height");a.zoomrestore.padding={w:a.win.outerWidth()-a.win.width(),h:a.win.outerHeight()-a.win.height()};e.isios4&&(a.zoomrestore.scrollTop=f(window).scrollTop(),f(window).scrollTop(0));
a.win.css({position:e.isios4?"absolute":"fixed",top:0,left:0,"z-index":x+100,margin:"0px"});c=a.win.css("backgroundColor");(""==c||/transparent|rgba\(0, 0, 0, 0\)|rgba\(0,0,0,0\)/.test(c))&&a.win.css("backgroundColor","#fff");a.rail.css({"z-index":x+101});a.zoom.css({"z-index":x+102});a.zoom.css("backgroundPosition","0px -18px");a.resizeZoom();a.onzoomin&&a.onzoomin.call(a);return a.cancelEvent(b)}};this.doZoomOut=function(b){if(a.zoomactive)return a.zoomactive=!1,a.win.css("margin",""),a.win.css(a.zoomrestore.style),
e.isios4&&f(window).scrollTop(a.zoomrestore.scrollTop),a.rail.css({"z-index":a.zindex}),a.zoom.css({"z-index":a.zindex}),a.zoomrestore=!1,a.zoom.css("backgroundPosition","0px 0px"),a.onResize(),a.onzoomout&&a.onzoomout.call(a),a.cancelEvent(b)};this.doZoom=function(b){return a.zoomactive?a.doZoomOut(b):a.doZoomIn(b)};this.resizeZoom=function(){if(a.zoomactive){var b=a.getScrollTop();a.win.css({width:f(window).width()-a.zoomrestore.padding.w+"px",height:f(window).height()-a.zoomrestore.padding.h+"px"});
a.onResize();a.setScrollTop(Math.min(a.page.maxh,b))}};this.init();f.nicescroll.push(this)},L=function(f){var c=this;this.nc=f;this.steptime=this.lasttime=this.speedy=this.speedx=this.lasty=this.lastx=0;this.snapy=this.snapx=!1;this.demuly=this.demulx=0;this.lastscrolly=this.lastscrollx=-1;this.timer=this.chky=this.chkx=0;this.time=function(){return+new Date};this.reset=function(f,k){c.stop();var d=c.time();c.steptime=0;c.lasttime=d;c.speedx=0;c.speedy=0;c.lastx=f;c.lasty=k;c.lastscrollx=-1;c.lastscrolly=
-1};this.update=function(f,k){var d=c.time();c.steptime=d-c.lasttime;c.lasttime=d;var d=k-c.lasty,n=f-c.lastx,p=c.nc.getScrollTop(),a=c.nc.getScrollLeft(),p=p+d,a=a+n;c.snapx=0>a||a>c.nc.page.maxw;c.snapy=0>p||p>c.nc.page.maxh;c.speedx=n;c.speedy=d;c.lastx=f;c.lasty=k};this.stop=function(){c.nc.unsynched("domomentum2d");c.timer&&clearTimeout(c.timer);c.timer=0;c.lastscrollx=-1;c.lastscrolly=-1};this.doSnapy=function(f,k){var d=!1;0>k?(k=0,d=!0):k>c.nc.page.maxh&&(k=c.nc.page.maxh,d=!0);0>f?(f=0,d=
!0):f>c.nc.page.maxw&&(f=c.nc.page.maxw,d=!0);d?c.nc.doScrollPos(f,k,c.nc.opt.snapbackspeed):c.nc.triggerScrollEnd()};this.doMomentum=function(f){var k=c.time(),d=f?k+f:c.lasttime;f=c.nc.getScrollLeft();var n=c.nc.getScrollTop(),p=c.nc.page.maxh,a=c.nc.page.maxw;c.speedx=0<a?Math.min(60,c.speedx):0;c.speedy=0<p?Math.min(60,c.speedy):0;d=d&&60>=k-d;if(0>n||n>p||0>f||f>a)d=!1;f=c.speedx&&d?c.speedx:!1;if(c.speedy&&d&&c.speedy||f){var s=Math.max(16,c.steptime);50<s&&(f=s/50,c.speedx*=f,c.speedy*=f,s=
50);c.demulxy=0;c.lastscrollx=c.nc.getScrollLeft();c.chkx=c.lastscrollx;c.lastscrolly=c.nc.getScrollTop();c.chky=c.lastscrolly;var e=c.lastscrollx,r=c.lastscrolly,t=function(){var d=600<c.time()-k?.04:.02;c.speedx&&(e=Math.floor(c.lastscrollx-c.speedx*(1-c.demulxy)),c.lastscrollx=e,0>e||e>a)&&(d=.1);c.speedy&&(r=Math.floor(c.lastscrolly-c.speedy*(1-c.demulxy)),c.lastscrolly=r,0>r||r>p)&&(d=.1);c.demulxy=Math.min(1,c.demulxy+d);c.nc.synched("domomentum2d",function(){c.speedx&&(c.nc.getScrollLeft()!=
c.chkx&&c.stop(),c.chkx=e,c.nc.setScrollLeft(e));c.speedy&&(c.nc.getScrollTop()!=c.chky&&c.stop(),c.chky=r,c.nc.setScrollTop(r));c.timer||(c.nc.hideCursor(),c.doSnapy(e,r))});1>c.demulxy?c.timer=setTimeout(t,s):(c.stop(),c.nc.hideCursor(),c.doSnapy(e,r))};t()}else c.doSnapy(c.nc.getScrollLeft(),c.nc.getScrollTop())}},w=f.fn.scrollTop;f.cssHooks.pageYOffset={get:function(k,c,h){return(c=f.data(k,"__nicescroll")||!1)&&c.ishwscroll?c.getScrollTop():w.call(k)},set:function(k,c){var h=f.data(k,"__nicescroll")||
!1;h&&h.ishwscroll?h.setScrollTop(parseInt(c)):w.call(k,c);return this}};f.fn.scrollTop=function(k){if("undefined"==typeof k){var c=this[0]?f.data(this[0],"__nicescroll")||!1:!1;return c&&c.ishwscroll?c.getScrollTop():w.call(this)}return this.each(function(){var c=f.data(this,"__nicescroll")||!1;c&&c.ishwscroll?c.setScrollTop(parseInt(k)):w.call(f(this),k)})};var B=f.fn.scrollLeft;f.cssHooks.pageXOffset={get:function(k,c,h){return(c=f.data(k,"__nicescroll")||!1)&&c.ishwscroll?c.getScrollLeft():B.call(k)},
set:function(k,c){var h=f.data(k,"__nicescroll")||!1;h&&h.ishwscroll?h.setScrollLeft(parseInt(c)):B.call(k,c);return this}};f.fn.scrollLeft=function(k){if("undefined"==typeof k){var c=this[0]?f.data(this[0],"__nicescroll")||!1:!1;return c&&c.ishwscroll?c.getScrollLeft():B.call(this)}return this.each(function(){var c=f.data(this,"__nicescroll")||!1;c&&c.ishwscroll?c.setScrollLeft(parseInt(k)):B.call(f(this),k)})};var C=function(k){var c=this;this.length=0;this.name="nicescrollarray";this.each=function(d){for(var f=
0,h=0;f<c.length;f++)d.call(c[f],h++);return c};this.push=function(d){c[c.length]=d;c.length++};this.eq=function(d){return c[d]};if(k)for(var h=0;h<k.length;h++){var m=f.data(k[h],"__nicescroll")||!1;m&&(this[this.length]=m,this.length++)}return this};(function(f,c,h){for(var m=0;m<c.length;m++)h(f,c[m])})(C.prototype,"show hide toggle onResize resize remove stop doScrollPos".split(" "),function(f,c){f[c]=function(){var f=arguments;return this.each(function(){this[c].apply(this,f)})}});f.fn.getNiceScroll=
function(k){return"undefined"==typeof k?new C(this):this[k]&&f.data(this[k],"__nicescroll")||!1};f.extend(f.expr[":"],{nicescroll:function(k){return f.data(k,"__nicescroll")?!0:!1}});f.fn.niceScroll=function(k,c){"undefined"!=typeof c||"object"!=typeof k||"jquery"in k||(c=k,k=!1);c=f.extend({},c);var h=new C;"undefined"==typeof c&&(c={});k&&(c.doc=f(k),c.win=f(this));var m=!("doc"in c);m||"win"in c||(c.win=f(this));this.each(function(){var d=f(this).data("__nicescroll")||!1;d||(c.doc=m?f(this):c.doc,
d=new R(c,f(this)),f(this).data("__nicescroll",d));h.push(d)});return 1==h.length?h[0]:h};window.NiceScroll={getjQuery:function(){return f}};f.nicescroll||(f.nicescroll=new C,f.nicescroll.options=I)});
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/chosen.jquery.min.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/* Chosen v1.1.0 | (c) 2011-2013 by Harvest | MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md */
!function(){var a,AbstractChosen,Chosen,SelectParser,b,c={}.hasOwnProperty,d=function(a,b){function d(){this.constructor=a}for(var e in b)c.call(b,e)&&(a[e]=b[e]);return d.prototype=b.prototype,a.prototype=new d,a.__super__=b.prototype,a};SelectParser=function(){function SelectParser(){this.options_index=0,this.parsed=[]}return SelectParser.prototype.add_node=function(a){return"OPTGROUP"===a.nodeName.toUpperCase()?this.add_group(a):this.add_option(a)},SelectParser.prototype.add_group=function(a){var b,c,d,e,f,g;for(b=this.parsed.length,this.parsed.push({array_index:b,group:!0,label:this.escapeExpression(a.label),children:0,disabled:a.disabled}),f=a.childNodes,g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(this.add_option(c,b,a.disabled));return g},SelectParser.prototype.add_option=function(a,b,c){return"OPTION"===a.nodeName.toUpperCase()?(""!==a.text?(null!=b&&(this.parsed[b].children+=1),this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:a.value,text:a.text,html:a.innerHTML,selected:a.selected,disabled:c===!0?c:a.disabled,group_array_index:b,classes:a.className,style:a.style.cssText})):this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:!0}),this.options_index+=1):void 0},SelectParser.prototype.escapeExpression=function(a){var b,c;return null==a||a===!1?"":/[\&\<\>\"\'\`]/.test(a)?(b={"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},c=/&(?!\w+;)|[\<\>\"\'\`]/g,a.replace(c,function(a){return b[a]||"&amp;"})):a},SelectParser}(),SelectParser.select_to_array=function(a){var b,c,d,e,f;for(c=new SelectParser,f=a.childNodes,d=0,e=f.length;e>d;d++)b=f[d],c.add_node(b);return c.parsed},AbstractChosen=function(){function AbstractChosen(a,b){this.form_field=a,this.options=null!=b?b:{},AbstractChosen.browser_is_supported()&&(this.is_multiple=this.form_field.multiple,this.set_default_text(),this.set_default_values(),this.setup(),this.set_up_html(),this.register_observers())}return AbstractChosen.prototype.set_default_values=function(){var a=this;return this.click_test_action=function(b){return a.test_active_click(b)},this.activate_action=function(b){return a.activate_field(b)},this.active_field=!1,this.mouse_on_container=!1,this.results_showing=!1,this.result_highlighted=null,this.allow_single_deselect=null!=this.options.allow_single_deselect&&null!=this.form_field.options[0]&&""===this.form_field.options[0].text?this.options.allow_single_deselect:!1,this.disable_search_threshold=this.options.disable_search_threshold||0,this.disable_search=this.options.disable_search||!1,this.enable_split_word_search=null!=this.options.enable_split_word_search?this.options.enable_split_word_search:!0,this.group_search=null!=this.options.group_search?this.options.group_search:!0,this.search_contains=this.options.search_contains||!1,this.single_backstroke_delete=null!=this.options.single_backstroke_delete?this.options.single_backstroke_delete:!0,this.max_selected_options=this.options.max_selected_options||1/0,this.inherit_select_classes=this.options.inherit_select_classes||!1,this.display_selected_options=null!=this.options.display_selected_options?this.options.display_selected_options:!0,this.display_disabled_options=null!=this.options.display_disabled_options?this.options.display_disabled_options:!0},AbstractChosen.prototype.set_default_text=function(){return this.default_text=this.form_field.getAttribute("data-placeholder")?this.form_field.getAttribute("data-placeholder"):this.is_multiple?this.options.placeholder_text_multiple||this.options.placeholder_text||AbstractChosen.default_multiple_text:this.options.placeholder_text_single||this.options.placeholder_text||AbstractChosen.default_single_text,this.results_none_found=this.form_field.getAttribute("data-no_results_text")||this.options.no_results_text||AbstractChosen.default_no_result_text},AbstractChosen.prototype.mouse_enter=function(){return this.mouse_on_container=!0},AbstractChosen.prototype.mouse_leave=function(){return this.mouse_on_container=!1},AbstractChosen.prototype.input_focus=function(){var a=this;if(this.is_multiple){if(!this.active_field)return setTimeout(function(){return a.container_mousedown()},50)}else if(!this.active_field)return this.activate_field()},AbstractChosen.prototype.input_blur=function(){var a=this;return this.mouse_on_container?void 0:(this.active_field=!1,setTimeout(function(){return a.blur_test()},100))},AbstractChosen.prototype.results_option_build=function(a){var b,c,d,e,f;for(b="",f=this.results_data,d=0,e=f.length;e>d;d++)c=f[d],b+=c.group?this.result_add_group(c):this.result_add_option(c),(null!=a?a.first:void 0)&&(c.selected&&this.is_multiple?this.choice_build(c):c.selected&&!this.is_multiple&&this.single_set_selected_text(c.text));return b},AbstractChosen.prototype.result_add_option=function(a){var b,c;return a.search_match?this.include_option_in_results(a)?(b=[],a.disabled||a.selected&&this.is_multiple||b.push("active-result"),!a.disabled||a.selected&&this.is_multiple||b.push("disabled-result"),a.selected&&b.push("result-selected"),null!=a.group_array_index&&b.push("group-option"),""!==a.classes&&b.push(a.classes),c=document.createElement("li"),c.className=b.join(" "),c.style.cssText=a.style,c.setAttribute("data-option-array-index",a.array_index),c.innerHTML=a.search_text,this.outerHTML(c)):"":""},AbstractChosen.prototype.result_add_group=function(a){var b;return a.search_match||a.group_match?a.active_options>0?(b=document.createElement("li"),b.className="group-result",b.innerHTML=a.search_text,this.outerHTML(b)):"":""},AbstractChosen.prototype.results_update_field=function(){return this.set_default_text(),this.is_multiple||this.results_reset_cleanup(),this.result_clear_highlight(),this.results_build(),this.results_showing?this.winnow_results():void 0},AbstractChosen.prototype.reset_single_select_options=function(){var a,b,c,d,e;for(d=this.results_data,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.selected?e.push(a.selected=!1):e.push(void 0);return e},AbstractChosen.prototype.results_toggle=function(){return this.results_showing?this.results_hide():this.results_show()},AbstractChosen.prototype.results_search=function(){return this.results_showing?this.winnow_results():this.results_show()},AbstractChosen.prototype.winnow_results=function(){var a,b,c,d,e,f,g,h,i,j,k,l,m;for(this.no_results_clear(),e=0,g=this.get_search_text(),a=g.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),d=this.search_contains?"":"^",c=new RegExp(d+a,"i"),j=new RegExp(a,"i"),m=this.results_data,k=0,l=m.length;l>k;k++)b=m[k],b.search_match=!1,f=null,this.include_option_in_results(b)&&(b.group&&(b.group_match=!1,b.active_options=0),null!=b.group_array_index&&this.results_data[b.group_array_index]&&(f=this.results_data[b.group_array_index],0===f.active_options&&f.search_match&&(e+=1),f.active_options+=1),(!b.group||this.group_search)&&(b.search_text=b.group?b.label:b.html,b.search_match=this.search_string_match(b.search_text,c),b.search_match&&!b.group&&(e+=1),b.search_match?(g.length&&(h=b.search_text.search(j),i=b.search_text.substr(0,h+g.length)+"</em>"+b.search_text.substr(h+g.length),b.search_text=i.substr(0,h)+"<em>"+i.substr(h)),null!=f&&(f.group_match=!0)):null!=b.group_array_index&&this.results_data[b.group_array_index].search_match&&(b.search_match=!0)));return this.result_clear_highlight(),1>e&&g.length?(this.update_results_content(""),this.no_results(g)):(this.update_results_content(this.results_option_build()),this.winnow_results_set_highlight())},AbstractChosen.prototype.search_string_match=function(a,b){var c,d,e,f;if(b.test(a))return!0;if(this.enable_split_word_search&&(a.indexOf(" ")>=0||0===a.indexOf("["))&&(d=a.replace(/\[|\]/g,"").split(" "),d.length))for(e=0,f=d.length;f>e;e++)if(c=d[e],b.test(c))return!0},AbstractChosen.prototype.choices_count=function(){var a,b,c,d;if(null!=this.selected_option_count)return this.selected_option_count;for(this.selected_option_count=0,d=this.form_field.options,b=0,c=d.length;c>b;b++)a=d[b],a.selected&&(this.selected_option_count+=1);return this.selected_option_count},AbstractChosen.prototype.choices_click=function(a){return a.preventDefault(),this.results_showing||this.is_disabled?void 0:this.results_show()},AbstractChosen.prototype.keyup_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),b){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices_count()>0)return this.keydown_backstroke();if(!this.pending_backstroke)return this.result_clear_highlight(),this.results_search();break;case 13:if(a.preventDefault(),this.results_showing)return this.result_select(a);break;case 27:return this.results_showing&&this.results_hide(),!0;case 9:case 38:case 40:case 16:case 91:case 17:break;default:return this.results_search()}},AbstractChosen.prototype.clipboard_event_checker=function(){var a=this;return setTimeout(function(){return a.results_search()},50)},AbstractChosen.prototype.container_width=function(){return null!=this.options.width?this.options.width:""+this.form_field.offsetWidth+"px"},AbstractChosen.prototype.include_option_in_results=function(a){return this.is_multiple&&!this.display_selected_options&&a.selected?!1:!this.display_disabled_options&&a.disabled?!1:a.empty?!1:!0},AbstractChosen.prototype.search_results_touchstart=function(a){return this.touch_started=!0,this.search_results_mouseover(a)},AbstractChosen.prototype.search_results_touchmove=function(a){return this.touch_started=!1,this.search_results_mouseout(a)},AbstractChosen.prototype.search_results_touchend=function(a){return this.touch_started?this.search_results_mouseup(a):void 0},AbstractChosen.prototype.outerHTML=function(a){var b;return a.outerHTML?a.outerHTML:(b=document.createElement("div"),b.appendChild(a),b.innerHTML)},AbstractChosen.browser_is_supported=function(){return"Microsoft Internet Explorer"===window.navigator.appName?document.documentMode>=8:/iP(od|hone)/i.test(window.navigator.userAgent)?!0:/Android/i.test(window.navigator.userAgent)&&/Mobile/i.test(window.navigator.userAgent)?!0:!0},AbstractChosen.default_multiple_text="Select Some Options",AbstractChosen.default_single_text="Select an Option",AbstractChosen.default_no_result_text="No results match",AbstractChosen}(),a=jQuery,a.fn.extend({chosen:function(b){return AbstractChosen.browser_is_supported()?this.each(function(){var c,d;c=a(this),d=c.data("chosen"),"destroy"===b&&d?d.destroy():d||c.data("chosen",new Chosen(this,b))}):this}}),Chosen=function(c){function Chosen(){return b=Chosen.__super__.constructor.apply(this,arguments)}return d(Chosen,c),Chosen.prototype.setup=function(){return this.form_field_jq=a(this.form_field),this.current_selectedIndex=this.form_field.selectedIndex,this.is_rtl=this.form_field_jq.hasClass("chosen-rtl")},Chosen.prototype.set_up_html=function(){var b,c;return b=["chosen-container"],b.push("chosen-container-"+(this.is_multiple?"multi":"single")),this.inherit_select_classes&&this.form_field.className&&b.push(this.form_field.className),this.is_rtl&&b.push("chosen-rtl"),c={"class":b.join(" "),style:"width: "+this.container_width()+";",title:this.form_field.title},this.form_field.id.length&&(c.id=this.form_field.id.replace(/[^\w]/g,"_")+"_chosen"),this.container=a("<div />",c),this.is_multiple?this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="'+this.default_text+'" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>'):this.container.html('<a class="chosen-single chosen-default" tabindex="-1"><span>'+this.default_text+'</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>'),this.form_field_jq.hide().after(this.container),this.dropdown=this.container.find("div.chosen-drop").first(),this.search_field=this.container.find("input").first(),this.search_results=this.container.find("ul.chosen-results").first(),this.search_field_scale(),this.search_no_results=this.container.find("li.no-results").first(),this.is_multiple?(this.search_choices=this.container.find("ul.chosen-choices").first(),this.search_container=this.container.find("li.search-field").first()):(this.search_container=this.container.find("div.chosen-search").first(),this.selected_item=this.container.find(".chosen-single").first()),this.results_build(),this.set_tab_index(),this.set_label_behavior(),this.form_field_jq.trigger("chosen:ready",{chosen:this})},Chosen.prototype.register_observers=function(){var a=this;return this.container.bind("mousedown.chosen",function(b){a.container_mousedown(b)}),this.container.bind("mouseup.chosen",function(b){a.container_mouseup(b)}),this.container.bind("mouseenter.chosen",function(b){a.mouse_enter(b)}),this.container.bind("mouseleave.chosen",function(b){a.mouse_leave(b)}),this.search_results.bind("mouseup.chosen",function(b){a.search_results_mouseup(b)}),this.search_results.bind("mouseover.chosen",function(b){a.search_results_mouseover(b)}),this.search_results.bind("mouseout.chosen",function(b){a.search_results_mouseout(b)}),this.search_results.bind("mousewheel.chosen DOMMouseScroll.chosen",function(b){a.search_results_mousewheel(b)}),this.search_results.bind("touchstart.chosen",function(b){a.search_results_touchstart(b)}),this.search_results.bind("touchmove.chosen",function(b){a.search_results_touchmove(b)}),this.search_results.bind("touchend.chosen",function(b){a.search_results_touchend(b)}),this.form_field_jq.bind("chosen:updated.chosen",function(b){a.results_update_field(b)}),this.form_field_jq.bind("chosen:activate.chosen",function(b){a.activate_field(b)}),this.form_field_jq.bind("chosen:open.chosen",function(b){a.container_mousedown(b)}),this.form_field_jq.bind("chosen:close.chosen",function(b){a.input_blur(b)}),this.search_field.bind("blur.chosen",function(b){a.input_blur(b)}),this.search_field.bind("keyup.chosen",function(b){a.keyup_checker(b)}),this.search_field.bind("keydown.chosen",function(b){a.keydown_checker(b)}),this.search_field.bind("focus.chosen",function(b){a.input_focus(b)}),this.search_field.bind("cut.chosen",function(b){a.clipboard_event_checker(b)}),this.search_field.bind("paste.chosen",function(b){a.clipboard_event_checker(b)}),this.is_multiple?this.search_choices.bind("click.chosen",function(b){a.choices_click(b)}):this.container.bind("click.chosen",function(a){a.preventDefault()})},Chosen.prototype.destroy=function(){return a(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.search_field[0].tabIndex&&(this.form_field_jq[0].tabIndex=this.search_field[0].tabIndex),this.container.remove(),this.form_field_jq.removeData("chosen"),this.form_field_jq.show()},Chosen.prototype.search_field_disabled=function(){return this.is_disabled=this.form_field_jq[0].disabled,this.is_disabled?(this.container.addClass("chosen-disabled"),this.search_field[0].disabled=!0,this.is_multiple||this.selected_item.unbind("focus.chosen",this.activate_action),this.close_field()):(this.container.removeClass("chosen-disabled"),this.search_field[0].disabled=!1,this.is_multiple?void 0:this.selected_item.bind("focus.chosen",this.activate_action))},Chosen.prototype.container_mousedown=function(b){return this.is_disabled||(b&&"mousedown"===b.type&&!this.results_showing&&b.preventDefault(),null!=b&&a(b.target).hasClass("search-choice-close"))?void 0:(this.active_field?this.is_multiple||!b||a(b.target)[0]!==this.selected_item[0]&&!a(b.target).parents("a.chosen-single").length||(b.preventDefault(),this.results_toggle()):(this.is_multiple&&this.search_field.val(""),a(this.container[0].ownerDocument).bind("click.chosen",this.click_test_action),this.results_show()),this.activate_field())},Chosen.prototype.container_mouseup=function(a){return"ABBR"!==a.target.nodeName||this.is_disabled?void 0:this.results_reset(a)},Chosen.prototype.search_results_mousewheel=function(a){var b;return a.originalEvent&&(b=-a.originalEvent.wheelDelta||a.originalEvent.detail),null!=b?(a.preventDefault(),"DOMMouseScroll"===a.type&&(b=40*b),this.search_results.scrollTop(b+this.search_results.scrollTop())):void 0},Chosen.prototype.blur_test=function(){return!this.active_field&&this.container.hasClass("chosen-container-active")?this.close_field():void 0},Chosen.prototype.close_field=function(){return a(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.active_field=!1,this.results_hide(),this.container.removeClass("chosen-container-active"),this.clear_backstroke(),this.show_search_field_default(),this.search_field_scale()},Chosen.prototype.activate_field=function(){return this.container.addClass("chosen-container-active"),this.active_field=!0,this.search_field.val(this.search_field.val()),this.search_field.focus()},Chosen.prototype.test_active_click=function(b){var c;return c=a(b.target).closest(".chosen-container"),c.length&&this.container[0]===c[0]?this.active_field=!0:this.close_field()},Chosen.prototype.results_build=function(){return this.parsing=!0,this.selected_option_count=null,this.results_data=SelectParser.select_to_array(this.form_field),this.is_multiple?this.search_choices.find("li.search-choice").remove():this.is_multiple||(this.single_set_selected_text(),this.disable_search||this.form_field.options.length<=this.disable_search_threshold?(this.search_field[0].readOnly=!0,this.container.addClass("chosen-container-single-nosearch")):(this.search_field[0].readOnly=!1,this.container.removeClass("chosen-container-single-nosearch"))),this.update_results_content(this.results_option_build({first:!0})),this.search_field_disabled(),this.show_search_field_default(),this.search_field_scale(),this.parsing=!1},Chosen.prototype.result_do_highlight=function(a){var b,c,d,e,f;if(a.length){if(this.result_clear_highlight(),this.result_highlight=a,this.result_highlight.addClass("highlighted"),d=parseInt(this.search_results.css("maxHeight"),10),f=this.search_results.scrollTop(),e=d+f,c=this.result_highlight.position().top+this.search_results.scrollTop(),b=c+this.result_highlight.outerHeight(),b>=e)return this.search_results.scrollTop(b-d>0?b-d:0);if(f>c)return this.search_results.scrollTop(c)}},Chosen.prototype.result_clear_highlight=function(){return this.result_highlight&&this.result_highlight.removeClass("highlighted"),this.result_highlight=null},Chosen.prototype.results_show=function(){return this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.container.addClass("chosen-with-drop"),this.results_showing=!0,this.search_field.focus(),this.search_field.val(this.search_field.val()),this.winnow_results(),this.form_field_jq.trigger("chosen:showing_dropdown",{chosen:this}))},Chosen.prototype.update_results_content=function(a){return this.search_results.html(a)},Chosen.prototype.results_hide=function(){return this.results_showing&&(this.result_clear_highlight(),this.container.removeClass("chosen-with-drop"),this.form_field_jq.trigger("chosen:hiding_dropdown",{chosen:this})),this.results_showing=!1},Chosen.prototype.set_tab_index=function(){var a;return this.form_field.tabIndex?(a=this.form_field.tabIndex,this.form_field.tabIndex=-1,this.search_field[0].tabIndex=a):void 0},Chosen.prototype.set_label_behavior=function(){var b=this;return this.form_field_label=this.form_field_jq.parents("label"),!this.form_field_label.length&&this.form_field.id.length&&(this.form_field_label=a("label[for='"+this.form_field.id+"']")),this.form_field_label.length>0?this.form_field_label.bind("click.chosen",function(a){return b.is_multiple?b.container_mousedown(a):b.activate_field()}):void 0},Chosen.prototype.show_search_field_default=function(){return this.is_multiple&&this.choices_count()<1&&!this.active_field?(this.search_field.val(this.default_text),this.search_field.addClass("default")):(this.search_field.val(""),this.search_field.removeClass("default"))},Chosen.prototype.search_results_mouseup=function(b){var c;return c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first(),c.length?(this.result_highlight=c,this.result_select(b),this.search_field.focus()):void 0},Chosen.prototype.search_results_mouseover=function(b){var c;return c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first(),c?this.result_do_highlight(c):void 0},Chosen.prototype.search_results_mouseout=function(b){return a(b.target).hasClass("active-result")?this.result_clear_highlight():void 0},Chosen.prototype.choice_build=function(b){var c,d,e=this;return c=a("<li />",{"class":"search-choice"}).html("<span>"+b.html+"</span>"),b.disabled?c.addClass("search-choice-disabled"):(d=a("<a />",{"class":"search-choice-close","data-option-array-index":b.array_index}),d.bind("click.chosen",function(a){return e.choice_destroy_link_click(a)}),c.append(d)),this.search_container.before(c)},Chosen.prototype.choice_destroy_link_click=function(b){return b.preventDefault(),b.stopPropagation(),this.is_disabled?void 0:this.choice_destroy(a(b.target))},Chosen.prototype.choice_destroy=function(a){return this.result_deselect(a[0].getAttribute("data-option-array-index"))?(this.show_search_field_default(),this.is_multiple&&this.choices_count()>0&&this.search_field.val().length<1&&this.results_hide(),a.parents("li").first().remove(),this.search_field_scale()):void 0},Chosen.prototype.results_reset=function(){return this.reset_single_select_options(),this.form_field.options[0].selected=!0,this.single_set_selected_text(),this.show_search_field_default(),this.results_reset_cleanup(),this.form_field_jq.trigger("change"),this.active_field?this.results_hide():void 0},Chosen.prototype.results_reset_cleanup=function(){return this.current_selectedIndex=this.form_field.selectedIndex,this.selected_item.find("abbr").remove()},Chosen.prototype.result_select=function(a){var b,c;return this.result_highlight?(b=this.result_highlight,this.result_clear_highlight(),this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.is_multiple?b.removeClass("active-result"):this.reset_single_select_options(),c=this.results_data[b[0].getAttribute("data-option-array-index")],c.selected=!0,this.form_field.options[c.options_index].selected=!0,this.selected_option_count=null,this.is_multiple?this.choice_build(c):this.single_set_selected_text(c.text),(a.metaKey||a.ctrlKey)&&this.is_multiple||this.results_hide(),this.search_field.val(""),(this.is_multiple||this.form_field.selectedIndex!==this.current_selectedIndex)&&this.form_field_jq.trigger("change",{selected:this.form_field.options[c.options_index].value}),this.current_selectedIndex=this.form_field.selectedIndex,this.search_field_scale())):void 0},Chosen.prototype.single_set_selected_text=function(a){return null==a&&(a=this.default_text),a===this.default_text?this.selected_item.addClass("chosen-default"):(this.single_deselect_control_build(),this.selected_item.removeClass("chosen-default")),this.selected_item.find("span").text(a)},Chosen.prototype.result_deselect=function(a){var b;return b=this.results_data[a],this.form_field.options[b.options_index].disabled?!1:(b.selected=!1,this.form_field.options[b.options_index].selected=!1,this.selected_option_count=null,this.result_clear_highlight(),this.results_showing&&this.winnow_results(),this.form_field_jq.trigger("change",{deselected:this.form_field.options[b.options_index].value}),this.search_field_scale(),!0)},Chosen.prototype.single_deselect_control_build=function(){return this.allow_single_deselect?(this.selected_item.find("abbr").length||this.selected_item.find("span").first().after('<abbr class="search-choice-close"></abbr>'),this.selected_item.addClass("chosen-single-with-deselect")):void 0},Chosen.prototype.get_search_text=function(){return this.search_field.val()===this.default_text?"":a("<div/>").text(a.trim(this.search_field.val())).html()},Chosen.prototype.winnow_results_set_highlight=function(){var a,b;return b=this.is_multiple?[]:this.search_results.find(".result-selected.active-result"),a=b.length?b.first():this.search_results.find(".active-result").first(),null!=a?this.result_do_highlight(a):void 0},Chosen.prototype.no_results=function(b){var c;return c=a('<li class="no-results">'+this.results_none_found+' "<span></span>"</li>'),c.find("span").first().html(b),this.search_results.append(c),this.form_field_jq.trigger("chosen:no_results",{chosen:this})},Chosen.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove()},Chosen.prototype.keydown_arrow=function(){var a;return this.results_showing&&this.result_highlight?(a=this.result_highlight.nextAll("li.active-result").first())?this.result_do_highlight(a):void 0:this.results_show()},Chosen.prototype.keyup_arrow=function(){var a;return this.results_showing||this.is_multiple?this.result_highlight?(a=this.result_highlight.prevAll("li.active-result"),a.length?this.result_do_highlight(a.first()):(this.choices_count()>0&&this.results_hide(),this.result_clear_highlight())):void 0:this.results_show()},Chosen.prototype.keydown_backstroke=function(){var a;return this.pending_backstroke?(this.choice_destroy(this.pending_backstroke.find("a").first()),this.clear_backstroke()):(a=this.search_container.siblings("li.search-choice").last(),a.length&&!a.hasClass("search-choice-disabled")?(this.pending_backstroke=a,this.single_backstroke_delete?this.keydown_backstroke():this.pending_backstroke.addClass("search-choice-focus")):void 0)},Chosen.prototype.clear_backstroke=function(){return this.pending_backstroke&&this.pending_backstroke.removeClass("search-choice-focus"),this.pending_backstroke=null},Chosen.prototype.keydown_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),8!==b&&this.pending_backstroke&&this.clear_backstroke(),b){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:this.results_showing&&!this.is_multiple&&this.result_select(a),this.mouse_on_container=!1;break;case 13:a.preventDefault();break;case 38:a.preventDefault(),this.keyup_arrow();break;case 40:a.preventDefault(),this.keydown_arrow()}},Chosen.prototype.search_field_scale=function(){var b,c,d,e,f,g,h,i,j;if(this.is_multiple){for(d=0,h=0,f="position:absolute; left: -1000px; top: -1000px; display:none;",g=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"],i=0,j=g.length;j>i;i++)e=g[i],f+=e+":"+this.search_field.css(e)+";";return b=a("<div />",{style:f}),b.text(this.search_field.val()),a("body").append(b),h=b.width()+25,b.remove(),c=this.container.outerWidth(),h>c-10&&(h=c-10),this.search_field.css({width:h+"px"})}},Chosen}(AbstractChosen)}.call(this);
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/jquery-ui.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/*! jQuery UI - v1.12.1 - 2017-10-14
 * http://jqueryui.com
 * Includes: widget.js, position.js, data.js, disable-selection.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/draggable.js, widgets/droppable.js, widgets/resizable.js, widgets/selectable.js, widgets/sortable.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/selectmenu.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js
 * Copyright jQuery Foundation and other contributors; Licensed MIT */

(function(factory) {
    if (typeof define === "function" && define.amd) {

        // AMD. Register as an anonymous module.
        define(["jquery"], factory);
    } else {

        // Browser globals
        factory(jQuery);
    }
}(function($) {

    $.ui = $.ui || {};

    var version = $.ui.version = "1.12.1";


    /*!
     * jQuery UI Widget 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Widget
    //>>group: Core
    //>>description: Provides a factory for creating stateful widgets with a common API.
    //>>docs: http://api.jqueryui.com/jQuery.widget/
    //>>demos: http://jqueryui.com/widget/



    var widgetUuid = 0;
    var widgetSlice = Array.prototype.slice;

    $.cleanData = (function(orig) {
        return function(elems) {
            var events, elem, i;
            for (i = 0;
                (elem = elems[i]) != null; i++) {
                try {

                    // Only trigger remove when necessary to save time
                    events = $._data(elem, "events");
                    if (events && events.remove) {
                        $(elem).triggerHandler("remove");
                    }

                    // Http://bugs.jquery.com/ticket/8235
                } catch (e) {}
            }
            orig(elems);
        };
    })($.cleanData);

    $.widget = function(name, base, prototype) {
        var existingConstructor, constructor, basePrototype;

        // ProxiedPrototype allows the provided prototype to remain unmodified
        // so that it can be used as a mixin for multiple widgets (#8876)
        var proxiedPrototype = {};

        var namespace = name.split(".")[0];
        name = name.split(".")[1];
        var fullName = namespace + "-" + name;

        if (!prototype) {
            prototype = base;
            base = $.Widget;
        }

        if ($.isArray(prototype)) {
            prototype = $.extend.apply(null, [{}].concat(prototype));
        }

        // Create selector for plugin
        $.expr[":"][fullName.toLowerCase()] = function(elem) {
            return !!$.data(elem, fullName);
        };

        $[namespace] = $[namespace] || {};
        existingConstructor = $[namespace][name];
        constructor = $[namespace][name] = function(options, element) {

            // Allow instantiation without "new" keyword
            if (!this._createWidget) {
                return new constructor(options, element);
            }

            // Allow instantiation without initializing for simple inheritance
            // must use "new" keyword (the code above always passes args)
            if (arguments.length) {
                this._createWidget(options, element);
            }
        };

        // Extend with the existing constructor to carry over any static properties
        $.extend(constructor, existingConstructor, {
            version: prototype.version,

            // Copy the object used to create the prototype in case we need to
            // redefine the widget later
            _proto: $.extend({}, prototype),

            // Track widgets that inherit from this widget in case this widget is
            // redefined after a widget inherits from it
            _childConstructors: []
        });

        basePrototype = new base();

        // We need to make the options hash a property directly on the new instance
        // otherwise we'll modify the options hash on the prototype that we're
        // inheriting from
        basePrototype.options = $.widget.extend({}, basePrototype.options);
        $.each(prototype, function(prop, value) {
            if (!$.isFunction(value)) {
                proxiedPrototype[prop] = value;
                return;
            }
            proxiedPrototype[prop] = (function() {
                function _super() {
                    return base.prototype[prop].apply(this, arguments);
                }

                function _superApply(args) {
                    return base.prototype[prop].apply(this, args);
                }

                return function() {
                    var __super = this._super;
                    var __superApply = this._superApply;
                    var returnValue;

                    this._super = _super;
                    this._superApply = _superApply;

                    returnValue = value.apply(this, arguments);

                    this._super = __super;
                    this._superApply = __superApply;

                    return returnValue;
                };
            })();
        });
        constructor.prototype = $.widget.extend(basePrototype, {

            // TODO: remove support for widgetEventPrefix
            // always use the name + a colon as the prefix, e.g., draggable:start
            // don't prefix for widgets that aren't DOM-based
            widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
        }, proxiedPrototype, {
            constructor: constructor,
            namespace: namespace,
            widgetName: name,
            widgetFullName: fullName
        });

        // If this widget is being redefined then we need to find all widgets that
        // are inheriting from it and redefine all of them so that they inherit from
        // the new version of this widget. We're essentially trying to replace one
        // level in the prototype chain.
        if (existingConstructor) {
            $.each(existingConstructor._childConstructors, function(i, child) {
                var childPrototype = child.prototype;

                // Redefine the child widget using the same prototype that was
                // originally used, but inherit from the new version of the base
                $.widget(childPrototype.namespace + "." + childPrototype.widgetName, constructor,
                    child._proto);
            });

            // Remove the list of existing child constructors from the old constructor
            // so the old child constructors can be garbage collected
            delete existingConstructor._childConstructors;
        } else {
            base._childConstructors.push(constructor);
        }

        $.widget.bridge(name, constructor);

        return constructor;
    };

    $.widget.extend = function(target) {
        var input = widgetSlice.call(arguments, 1);
        var inputIndex = 0;
        var inputLength = input.length;
        var key;
        var value;

        for (; inputIndex < inputLength; inputIndex++) {
            for (key in input[inputIndex]) {
                value = input[inputIndex][key];
                if (input[inputIndex].hasOwnProperty(key) && value !== undefined) {

                    // Clone objects
                    if ($.isPlainObject(value)) {
                        target[key] = $.isPlainObject(target[key]) ?
                            $.widget.extend({}, target[key], value) :

                            // Don't extend strings, arrays, etc. with objects
                            $.widget.extend({}, value);

                        // Copy everything else by reference
                    } else {
                        target[key] = value;
                    }
                }
            }
        }
        return target;
    };

    $.widget.bridge = function(name, object) {
        var fullName = object.prototype.widgetFullName || name;
        $.fn[name] = function(options) {
            var isMethodCall = typeof options === "string";
            var args = widgetSlice.call(arguments, 1);
            var returnValue = this;

            if (isMethodCall) {

                // If this is an empty collection, we need to have the instance method
                // return undefined instead of the jQuery instance
                if (!this.length && options === "instance") {
                    returnValue = undefined;
                } else {
                    this.each(function() {
                        var methodValue;
                        var instance = $.data(this, fullName);

                        if (options === "instance") {
                            returnValue = instance;
                            return false;
                        }

                        if (!instance) {
                            return $.error("cannot call methods on " + name +
                                " prior to initialization; " +
                                "attempted to call method '" + options + "'");
                        }

                        if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
                            return $.error("no such method '" + options + "' for " + name +
                                " widget instance");
                        }

                        methodValue = instance[options].apply(instance, args);

                        if (methodValue !== instance && methodValue !== undefined) {
                            returnValue = methodValue && methodValue.jquery ?
                                returnValue.pushStack(methodValue.get()) :
                                methodValue;
                            return false;
                        }
                    });
                }
            } else {

                // Allow multiple hashes to be passed on init
                if (args.length) {
                    options = $.widget.extend.apply(null, [options].concat(args));
                }

                this.each(function() {
                    var instance = $.data(this, fullName);
                    if (instance) {
                        instance.option(options || {});
                        if (instance._init) {
                            instance._init();
                        }
                    } else {
                        $.data(this, fullName, new object(options, this));
                    }
                });
            }

            return returnValue;
        };
    };

    $.Widget = function( /* options, element */ ) {};
    $.Widget._childConstructors = [];

    $.Widget.prototype = {
        widgetName: "widget",
        widgetEventPrefix: "",
        defaultElement: "<div>",

        options: {
            classes: {},
            disabled: false,

            // Callbacks
            create: null
        },

        _createWidget: function(options, element) {
            element = $(element || this.defaultElement || this)[0];
            this.element = $(element);
            this.uuid = widgetUuid++;
            this.eventNamespace = "." + this.widgetName + this.uuid;

            this.bindings = $();
            this.hoverable = $();
            this.focusable = $();
            this.classesElementLookup = {};

            if (element !== this) {
                $.data(element, this.widgetFullName, this);
                this._on(true, this.element, {
                    remove: function(event) {
                        if (event.target === element) {
                            this.destroy();
                        }
                    }
                });
                this.document = $(element.style ?

                    // Element within the document
                    element.ownerDocument :

                    // Element is window or document
                    element.document || element);
                this.window = $(this.document[0].defaultView || this.document[0].parentWindow);
            }

            this.options = $.widget.extend({},
                this.options,
                this._getCreateOptions(),
                options);

            this._create();

            if (this.options.disabled) {
                this._setOptionDisabled(this.options.disabled);
            }

            this._trigger("create", null, this._getCreateEventData());
            this._init();
        },

        _getCreateOptions: function() {
            return {};
        },

        _getCreateEventData: $.noop,

        _create: $.noop,

        _init: $.noop,

        destroy: function() {
            var that = this;

            this._destroy();
            $.each(this.classesElementLookup, function(key, value) {
                that._removeClass(value, key);
            });

            // We can probably remove the unbind calls in 2.0
            // all event bindings should go through this._on()
            this.element
                .off(this.eventNamespace)
                .removeData(this.widgetFullName);
            this.widget()
                .off(this.eventNamespace)
                .removeAttr("aria-disabled");

            // Clean up events and states
            this.bindings.off(this.eventNamespace);
        },

        _destroy: $.noop,

        widget: function() {
            return this.element;
        },

        option: function(key, value) {
            var options = key;
            var parts;
            var curOption;
            var i;

            if (arguments.length === 0) {

                // Don't return a reference to the internal hash
                return $.widget.extend({}, this.options);
            }

            if (typeof key === "string") {

                // Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
                options = {};
                parts = key.split(".");
                key = parts.shift();
                if (parts.length) {
                    curOption = options[key] = $.widget.extend({}, this.options[key]);
                    for (i = 0; i < parts.length - 1; i++) {
                        curOption[parts[i]] = curOption[parts[i]] || {};
                        curOption = curOption[parts[i]];
                    }
                    key = parts.pop();
                    if (arguments.length === 1) {
                        return curOption[key] === undefined ? null : curOption[key];
                    }
                    curOption[key] = value;
                } else {
                    if (arguments.length === 1) {
                        return this.options[key] === undefined ? null : this.options[key];
                    }
                    options[key] = value;
                }
            }

            this._setOptions(options);

            return this;
        },

        _setOptions: function(options) {
            var key;

            for (key in options) {
                this._setOption(key, options[key]);
            }

            return this;
        },

        _setOption: function(key, value) {
            if (key === "classes") {
                this._setOptionClasses(value);
            }

            this.options[key] = value;

            if (key === "disabled") {
                this._setOptionDisabled(value);
            }

            return this;
        },

        _setOptionClasses: function(value) {
            var classKey, elements, currentElements;

            for (classKey in value) {
                currentElements = this.classesElementLookup[classKey];
                if (value[classKey] === this.options.classes[classKey] ||
                    !currentElements ||
                    !currentElements.length) {
                    continue;
                }

                // We are doing this to create a new jQuery object because the _removeClass() call
                // on the next line is going to destroy the reference to the current elements being
                // tracked. We need to save a copy of this collection so that we can add the new classes
                // below.
                elements = $(currentElements.get());
                this._removeClass(currentElements, classKey);

                // We don't use _addClass() here, because that uses this.options.classes
                // for generating the string of classes. We want to use the value passed in from
                // _setOption(), this is the new value of the classes option which was passed to
                // _setOption(). We pass this value directly to _classes().
                elements.addClass(this._classes({
                    element: elements,
                    keys: classKey,
                    classes: value,
                    add: true
                }));
            }
        },

        _setOptionDisabled: function(value) {
            this._toggleClass(this.widget(), this.widgetFullName + "-disabled", null, !!value);

            // If the widget is becoming disabled, then nothing is interactive
            if (value) {
                this._removeClass(this.hoverable, null, "ui-state-hover");
                this._removeClass(this.focusable, null, "ui-state-focus");
            }
        },

        enable: function() {
            return this._setOptions({ disabled: false });
        },

        disable: function() {
            return this._setOptions({ disabled: true });
        },

        _classes: function(options) {
            var full = [];
            var that = this;

            options = $.extend({
                element: this.element,
                classes: this.options.classes || {}
            }, options);

            function processClassString(classes, checkOption) {
                var current, i;
                for (i = 0; i < classes.length; i++) {
                    current = that.classesElementLookup[classes[i]] || $();
                    if (options.add) {
                        current = $($.unique(current.get().concat(options.element.get())));
                    } else {
                        current = $(current.not(options.element).get());
                    }
                    that.classesElementLookup[classes[i]] = current;
                    full.push(classes[i]);
                    if (checkOption && options.classes[classes[i]]) {
                        full.push(options.classes[classes[i]]);
                    }
                }
            }

            this._on(options.element, {
                "remove": "_untrackClassesElement"
            });

            if (options.keys) {
                processClassString(options.keys.match(/\S+/g) || [], true);
            }
            if (options.extra) {
                processClassString(options.extra.match(/\S+/g) || []);
            }

            return full.join(" ");
        },

        _untrackClassesElement: function(event) {
            var that = this;
            $.each(that.classesElementLookup, function(key, value) {
                if ($.inArray(event.target, value) !== -1) {
                    that.classesElementLookup[key] = $(value.not(event.target).get());
                }
            });
        },

        _removeClass: function(element, keys, extra) {
            return this._toggleClass(element, keys, extra, false);
        },

        _addClass: function(element, keys, extra) {
            return this._toggleClass(element, keys, extra, true);
        },

        _toggleClass: function(element, keys, extra, add) {
            add = (typeof add === "boolean") ? add : extra;
            var shift = (typeof element === "string" || element === null),
                options = {
                    extra: shift ? keys : extra,
                    keys: shift ? element : keys,
                    element: shift ? this.element : element,
                    add: add
                };
            options.element.toggleClass(this._classes(options), add);
            return this;
        },

        _on: function(suppressDisabledCheck, element, handlers) {
            var delegateElement;
            var instance = this;

            // No suppressDisabledCheck flag, shuffle arguments
            if (typeof suppressDisabledCheck !== "boolean") {
                handlers = element;
                element = suppressDisabledCheck;
                suppressDisabledCheck = false;
            }

            // No element argument, shuffle and use this.element
            if (!handlers) {
                handlers = element;
                element = this.element;
                delegateElement = this.widget();
            } else {
                element = delegateElement = $(element);
                this.bindings = this.bindings.add(element);
            }

            $.each(handlers, function(event, handler) {
                function handlerProxy() {

                    // Allow widgets to customize the disabled handling
                    // - disabled as an array instead of boolean
                    // - disabled class as method for disabling individual parts
                    if (!suppressDisabledCheck &&
                        (instance.options.disabled === true ||
                            $(this).hasClass("ui-state-disabled"))) {
                        return;
                    }
                    return (typeof handler === "string" ? instance[handler] : handler)
                        .apply(instance, arguments);
                }

                // Copy the guid so direct unbinding works
                if (typeof handler !== "string") {
                    handlerProxy.guid = handler.guid =
                        handler.guid || handlerProxy.guid || $.guid++;
                }

                var match = event.match(/^([\w:-]*)\s*(.*)$/);
                var eventName = match[1] + instance.eventNamespace;
                var selector = match[2];

                if (selector) {
                    delegateElement.on(eventName, selector, handlerProxy);
                } else {
                    element.on(eventName, handlerProxy);
                }
            });
        },

        _off: function(element, eventName) {
            eventName = (eventName || "").split(" ").join(this.eventNamespace + " ") +
                this.eventNamespace;
            element.off(eventName).off(eventName);

            // Clear the stack to avoid memory leaks (#10056)
            this.bindings = $(this.bindings.not(element).get());
            this.focusable = $(this.focusable.not(element).get());
            this.hoverable = $(this.hoverable.not(element).get());
        },

        _delay: function(handler, delay) {
            function handlerProxy() {
                return (typeof handler === "string" ? instance[handler] : handler)
                    .apply(instance, arguments);
            }
            var instance = this;
            return setTimeout(handlerProxy, delay || 0);
        },

        _hoverable: function(element) {
            this.hoverable = this.hoverable.add(element);
            this._on(element, {
                mouseenter: function(event) {
                    this._addClass($(event.currentTarget), null, "ui-state-hover");
                },
                mouseleave: function(event) {
                    this._removeClass($(event.currentTarget), null, "ui-state-hover");
                }
            });
        },

        _focusable: function(element) {
            this.focusable = this.focusable.add(element);
            this._on(element, {
                focusin: function(event) {
                    this._addClass($(event.currentTarget), null, "ui-state-focus");
                },
                focusout: function(event) {
                    this._removeClass($(event.currentTarget), null, "ui-state-focus");
                }
            });
        },

        _trigger: function(type, event, data) {
            var prop, orig;
            var callback = this.options[type];

            data = data || {};
            event = $.Event(event);
            event.type = (type === this.widgetEventPrefix ?
                type :
                this.widgetEventPrefix + type).toLowerCase();

            // The original event may come from any element
            // so we need to reset the target on the new event
            event.target = this.element[0];

            // Copy original event properties over to the new event
            orig = event.originalEvent;
            if (orig) {
                for (prop in orig) {
                    if (!(prop in event)) {
                        event[prop] = orig[prop];
                    }
                }
            }

            this.element.trigger(event, data);
            return !($.isFunction(callback) &&
                callback.apply(this.element[0], [event].concat(data)) === false ||
                event.isDefaultPrevented());
        }
    };

    $.each({ show: "fadeIn", hide: "fadeOut" }, function(method, defaultEffect) {
        $.Widget.prototype["_" + method] = function(element, options, callback) {
            if (typeof options === "string") {
                options = { effect: options };
            }

            var hasOptions;
            var effectName = !options ?
                method :
                options === true || typeof options === "number" ?
                defaultEffect :
                options.effect || defaultEffect;

            options = options || {};
            if (typeof options === "number") {
                options = { duration: options };
            }

            hasOptions = !$.isEmptyObject(options);
            options.complete = callback;

            if (options.delay) {
                element.delay(options.delay);
            }

            if (hasOptions && $.effects && $.effects.effect[effectName]) {
                element[method](options);
            } else if (effectName !== method && element[effectName]) {
                element[effectName](options.duration, options.easing, callback);
            } else {
                element.queue(function(next) {
                    $(this)[method]();
                    if (callback) {
                        callback.call(element[0]);
                    }
                    next();
                });
            }
        };
    });

    var widget = $.widget;


    /*!
     * jQuery UI Position 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     *
     * http://api.jqueryui.com/position/
     */

    //>>label: Position
    //>>group: Core
    //>>description: Positions elements relative to other elements.
    //>>docs: http://api.jqueryui.com/position/
    //>>demos: http://jqueryui.com/position/


    (function() {
        var cachedScrollbarWidth,
            max = Math.max,
            abs = Math.abs,
            rhorizontal = /left|center|right/,
            rvertical = /top|center|bottom/,
            roffset = /[\+\-]\d+(\.[\d]+)?%?/,
            rposition = /^\w+/,
            rpercent = /%$/,
            _position = $.fn.position;

        function getOffsets(offsets, width, height) {
            return [
                parseFloat(offsets[0]) * (rpercent.test(offsets[0]) ? width / 100 : 1),
                parseFloat(offsets[1]) * (rpercent.test(offsets[1]) ? height / 100 : 1)
            ];
        }

        function parseCss(element, property) {
            return parseInt($.css(element, property), 10) || 0;
        }

        function getDimensions(elem) {
            var raw = elem[0];
            if (raw.nodeType === 9) {
                return {
                    width: elem.width(),
                    height: elem.height(),
                    offset: { top: 0, left: 0 }
                };
            }
            if ($.isWindow(raw)) {
                return {
                    width: elem.width(),
                    height: elem.height(),
                    offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
                };
            }
            if (raw.preventDefault) {
                return {
                    width: 0,
                    height: 0,
                    offset: { top: raw.pageY, left: raw.pageX }
                };
            }
            return {
                width: elem.outerWidth(),
                height: elem.outerHeight(),
                offset: elem.offset()
            };
        }

        $.position = {
            scrollbarWidth: function() {
                if (cachedScrollbarWidth !== undefined) {
                    return cachedScrollbarWidth;
                }
                var w1, w2,
                    div = $("<div " +
                        "style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" +
                        "<div style='height:100px;width:auto;'></div></div>"),
                    innerDiv = div.children()[0];

                $("body").append(div);
                w1 = innerDiv.offsetWidth;
                div.css("overflow", "scroll");

                w2 = innerDiv.offsetWidth;

                if (w1 === w2) {
                    w2 = div[0].clientWidth;
                }

                div.remove();

                return (cachedScrollbarWidth = w1 - w2);
            },
            getScrollInfo: function(within) {
                var overflowX = within.isWindow || within.isDocument ? "" :
                    within.element.css("overflow-x"),
                    overflowY = within.isWindow || within.isDocument ? "" :
                    within.element.css("overflow-y"),
                    hasOverflowX = overflowX === "scroll" ||
                    (overflowX === "auto" && within.width < within.element[0].scrollWidth),
                    hasOverflowY = overflowY === "scroll" ||
                    (overflowY === "auto" && within.height < within.element[0].scrollHeight);
                return {
                    width: hasOverflowY ? $.position.scrollbarWidth() : 0,
                    height: hasOverflowX ? $.position.scrollbarWidth() : 0
                };
            },
            getWithinInfo: function(element) {
                var withinElement = $(element || window),
                    isWindow = $.isWindow(withinElement[0]),
                    isDocument = !!withinElement[0] && withinElement[0].nodeType === 9,
                    hasOffset = !isWindow && !isDocument;
                return {
                    element: withinElement,
                    isWindow: isWindow,
                    isDocument: isDocument,
                    offset: hasOffset ? $(element).offset() : { left: 0, top: 0 },
                    scrollLeft: withinElement.scrollLeft(),
                    scrollTop: withinElement.scrollTop(),
                    width: withinElement.outerWidth(),
                    height: withinElement.outerHeight()
                };
            }
        };

        $.fn.position = function(options) {
            if (!options || !options.of) {
                return _position.apply(this, arguments);
            }

            // Make a copy, we don't want to modify arguments
            options = $.extend({}, options);

            var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
                target = $(options.of),
                within = $.position.getWithinInfo(options.within),
                scrollInfo = $.position.getScrollInfo(within),
                collision = (options.collision || "flip").split(" "),
                offsets = {};

            dimensions = getDimensions(target);
            if (target[0].preventDefault) {

                // Force left top to allow flipping
                options.at = "left top";
            }
            targetWidth = dimensions.width;
            targetHeight = dimensions.height;
            targetOffset = dimensions.offset;

            // Clone to reuse original targetOffset later
            basePosition = $.extend({}, targetOffset);

            // Force my and at to have valid horizontal and vertical positions
            // if a value is missing or invalid, it will be converted to center
            $.each(["my", "at"], function() {
                var pos = (options[this] || "").split(" "),
                    horizontalOffset,
                    verticalOffset;

                if (pos.length === 1) {
                    pos = rhorizontal.test(pos[0]) ?
                        pos.concat(["center"]) :
                        rvertical.test(pos[0]) ? ["center"].concat(pos) : ["center", "center"];
                }
                pos[0] = rhorizontal.test(pos[0]) ? pos[0] : "center";
                pos[1] = rvertical.test(pos[1]) ? pos[1] : "center";

                // Calculate offsets
                horizontalOffset = roffset.exec(pos[0]);
                verticalOffset = roffset.exec(pos[1]);
                offsets[this] = [
                    horizontalOffset ? horizontalOffset[0] : 0,
                    verticalOffset ? verticalOffset[0] : 0
                ];

                // Reduce to just the positions without the offsets
                options[this] = [
                    rposition.exec(pos[0])[0],
                    rposition.exec(pos[1])[0]
                ];
            });

            // Normalize collision option
            if (collision.length === 1) {
                collision[1] = collision[0];
            }

            if (options.at[0] === "right") {
                basePosition.left += targetWidth;
            } else if (options.at[0] === "center") {
                basePosition.left += targetWidth / 2;
            }

            if (options.at[1] === "bottom") {
                basePosition.top += targetHeight;
            } else if (options.at[1] === "center") {
                basePosition.top += targetHeight / 2;
            }

            atOffset = getOffsets(offsets.at, targetWidth, targetHeight);
            basePosition.left += atOffset[0];
            basePosition.top += atOffset[1];

            return this.each(function() {
                var collisionPosition, using,
                    elem = $(this),
                    elemWidth = elem.outerWidth(),
                    elemHeight = elem.outerHeight(),
                    marginLeft = parseCss(this, "marginLeft"),
                    marginTop = parseCss(this, "marginTop"),
                    collisionWidth = elemWidth + marginLeft + parseCss(this, "marginRight") +
                    scrollInfo.width,
                    collisionHeight = elemHeight + marginTop + parseCss(this, "marginBottom") +
                    scrollInfo.height,
                    position = $.extend({}, basePosition),
                    myOffset = getOffsets(offsets.my, elem.outerWidth(), elem.outerHeight());

                if (options.my[0] === "right") {
                    position.left -= elemWidth;
                } else if (options.my[0] === "center") {
                    position.left -= elemWidth / 2;
                }

                if (options.my[1] === "bottom") {
                    position.top -= elemHeight;
                } else if (options.my[1] === "center") {
                    position.top -= elemHeight / 2;
                }

                position.left += myOffset[0];
                position.top += myOffset[1];

                collisionPosition = {
                    marginLeft: marginLeft,
                    marginTop: marginTop
                };

                $.each(["left", "top"], function(i, dir) {
                    if ($.ui.position[collision[i]]) {
                        $.ui.position[collision[i]][dir](position, {
                            targetWidth: targetWidth,
                            targetHeight: targetHeight,
                            elemWidth: elemWidth,
                            elemHeight: elemHeight,
                            collisionPosition: collisionPosition,
                            collisionWidth: collisionWidth,
                            collisionHeight: collisionHeight,
                            offset: [atOffset[0] + myOffset[0], atOffset[1] + myOffset[1]],
                            my: options.my,
                            at: options.at,
                            within: within,
                            elem: elem
                        });
                    }
                });

                if (options.using) {

                    // Adds feedback as second argument to using callback, if present
                    using = function(props) {
                        var left = targetOffset.left - position.left,
                            right = left + targetWidth - elemWidth,
                            top = targetOffset.top - position.top,
                            bottom = top + targetHeight - elemHeight,
                            feedback = {
                                target: {
                                    element: target,
                                    left: targetOffset.left,
                                    top: targetOffset.top,
                                    width: targetWidth,
                                    height: targetHeight
                                },
                                element: {
                                    element: elem,
                                    left: position.left,
                                    top: position.top,
                                    width: elemWidth,
                                    height: elemHeight
                                },
                                horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
                                vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
                            };
                        if (targetWidth < elemWidth && abs(left + right) < targetWidth) {
                            feedback.horizontal = "center";
                        }
                        if (targetHeight < elemHeight && abs(top + bottom) < targetHeight) {
                            feedback.vertical = "middle";
                        }
                        if (max(abs(left), abs(right)) > max(abs(top), abs(bottom))) {
                            feedback.important = "horizontal";
                        } else {
                            feedback.important = "vertical";
                        }
                        options.using.call(this, props, feedback);
                    };
                }

                elem.offset($.extend(position, { using: using }));
            });
        };

        $.ui.position = {
            fit: {
                left: function(position, data) {
                    var within = data.within,
                        withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
                        outerWidth = within.width,
                        collisionPosLeft = position.left - data.collisionPosition.marginLeft,
                        overLeft = withinOffset - collisionPosLeft,
                        overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
                        newOverRight;

                    // Element is wider than within
                    if (data.collisionWidth > outerWidth) {

                        // Element is initially over the left side of within
                        if (overLeft > 0 && overRight <= 0) {
                            newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
                                withinOffset;
                            position.left += overLeft - newOverRight;

                            // Element is initially over right side of within
                        } else if (overRight > 0 && overLeft <= 0) {
                            position.left = withinOffset;

                            // Element is initially over both left and right sides of within
                        } else {
                            if (overLeft > overRight) {
                                position.left = withinOffset + outerWidth - data.collisionWidth;
                            } else {
                                position.left = withinOffset;
                            }
                        }

                        // Too far left -> align with left edge
                    } else if (overLeft > 0) {
                        position.left += overLeft;

                        // Too far right -> align with right edge
                    } else if (overRight > 0) {
                        position.left -= overRight;

                        // Adjust based on position and margin
                    } else {
                        position.left = max(position.left - collisionPosLeft, position.left);
                    }
                },
                top: function(position, data) {
                    var within = data.within,
                        withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
                        outerHeight = data.within.height,
                        collisionPosTop = position.top - data.collisionPosition.marginTop,
                        overTop = withinOffset - collisionPosTop,
                        overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
                        newOverBottom;

                    // Element is taller than within
                    if (data.collisionHeight > outerHeight) {

                        // Element is initially over the top of within
                        if (overTop > 0 && overBottom <= 0) {
                            newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
                                withinOffset;
                            position.top += overTop - newOverBottom;

                            // Element is initially over bottom of within
                        } else if (overBottom > 0 && overTop <= 0) {
                            position.top = withinOffset;

                            // Element is initially over both top and bottom of within
                        } else {
                            if (overTop > overBottom) {
                                position.top = withinOffset + outerHeight - data.collisionHeight;
                            } else {
                                position.top = withinOffset;
                            }
                        }

                        // Too far up -> align with top
                    } else if (overTop > 0) {
                        position.top += overTop;

                        // Too far down -> align with bottom edge
                    } else if (overBottom > 0) {
                        position.top -= overBottom;

                        // Adjust based on position and margin
                    } else {
                        position.top = max(position.top - collisionPosTop, position.top);
                    }
                }
            },
            flip: {
                left: function(position, data) {
                    var within = data.within,
                        withinOffset = within.offset.left + within.scrollLeft,
                        outerWidth = within.width,
                        offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
                        collisionPosLeft = position.left - data.collisionPosition.marginLeft,
                        overLeft = collisionPosLeft - offsetLeft,
                        overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
                        myOffset = data.my[0] === "left" ?
                        -data.elemWidth :
                        data.my[0] === "right" ?
                        data.elemWidth :
                        0,
                        atOffset = data.at[0] === "left" ?
                        data.targetWidth :
                        data.at[0] === "right" ?
                        -data.targetWidth :
                        0,
                        offset = -2 * data.offset[0],
                        newOverRight,
                        newOverLeft;

                    if (overLeft < 0) {
                        newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
                            outerWidth - withinOffset;
                        if (newOverRight < 0 || newOverRight < abs(overLeft)) {
                            position.left += myOffset + atOffset + offset;
                        }
                    } else if (overRight > 0) {
                        newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
                            atOffset + offset - offsetLeft;
                        if (newOverLeft > 0 || abs(newOverLeft) < overRight) {
                            position.left += myOffset + atOffset + offset;
                        }
                    }
                },
                top: function(position, data) {
                    var within = data.within,
                        withinOffset = within.offset.top + within.scrollTop,
                        outerHeight = within.height,
                        offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
                        collisionPosTop = position.top - data.collisionPosition.marginTop,
                        overTop = collisionPosTop - offsetTop,
                        overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
                        top = data.my[1] === "top",
                        myOffset = top ?
                        -data.elemHeight :
                        data.my[1] === "bottom" ?
                        data.elemHeight :
                        0,
                        atOffset = data.at[1] === "top" ?
                        data.targetHeight :
                        data.at[1] === "bottom" ?
                        -data.targetHeight :
                        0,
                        offset = -2 * data.offset[1],
                        newOverTop,
                        newOverBottom;
                    if (overTop < 0) {
                        newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
                            outerHeight - withinOffset;
                        if (newOverBottom < 0 || newOverBottom < abs(overTop)) {
                            position.top += myOffset + atOffset + offset;
                        }
                    } else if (overBottom > 0) {
                        newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
                            offset - offsetTop;
                        if (newOverTop > 0 || abs(newOverTop) < overBottom) {
                            position.top += myOffset + atOffset + offset;
                        }
                    }
                }
            },
            flipfit: {
                left: function() {
                    $.ui.position.flip.left.apply(this, arguments);
                    $.ui.position.fit.left.apply(this, arguments);
                },
                top: function() {
                    $.ui.position.flip.top.apply(this, arguments);
                    $.ui.position.fit.top.apply(this, arguments);
                }
            }
        };

    })();

    var position = $.ui.position;


    /*!
     * jQuery UI :data 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: :data Selector
    //>>group: Core
    //>>description: Selects elements which have data stored under the specified key.
    //>>docs: http://api.jqueryui.com/data-selector/


    var data = $.extend($.expr[":"], {
        data: $.expr.createPseudo ?
            $.expr.createPseudo(function(dataName) {
                return function(elem) {
                    return !!$.data(elem, dataName);
                };
            }) :

            // Support: jQuery <1.8
            function(elem, i, match) {
                return !!$.data(elem, match[3]);
            }
    });

    /*!
     * jQuery UI Disable Selection 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: disableSelection
    //>>group: Core
    //>>description: Disable selection of text content within the set of matched elements.
    //>>docs: http://api.jqueryui.com/disableSelection/

    // This file is deprecated


    var disableSelection = $.fn.extend({
        disableSelection: (function() {
            var eventType = "onselectstart" in document.createElement("div") ?
                "selectstart" :
                "mousedown";

            return function() {
                return this.on(eventType + ".ui-disableSelection", function(event) {
                    event.preventDefault();
                });
            };
        })(),

        enableSelection: function() {
            return this.off(".ui-disableSelection");
        }
    });


    /*!
     * jQuery UI Focusable 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: :focusable Selector
    //>>group: Core
    //>>description: Selects elements which can be focused.
    //>>docs: http://api.jqueryui.com/focusable-selector/



    // Selectors
    $.ui.focusable = function(element, hasTabindex) {
        var map, mapName, img, focusableIfVisible, fieldset,
            nodeName = element.nodeName.toLowerCase();

        if ("area" === nodeName) {
            map = element.parentNode;
            mapName = map.name;
            if (!element.href || !mapName || map.nodeName.toLowerCase() !== "map") {
                return false;
            }
            img = $("img[usemap='#" + mapName + "']");
            return img.length > 0 && img.is(":visible");
        }

        if (/^(input|select|textarea|button|object)$/.test(nodeName)) {
            focusableIfVisible = !element.disabled;

            if (focusableIfVisible) {

                // Form controls within a disabled fieldset are disabled.
                // However, controls within the fieldset's legend do not get disabled.
                // Since controls generally aren't placed inside legends, we skip
                // this portion of the check.
                fieldset = $(element).closest("fieldset")[0];
                if (fieldset) {
                    focusableIfVisible = !fieldset.disabled;
                }
            }
        } else if ("a" === nodeName) {
            focusableIfVisible = element.href || hasTabindex;
        } else {
            focusableIfVisible = hasTabindex;
        }

        return focusableIfVisible && $(element).is(":visible") && visible($(element));
    };

    // Support: IE 8 only
    // IE 8 doesn't resolve inherit to visible/hidden for computed values
    function visible(element) {
        var visibility = element.css("visibility");
        while (visibility === "inherit") {
            element = element.parent();
            visibility = element.css("visibility");
        }
        return visibility !== "hidden";
    }

    $.extend($.expr[":"], {
        focusable: function(element) {
            return $.ui.focusable(element, $.attr(element, "tabindex") != null);
        }
    });

    var focusable = $.ui.focusable;




    // Support: IE8 Only
    // IE8 does not support the form attribute and when it is supplied. It overwrites the form prop
    // with a string, so we need to find the proper form.
    var form = $.fn.form = function() {
        return typeof this[0].form === "string" ? this.closest("form") : $(this[0].form);
    };


    /*!
     * jQuery UI Form Reset Mixin 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Form Reset Mixin
    //>>group: Core
    //>>description: Refresh input widgets when their form is reset
    //>>docs: http://api.jqueryui.com/form-reset-mixin/



    var formResetMixin = $.ui.formResetMixin = {
        _formResetHandler: function() {
            var form = $(this);

            // Wait for the form reset to actually happen before refreshing
            setTimeout(function() {
                var instances = form.data("ui-form-reset-instances");
                $.each(instances, function() {
                    this.refresh();
                });
            });
        },

        _bindFormResetHandler: function() {
            this.form = this.element.form();
            if (!this.form.length) {
                return;
            }

            var instances = this.form.data("ui-form-reset-instances") || [];
            if (!instances.length) {

                // We don't use _on() here because we use a single event handler per form
                this.form.on("reset.ui-form-reset", this._formResetHandler);
            }
            instances.push(this);
            this.form.data("ui-form-reset-instances", instances);
        },

        _unbindFormResetHandler: function() {
            if (!this.form.length) {
                return;
            }

            var instances = this.form.data("ui-form-reset-instances");
            instances.splice($.inArray(this, instances), 1);
            if (instances.length) {
                this.form.data("ui-form-reset-instances", instances);
            } else {
                this.form
                    .removeData("ui-form-reset-instances")
                    .off("reset.ui-form-reset");
            }
        }
    };


    /*!
     * jQuery UI Support for jQuery core 1.7.x 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     *
     */

    //>>label: jQuery 1.7 Support
    //>>group: Core
    //>>description: Support version 1.7.x of jQuery core



    // Support: jQuery 1.7 only
    // Not a great way to check versions, but since we only support 1.7+ and only
    // need to detect <1.8, this is a simple check that should suffice. Checking
    // for "1.7." would be a bit safer, but the version string is 1.7, not 1.7.0
    // and we'll never reach 1.70.0 (if we do, we certainly won't be supporting
    // 1.7 anymore). See #11197 for why we're not using feature detection.
    if ($.fn.jquery.substring(0, 3) === "1.7") {

        // Setters for .innerWidth(), .innerHeight(), .outerWidth(), .outerHeight()
        // Unlike jQuery Core 1.8+, these only support numeric values to set the
        // dimensions in pixels
        $.each(["Width", "Height"], function(i, name) {
            var side = name === "Width" ? ["Left", "Right"] : ["Top", "Bottom"],
                type = name.toLowerCase(),
                orig = {
                    innerWidth: $.fn.innerWidth,
                    innerHeight: $.fn.innerHeight,
                    outerWidth: $.fn.outerWidth,
                    outerHeight: $.fn.outerHeight
                };

            function reduce(elem, size, border, margin) {
                $.each(side, function() {
                    size -= parseFloat($.css(elem, "padding" + this)) || 0;
                    if (border) {
                        size -= parseFloat($.css(elem, "border" + this + "Width")) || 0;
                    }
                    if (margin) {
                        size -= parseFloat($.css(elem, "margin" + this)) || 0;
                    }
                });
                return size;
            }

            $.fn["inner" + name] = function(size) {
                if (size === undefined) {
                    return orig["inner" + name].call(this);
                }

                return this.each(function() {
                    $(this).css(type, reduce(this, size) + "px");
                });
            };

            $.fn["outer" + name] = function(size, margin) {
                if (typeof size !== "number") {
                    return orig["outer" + name].call(this, size);
                }

                return this.each(function() {
                    $(this).css(type, reduce(this, size, true, margin) + "px");
                });
            };
        });

        $.fn.addBack = function(selector) {
            return this.add(selector == null ?
                this.prevObject : this.prevObject.filter(selector)
            );
        };
    }

    ;
    /*!
     * jQuery UI Keycode 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Keycode
    //>>group: Core
    //>>description: Provide keycodes as keynames
    //>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/


    var keycode = $.ui.keyCode = {
        BACKSPACE: 8,
        COMMA: 188,
        DELETE: 46,
        DOWN: 40,
        END: 35,
        ENTER: 13,
        ESCAPE: 27,
        HOME: 36,
        LEFT: 37,
        PAGE_DOWN: 34,
        PAGE_UP: 33,
        PERIOD: 190,
        RIGHT: 39,
        SPACE: 32,
        TAB: 9,
        UP: 38
    };




    // Internal use only
    var escapeSelector = $.ui.escapeSelector = (function() {
        var selectorEscape = /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g;
        return function(selector) {
            return selector.replace(selectorEscape, "\\$1");
        };
    })();


    /*!
     * jQuery UI Labels 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: labels
    //>>group: Core
    //>>description: Find all the labels associated with a given input
    //>>docs: http://api.jqueryui.com/labels/



    var labels = $.fn.labels = function() {
        var ancestor, selector, id, labels, ancestors;

        // Check control.labels first
        if (this[0].labels && this[0].labels.length) {
            return this.pushStack(this[0].labels);
        }

        // Support: IE <= 11, FF <= 37, Android <= 2.3 only
        // Above browsers do not support control.labels. Everything below is to support them
        // as well as document fragments. control.labels does not work on document fragments
        labels = this.eq(0).parents("label");

        // Look for the label based on the id
        id = this.attr("id");
        if (id) {

            // We don't search against the document in case the element
            // is disconnected from the DOM
            ancestor = this.eq(0).parents().last();

            // Get a full set of top level ancestors
            ancestors = ancestor.add(ancestor.length ? ancestor.siblings() : this.siblings());

            // Create a selector for the label based on the id
            selector = "label[for='" + $.ui.escapeSelector(id) + "']";

            labels = labels.add(ancestors.find(selector).addBack(selector));

        }

        // Return whatever we have found for labels
        return this.pushStack(labels);
    };


    /*!
     * jQuery UI Scroll Parent 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: scrollParent
    //>>group: Core
    //>>description: Get the closest ancestor element that is scrollable.
    //>>docs: http://api.jqueryui.com/scrollParent/



    var scrollParent = $.fn.scrollParent = function(includeHidden) {
        var position = this.css("position"),
            excludeStaticParent = position === "absolute",
            overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
            scrollParent = this.parents().filter(function() {
                var parent = $(this);
                if (excludeStaticParent && parent.css("position") === "static") {
                    return false;
                }
                return overflowRegex.test(parent.css("overflow") + parent.css("overflow-y") +
                    parent.css("overflow-x"));
            }).eq(0);

        return position === "fixed" || !scrollParent.length ?
            $(this[0].ownerDocument || document) :
            scrollParent;
    };


    /*!
     * jQuery UI Tabbable 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: :tabbable Selector
    //>>group: Core
    //>>description: Selects elements which can be tabbed to.
    //>>docs: http://api.jqueryui.com/tabbable-selector/



    var tabbable = $.extend($.expr[":"], {
        tabbable: function(element) {
            var tabIndex = $.attr(element, "tabindex"),
                hasTabindex = tabIndex != null;
            return (!hasTabindex || tabIndex >= 0) && $.ui.focusable(element, hasTabindex);
        }
    });


    /*!
     * jQuery UI Unique ID 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: uniqueId
    //>>group: Core
    //>>description: Functions to generate and remove uniqueId's
    //>>docs: http://api.jqueryui.com/uniqueId/



    var uniqueId = $.fn.extend({
        uniqueId: (function() {
            var uuid = 0;

            return function() {
                return this.each(function() {
                    if (!this.id) {
                        this.id = "ui-id-" + (++uuid);
                    }
                });
            };
        })(),

        removeUniqueId: function() {
            return this.each(function() {
                if (/^ui-id-\d+$/.test(this.id)) {
                    $(this).removeAttr("id");
                }
            });
        }
    });




    // This file is deprecated
    var ie = $.ui.ie = !!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());

    /*!
     * jQuery UI Mouse 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Mouse
    //>>group: Widgets
    //>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
    //>>docs: http://api.jqueryui.com/mouse/



    var mouseHandled = false;
    $(document).on("mouseup", function() {
        mouseHandled = false;
    });

    var widgetsMouse = $.widget("ui.mouse", {
        version: "1.12.1",
        options: {
            cancel: "input, textarea, button, select, option",
            distance: 1,
            delay: 0
        },
        _mouseInit: function() {
            var that = this;

            this.element
                .on("mousedown." + this.widgetName, function(event) {
                    return that._mouseDown(event);
                })
                .on("click." + this.widgetName, function(event) {
                    if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
                        $.removeData(event.target, that.widgetName + ".preventClickEvent");
                        event.stopImmediatePropagation();
                        return false;
                    }
                });

            this.started = false;
        },

        // TODO: make sure destroying one instance of mouse doesn't mess with
        // other instances of mouse
        _mouseDestroy: function() {
            this.element.off("." + this.widgetName);
            if (this._mouseMoveDelegate) {
                this.document
                    .off("mousemove." + this.widgetName, this._mouseMoveDelegate)
                    .off("mouseup." + this.widgetName, this._mouseUpDelegate);
            }
        },

        _mouseDown: function(event) {

            // don't let more than one widget handle mouseStart
            if (mouseHandled) {
                return;
            }

            this._mouseMoved = false;

            // We may have missed mouseup (out of window)
            (this._mouseStarted && this._mouseUp(event));

            this._mouseDownEvent = event;

            var that = this,
                btnIsLeft = (event.which === 1),

                // event.target.nodeName works around a bug in IE 8 with
                // disabled inputs (#7620)
                elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ?
                    $(event.target).closest(this.options.cancel).length : false);
            if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
                return true;
            }

            this.mouseDelayMet = !this.options.delay;
            if (!this.mouseDelayMet) {
                this._mouseDelayTimer = setTimeout(function() {
                    that.mouseDelayMet = true;
                }, this.options.delay);
            }

            if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
                this._mouseStarted = (this._mouseStart(event) !== false);
                if (!this._mouseStarted) {
                    event.preventDefault();
                    return true;
                }
            }

            // Click event may never have fired (Gecko & Opera)
            if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
                $.removeData(event.target, this.widgetName + ".preventClickEvent");
            }

            // These delegates are required to keep context
            this._mouseMoveDelegate = function(event) {
                return that._mouseMove(event);
            };
            this._mouseUpDelegate = function(event) {
                return that._mouseUp(event);
            };

            this.document
                .on("mousemove." + this.widgetName, this._mouseMoveDelegate)
                .on("mouseup." + this.widgetName, this._mouseUpDelegate);

            event.preventDefault();

            mouseHandled = true;
            return true;
        },

        _mouseMove: function(event) {

            // Only check for mouseups outside the document if you've moved inside the document
            // at least once. This prevents the firing of mouseup in the case of IE<9, which will
            // fire a mousemove event if content is placed under the cursor. See #7778
            // Support: IE <9
            if (this._mouseMoved) {

                // IE mouseup check - mouseup happened when mouse was out of window
                if ($.ui.ie && (!document.documentMode || document.documentMode < 9) &&
                    !event.button) {
                    return this._mouseUp(event);

                    // Iframe mouseup check - mouseup occurred in another document
                } else if (!event.which) {

                    // Support: Safari <=8 - 9
                    // Safari sets which to 0 if you press any of the following keys
                    // during a drag (#14461)
                    if (event.originalEvent.altKey || event.originalEvent.ctrlKey ||
                        event.originalEvent.metaKey || event.originalEvent.shiftKey) {
                        this.ignoreMissingWhich = true;
                    } else if (!this.ignoreMissingWhich) {
                        return this._mouseUp(event);
                    }
                }
            }

            if (event.which || event.button) {
                this._mouseMoved = true;
            }

            if (this._mouseStarted) {
                this._mouseDrag(event);
                return event.preventDefault();
            }

            if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
                this._mouseStarted =
                    (this._mouseStart(this._mouseDownEvent, event) !== false);
                (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
            }

            return !this._mouseStarted;
        },

        _mouseUp: function(event) {
            this.document
                .off("mousemove." + this.widgetName, this._mouseMoveDelegate)
                .off("mouseup." + this.widgetName, this._mouseUpDelegate);

            if (this._mouseStarted) {
                this._mouseStarted = false;

                if (event.target === this._mouseDownEvent.target) {
                    $.data(event.target, this.widgetName + ".preventClickEvent", true);
                }

                this._mouseStop(event);
            }

            if (this._mouseDelayTimer) {
                clearTimeout(this._mouseDelayTimer);
                delete this._mouseDelayTimer;
            }

            this.ignoreMissingWhich = false;
            mouseHandled = false;
            event.preventDefault();
        },

        _mouseDistanceMet: function(event) {
            return (Math.max(
                Math.abs(this._mouseDownEvent.pageX - event.pageX),
                Math.abs(this._mouseDownEvent.pageY - event.pageY)
            ) >= this.options.distance);
        },

        _mouseDelayMet: function( /* event */ ) {
            return this.mouseDelayMet;
        },

        // These are placeholder methods, to be overriden by extending plugin
        _mouseStart: function( /* event */ ) {},
        _mouseDrag: function( /* event */ ) {},
        _mouseStop: function( /* event */ ) {},
        _mouseCapture: function( /* event */ ) { return true; }
    });




    // $.ui.plugin is deprecated. Use $.widget() extensions instead.
    var plugin = $.ui.plugin = {
        add: function(module, option, set) {
            var i,
                proto = $.ui[module].prototype;
            for (i in set) {
                proto.plugins[i] = proto.plugins[i] || [];
                proto.plugins[i].push([option, set[i]]);
            }
        },
        call: function(instance, name, args, allowDisconnected) {
            var i,
                set = instance.plugins[name];

            if (!set) {
                return;
            }

            if (!allowDisconnected && (!instance.element[0].parentNode ||
                    instance.element[0].parentNode.nodeType === 11)) {
                return;
            }

            for (i = 0; i < set.length; i++) {
                if (instance.options[set[i][0]]) {
                    set[i][1].apply(instance.element, args);
                }
            }
        }
    };



    var safeActiveElement = $.ui.safeActiveElement = function(document) {
        var activeElement;

        // Support: IE 9 only
        // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
        try {
            activeElement = document.activeElement;
        } catch (error) {
            activeElement = document.body;
        }

        // Support: IE 9 - 11 only
        // IE may return null instead of an element
        // Interestingly, this only seems to occur when NOT in an iframe
        if (!activeElement) {
            activeElement = document.body;
        }

        // Support: IE 11 only
        // IE11 returns a seemingly empty object in some cases when accessing
        // document.activeElement from an <iframe>
        if (!activeElement.nodeName) {
            activeElement = document.body;
        }

        return activeElement;
    };



    var safeBlur = $.ui.safeBlur = function(element) {

        // Support: IE9 - 10 only
        // If the <body> is blurred, IE will switch windows, see #9420
        if (element && element.nodeName.toLowerCase() !== "body") {
            $(element).trigger("blur");
        }
    };


    /*!
     * jQuery UI Draggable 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Draggable
    //>>group: Interactions
    //>>description: Enables dragging functionality for any element.
    //>>docs: http://api.jqueryui.com/draggable/
    //>>demos: http://jqueryui.com/draggable/
    //>>css.structure: ../../themes/base/draggable.css



    $.widget("ui.draggable", $.ui.mouse, {
        version: "1.12.1",
        widgetEventPrefix: "drag",
        options: {
            addClasses: true,
            appendTo: "parent",
            axis: false,
            connectToSortable: false,
            containment: false,
            cursor: "auto",
            cursorAt: false,
            grid: false,
            handle: false,
            helper: "original",
            iframeFix: false,
            opacity: false,
            refreshPositions: false,
            revert: false,
            revertDuration: 500,
            scope: "default",
            scroll: true,
            scrollSensitivity: 20,
            scrollSpeed: 20,
            snap: false,
            snapMode: "both",
            snapTolerance: 20,
            stack: false,
            zIndex: false,

            // Callbacks
            drag: null,
            start: null,
            stop: null
        },
        _create: function() {

            if (this.options.helper === "original") {
                this._setPositionRelative();
            }
            if (this.options.addClasses) {
                this._addClass("ui-draggable");
            }
            this._setHandleClassName();

            this._mouseInit();
        },

        _setOption: function(key, value) {
            this._super(key, value);
            if (key === "handle") {
                this._removeHandleClassName();
                this._setHandleClassName();
            }
        },

        _destroy: function() {
            if ((this.helper || this.element).is(".ui-draggable-dragging")) {
                this.destroyOnClear = true;
                return;
            }
            this._removeHandleClassName();
            this._mouseDestroy();
        },

        _mouseCapture: function(event) {
            var o = this.options;

            // Among others, prevent a drag on a resizable-handle
            if (this.helper || o.disabled ||
                $(event.target).closest(".ui-resizable-handle").length > 0) {
                return false;
            }

            //Quit if we're not on a valid handle
            this.handle = this._getHandle(event);
            if (!this.handle) {
                return false;
            }

            this._blurActiveElement(event);

            this._blockFrames(o.iframeFix === true ? "iframe" : o.iframeFix);

            return true;

        },

        _blockFrames: function(selector) {
            this.iframeBlocks = this.document.find(selector).map(function() {
                var iframe = $(this);

                return $("<div>")
                    .css("position", "absolute")
                    .appendTo(iframe.parent())
                    .outerWidth(iframe.outerWidth())
                    .outerHeight(iframe.outerHeight())
                    .offset(iframe.offset())[0];
            });
        },

        _unblockFrames: function() {
            if (this.iframeBlocks) {
                this.iframeBlocks.remove();
                delete this.iframeBlocks;
            }
        },

        _blurActiveElement: function(event) {
            var activeElement = $.ui.safeActiveElement(this.document[0]),
                target = $(event.target);

            // Don't blur if the event occurred on an element that is within
            // the currently focused element
            // See #10527, #12472
            if (target.closest(activeElement).length) {
                return;
            }

            // Blur any element that currently has focus, see #4261
            $.ui.safeBlur(activeElement);
        },

        _mouseStart: function(event) {

            var o = this.options;

            //Create and append the visible helper
            this.helper = this._createHelper(event);

            this._addClass(this.helper, "ui-draggable-dragging");

            //Cache the helper size
            this._cacheHelperProportions();

            //If ddmanager is used for droppables, set the global draggable
            if ($.ui.ddmanager) {
                $.ui.ddmanager.current = this;
            }

            /*
             * - Position generation -
             * This block generates everything position related - it's the core of draggables.
             */

            //Cache the margins of the original element
            this._cacheMargins();

            //Store the helper's css position
            this.cssPosition = this.helper.css("position");
            this.scrollParent = this.helper.scrollParent(true);
            this.offsetParent = this.helper.offsetParent();
            this.hasFixedAncestor = this.helper.parents().filter(function() {
                return $(this).css("position") === "fixed";
            }).length > 0;

            //The element's absolute position on the page minus margins
            this.positionAbs = this.element.offset();
            this._refreshOffsets(event);

            //Generate the original position
            this.originalPosition = this.position = this._generatePosition(event, false);
            this.originalPageX = event.pageX;
            this.originalPageY = event.pageY;

            //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
            (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

            //Set a containment if given in the options
            this._setContainment();

            //Trigger event + callbacks
            if (this._trigger("start", event) === false) {
                this._clear();
                return false;
            }

            //Recache the helper size
            this._cacheHelperProportions();

            //Prepare the droppable offsets
            if ($.ui.ddmanager && !o.dropBehaviour) {
                $.ui.ddmanager.prepareOffsets(this, event);
            }

            // Execute the drag once - this causes the helper not to be visible before getting its
            // correct position
            this._mouseDrag(event, true);

            // If the ddmanager is used for droppables, inform the manager that dragging has started
            // (see #5003)
            if ($.ui.ddmanager) {
                $.ui.ddmanager.dragStart(this, event);
            }

            return true;
        },

        _refreshOffsets: function(event) {
            this.offset = {
                top: this.positionAbs.top - this.margins.top,
                left: this.positionAbs.left - this.margins.left,
                scroll: false,
                parent: this._getParentOffset(),
                relative: this._getRelativeOffset()
            };

            this.offset.click = {
                left: event.pageX - this.offset.left,
                top: event.pageY - this.offset.top
            };
        },

        _mouseDrag: function(event, noPropagation) {

            // reset any necessary cached properties (see #5009)
            if (this.hasFixedAncestor) {
                this.offset.parent = this._getParentOffset();
            }

            //Compute the helpers position
            this.position = this._generatePosition(event, true);
            this.positionAbs = this._convertPositionTo("absolute");

            //Call plugins and callbacks and use the resulting position if something is returned
            if (!noPropagation) {
                var ui = this._uiHash();
                if (this._trigger("drag", event, ui) === false) {
                    this._mouseUp(new $.Event("mouseup", event));
                    return false;
                }
                this.position = ui.position;
            }

            this.helper[0].style.left = this.position.left + "px";
            this.helper[0].style.top = this.position.top + "px";

            if ($.ui.ddmanager) {
                $.ui.ddmanager.drag(this, event);
            }

            return false;
        },

        _mouseStop: function(event) {

            //If we are using droppables, inform the manager about the drop
            var that = this,
                dropped = false;
            if ($.ui.ddmanager && !this.options.dropBehaviour) {
                dropped = $.ui.ddmanager.drop(this, event);
            }

            //if a drop comes from outside (a sortable)
            if (this.dropped) {
                dropped = this.dropped;
                this.dropped = false;
            }

            if ((this.options.revert === "invalid" && !dropped) ||
                (this.options.revert === "valid" && dropped) ||
                this.options.revert === true || ($.isFunction(this.options.revert) &&
                    this.options.revert.call(this.element, dropped))
            ) {
                $(this.helper).animate(
                    this.originalPosition,
                    parseInt(this.options.revertDuration, 10),
                    function() {
                        if (that._trigger("stop", event) !== false) {
                            that._clear();
                        }
                    }
                );
            } else {
                if (this._trigger("stop", event) !== false) {
                    this._clear();
                }
            }

            return false;
        },

        _mouseUp: function(event) {
            this._unblockFrames();

            // If the ddmanager is used for droppables, inform the manager that dragging has stopped
            // (see #5003)
            if ($.ui.ddmanager) {
                $.ui.ddmanager.dragStop(this, event);
            }

            // Only need to focus if the event occurred on the draggable itself, see #10527
            if (this.handleElement.is(event.target)) {

                // The interaction is over; whether or not the click resulted in a drag,
                // focus the element
                this.element.trigger("focus");
            }

            return $.ui.mouse.prototype._mouseUp.call(this, event);
        },

        cancel: function() {

            if (this.helper.is(".ui-draggable-dragging")) {
                this._mouseUp(new $.Event("mouseup", { target: this.element[0] }));
            } else {
                this._clear();
            }

            return this;

        },

        _getHandle: function(event) {
            return this.options.handle ?
                !!$(event.target).closest(this.element.find(this.options.handle)).length :
                true;
        },

        _setHandleClassName: function() {
            this.handleElement = this.options.handle ?
                this.element.find(this.options.handle) : this.element;
            this._addClass(this.handleElement, "ui-draggable-handle");
        },

        _removeHandleClassName: function() {
            this._removeClass(this.handleElement, "ui-draggable-handle");
        },

        _createHelper: function(event) {

            var o = this.options,
                helperIsFunction = $.isFunction(o.helper),
                helper = helperIsFunction ?
                $(o.helper.apply(this.element[0], [event])) :
                (o.helper === "clone" ?
                    this.element.clone().removeAttr("id") :
                    this.element);

            if (!helper.parents("body").length) {
                helper.appendTo((o.appendTo === "parent" ?
                    this.element[0].parentNode :
                    o.appendTo));
            }

            // Http://bugs.jqueryui.com/ticket/9446
            // a helper function can return the original element
            // which wouldn't have been set to relative in _create
            if (helperIsFunction && helper[0] === this.element[0]) {
                this._setPositionRelative();
            }

            if (helper[0] !== this.element[0] &&
                !(/(fixed|absolute)/).test(helper.css("position"))) {
                helper.css("position", "absolute");
            }

            return helper;

        },

        _setPositionRelative: function() {
            if (!(/^(?:r|a|f)/).test(this.element.css("position"))) {
                this.element[0].style.position = "relative";
            }
        },

        _adjustOffsetFromHelper: function(obj) {
            if (typeof obj === "string") {
                obj = obj.split(" ");
            }
            if ($.isArray(obj)) {
                obj = { left: +obj[0], top: +obj[1] || 0 };
            }
            if ("left" in obj) {
                this.offset.click.left = obj.left + this.margins.left;
            }
            if ("right" in obj) {
                this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
            }
            if ("top" in obj) {
                this.offset.click.top = obj.top + this.margins.top;
            }
            if ("bottom" in obj) {
                this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
            }
        },

        _isRootNode: function(element) {
            return (/(html|body)/i).test(element.tagName) || element === this.document[0];
        },

        _getParentOffset: function() {

            //Get the offsetParent and cache its position
            var po = this.offsetParent.offset(),
                document = this.document[0];

            // This is a special case where we need to modify a offset calculated on start, since the
            // following happened:
            // 1. The position of the helper is absolute, so it's position is calculated based on the
            // next positioned parent
            // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
            // the document, which means that the scroll is included in the initial calculation of the
            // offset of the parent, and never recalculated upon drag
            if (this.cssPosition === "absolute" && this.scrollParent[0] !== document &&
                $.contains(this.scrollParent[0], this.offsetParent[0])) {
                po.left += this.scrollParent.scrollLeft();
                po.top += this.scrollParent.scrollTop();
            }

            if (this._isRootNode(this.offsetParent[0])) {
                po = { top: 0, left: 0 };
            }

            return {
                top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0),
                left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)
            };

        },

        _getRelativeOffset: function() {
            if (this.cssPosition !== "relative") {
                return { top: 0, left: 0 };
            }

            var p = this.element.position(),
                scrollIsRootNode = this._isRootNode(this.scrollParent[0]);

            return {
                top: p.top - (parseInt(this.helper.css("top"), 10) || 0) +
                    (!scrollIsRootNode ? this.scrollParent.scrollTop() : 0),
                left: p.left - (parseInt(this.helper.css("left"), 10) || 0) +
                    (!scrollIsRootNode ? this.scrollParent.scrollLeft() : 0)
            };

        },

        _cacheMargins: function() {
            this.margins = {
                left: (parseInt(this.element.css("marginLeft"), 10) || 0),
                top: (parseInt(this.element.css("marginTop"), 10) || 0),
                right: (parseInt(this.element.css("marginRight"), 10) || 0),
                bottom: (parseInt(this.element.css("marginBottom"), 10) || 0)
            };
        },

        _cacheHelperProportions: function() {
            this.helperProportions = {
                width: this.helper.outerWidth(),
                height: this.helper.outerHeight()
            };
        },

        _setContainment: function() {

            var isUserScrollable, c, ce,
                o = this.options,
                document = this.document[0];

            this.relativeContainer = null;

            if (!o.containment) {
                this.containment = null;
                return;
            }

            if (o.containment === "window") {
                this.containment = [
                    $(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
                    $(window).scrollTop() - this.offset.relative.top - this.offset.parent.top,
                    $(window).scrollLeft() + $(window).width() -
                    this.helperProportions.width - this.margins.left,
                    $(window).scrollTop() +
                    ($(window).height() || document.body.parentNode.scrollHeight) -
                    this.helperProportions.height - this.margins.top
                ];
                return;
            }

            if (o.containment === "document") {
                this.containment = [
                    0,
                    0,
                    $(document).width() - this.helperProportions.width - this.margins.left,
                    ($(document).height() || document.body.parentNode.scrollHeight) -
                    this.helperProportions.height - this.margins.top
                ];
                return;
            }

            if (o.containment.constructor === Array) {
                this.containment = o.containment;
                return;
            }

            if (o.containment === "parent") {
                o.containment = this.helper[0].parentNode;
            }

            c = $(o.containment);
            ce = c[0];

            if (!ce) {
                return;
            }

            isUserScrollable = /(scroll|auto)/.test(c.css("overflow"));

            this.containment = [
                (parseInt(c.css("borderLeftWidth"), 10) || 0) +
                (parseInt(c.css("paddingLeft"), 10) || 0),
                (parseInt(c.css("borderTopWidth"), 10) || 0) +
                (parseInt(c.css("paddingTop"), 10) || 0),
                (isUserScrollable ? Math.max(ce.scrollWidth, ce.offsetWidth) : ce.offsetWidth) -
                (parseInt(c.css("borderRightWidth"), 10) || 0) -
                (parseInt(c.css("paddingRight"), 10) || 0) -
                this.helperProportions.width -
                this.margins.left -
                this.margins.right,
                (isUserScrollable ? Math.max(ce.scrollHeight, ce.offsetHeight) : ce.offsetHeight) -
                (parseInt(c.css("borderBottomWidth"), 10) || 0) -
                (parseInt(c.css("paddingBottom"), 10) || 0) -
                this.helperProportions.height -
                this.margins.top -
                this.margins.bottom
            ];
            this.relativeContainer = c;
        },

        _convertPositionTo: function(d, pos) {

            if (!pos) {
                pos = this.position;
            }

            var mod = d === "absolute" ? 1 : -1,
                scrollIsRootNode = this._isRootNode(this.scrollParent[0]);

            return {
                top: (

                    // The absolute mouse position
                    pos.top +

                    // Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.relative.top * mod +

                    // The offsetParent's offset without borders (offset + border)
                    this.offset.parent.top * mod -
                    ((this.cssPosition === "fixed" ?
                        -this.offset.scroll.top :
                        (scrollIsRootNode ? 0 : this.offset.scroll.top)) * mod)
                ),
                left: (

                    // The absolute mouse position
                    pos.left +

                    // Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.relative.left * mod +

                    // The offsetParent's offset without borders (offset + border)
                    this.offset.parent.left * mod -
                    ((this.cssPosition === "fixed" ?
                        -this.offset.scroll.left :
                        (scrollIsRootNode ? 0 : this.offset.scroll.left)) * mod)
                )
            };

        },

        _generatePosition: function(event, constrainPosition) {

            var containment, co, top, left,
                o = this.options,
                scrollIsRootNode = this._isRootNode(this.scrollParent[0]),
                pageX = event.pageX,
                pageY = event.pageY;

            // Cache the scroll
            if (!scrollIsRootNode || !this.offset.scroll) {
                this.offset.scroll = {
                    top: this.scrollParent.scrollTop(),
                    left: this.scrollParent.scrollLeft()
                };
            }

            /*
             * - Position constraining -
             * Constrain the position to a mix of grid, containment.
             */

            // If we are not dragging yet, we won't check for options
            if (constrainPosition) {
                if (this.containment) {
                    if (this.relativeContainer) {
                        co = this.relativeContainer.offset();
                        containment = [
                            this.containment[0] + co.left,
                            this.containment[1] + co.top,
                            this.containment[2] + co.left,
                            this.containment[3] + co.top
                        ];
                    } else {
                        containment = this.containment;
                    }

                    if (event.pageX - this.offset.click.left < containment[0]) {
                        pageX = containment[0] + this.offset.click.left;
                    }
                    if (event.pageY - this.offset.click.top < containment[1]) {
                        pageY = containment[1] + this.offset.click.top;
                    }
                    if (event.pageX - this.offset.click.left > containment[2]) {
                        pageX = containment[2] + this.offset.click.left;
                    }
                    if (event.pageY - this.offset.click.top > containment[3]) {
                        pageY = containment[3] + this.offset.click.top;
                    }
                }

                if (o.grid) {

                    //Check for grid elements set to 0 to prevent divide by 0 error causing invalid
                    // argument errors in IE (see ticket #6950)
                    top = o.grid[1] ? this.originalPageY + Math.round((pageY -
                        this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
                    pageY = containment ? ((top - this.offset.click.top >= containment[1] ||
                            top - this.offset.click.top > containment[3]) ?
                        top :
                        ((top - this.offset.click.top >= containment[1]) ?
                            top - o.grid[1] : top + o.grid[1])) : top;

                    left = o.grid[0] ? this.originalPageX +
                        Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] :
                        this.originalPageX;
                    pageX = containment ? ((left - this.offset.click.left >= containment[0] ||
                            left - this.offset.click.left > containment[2]) ?
                        left :
                        ((left - this.offset.click.left >= containment[0]) ?
                            left - o.grid[0] : left + o.grid[0])) : left;
                }

                if (o.axis === "y") {
                    pageX = this.originalPageX;
                }

                if (o.axis === "x") {
                    pageY = this.originalPageY;
                }
            }

            return {
                top: (

                    // The absolute mouse position
                    pageY -

                    // Click offset (relative to the element)
                    this.offset.click.top -

                    // Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.relative.top -

                    // The offsetParent's offset without borders (offset + border)
                    this.offset.parent.top +
                    (this.cssPosition === "fixed" ?
                        -this.offset.scroll.top :
                        (scrollIsRootNode ? 0 : this.offset.scroll.top))
                ),
                left: (

                    // The absolute mouse position
                    pageX -

                    // Click offset (relative to the element)
                    this.offset.click.left -

                    // Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.relative.left -

                    // The offsetParent's offset without borders (offset + border)
                    this.offset.parent.left +
                    (this.cssPosition === "fixed" ?
                        -this.offset.scroll.left :
                        (scrollIsRootNode ? 0 : this.offset.scroll.left))
                )
            };

        },

        _clear: function() {
            this._removeClass(this.helper, "ui-draggable-dragging");
            if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
                this.helper.remove();
            }
            this.helper = null;
            this.cancelHelperRemoval = false;
            if (this.destroyOnClear) {
                this.destroy();
            }
        },

        // From now on bulk stuff - mainly helpers

        _trigger: function(type, event, ui) {
            ui = ui || this._uiHash();
            $.ui.plugin.call(this, type, [event, ui, this], true);

            // Absolute position and offset (see #6884 ) have to be recalculated after plugins
            if (/^(drag|start|stop)/.test(type)) {
                this.positionAbs = this._convertPositionTo("absolute");
                ui.offset = this.positionAbs;
            }
            return $.Widget.prototype._trigger.call(this, type, event, ui);
        },

        plugins: {},

        _uiHash: function() {
            return {
                helper: this.helper,
                position: this.position,
                originalPosition: this.originalPosition,
                offset: this.positionAbs
            };
        }

    });

    $.ui.plugin.add("draggable", "connectToSortable", {
        start: function(event, ui, draggable) {
            var uiSortable = $.extend({}, ui, {
                item: draggable.element
            });

            draggable.sortables = [];
            $(draggable.options.connectToSortable).each(function() {
                var sortable = $(this).sortable("instance");

                if (sortable && !sortable.options.disabled) {
                    draggable.sortables.push(sortable);

                    // RefreshPositions is called at drag start to refresh the containerCache
                    // which is used in drag. This ensures it's initialized and synchronized
                    // with any changes that might have happened on the page since initialization.
                    sortable.refreshPositions();
                    sortable._trigger("activate", event, uiSortable);
                }
            });
        },
        stop: function(event, ui, draggable) {
            var uiSortable = $.extend({}, ui, {
                item: draggable.element
            });

            draggable.cancelHelperRemoval = false;

            $.each(draggable.sortables, function() {
                var sortable = this;

                if (sortable.isOver) {
                    sortable.isOver = 0;

                    // Allow this sortable to handle removing the helper
                    draggable.cancelHelperRemoval = true;
                    sortable.cancelHelperRemoval = false;

                    // Use _storedCSS To restore properties in the sortable,
                    // as this also handles revert (#9675) since the draggable
                    // may have modified them in unexpected ways (#8809)
                    sortable._storedCSS = {
                        position: sortable.placeholder.css("position"),
                        top: sortable.placeholder.css("top"),
                        left: sortable.placeholder.css("left")
                    };

                    sortable._mouseStop(event);

                    // Once drag has ended, the sortable should return to using
                    // its original helper, not the shared helper from draggable
                    sortable.options.helper = sortable.options._helper;
                } else {

                    // Prevent this Sortable from removing the helper.
                    // However, don't set the draggable to remove the helper
                    // either as another connected Sortable may yet handle the removal.
                    sortable.cancelHelperRemoval = true;

                    sortable._trigger("deactivate", event, uiSortable);
                }
            });
        },
        drag: function(event, ui, draggable) {
            $.each(draggable.sortables, function() {
                var innermostIntersecting = false,
                    sortable = this;

                // Copy over variables that sortable's _intersectsWith uses
                sortable.positionAbs = draggable.positionAbs;
                sortable.helperProportions = draggable.helperProportions;
                sortable.offset.click = draggable.offset.click;

                if (sortable._intersectsWith(sortable.containerCache)) {
                    innermostIntersecting = true;

                    $.each(draggable.sortables, function() {

                        // Copy over variables that sortable's _intersectsWith uses
                        this.positionAbs = draggable.positionAbs;
                        this.helperProportions = draggable.helperProportions;
                        this.offset.click = draggable.offset.click;

                        if (this !== sortable &&
                            this._intersectsWith(this.containerCache) &&
                            $.contains(sortable.element[0], this.element[0])) {
                            innermostIntersecting = false;
                        }

                        return innermostIntersecting;
                    });
                }

                if (innermostIntersecting) {

                    // If it intersects, we use a little isOver variable and set it once,
                    // so that the move-in stuff gets fired only once.
                    if (!sortable.isOver) {
                        sortable.isOver = 1;

                        // Store draggable's parent in case we need to reappend to it later.
                        draggable._parent = ui.helper.parent();

                        sortable.currentItem = ui.helper
                            .appendTo(sortable.element)
                            .data("ui-sortable-item", true);

                        // Store helper option to later restore it
                        sortable.options._helper = sortable.options.helper;

                        sortable.options.helper = function() {
                            return ui.helper[0];
                        };

                        // Fire the start events of the sortable with our passed browser event,
                        // and our own helper (so it doesn't create a new one)
                        event.target = sortable.currentItem[0];
                        sortable._mouseCapture(event, true);
                        sortable._mouseStart(event, true, true);

                        // Because the browser event is way off the new appended portlet,
                        // modify necessary variables to reflect the changes
                        sortable.offset.click.top = draggable.offset.click.top;
                        sortable.offset.click.left = draggable.offset.click.left;
                        sortable.offset.parent.left -= draggable.offset.parent.left -
                            sortable.offset.parent.left;
                        sortable.offset.parent.top -= draggable.offset.parent.top -
                            sortable.offset.parent.top;

                        draggable._trigger("toSortable", event);

                        // Inform draggable that the helper is in a valid drop zone,
                        // used solely in the revert option to handle "valid/invalid".
                        draggable.dropped = sortable.element;

                        // Need to refreshPositions of all sortables in the case that
                        // adding to one sortable changes the location of the other sortables (#9675)
                        $.each(draggable.sortables, function() {
                            this.refreshPositions();
                        });

                        // Hack so receive/update callbacks work (mostly)
                        draggable.currentItem = draggable.element;
                        sortable.fromOutside = draggable;
                    }

                    if (sortable.currentItem) {
                        sortable._mouseDrag(event);

                        // Copy the sortable's position because the draggable's can potentially reflect
                        // a relative position, while sortable is always absolute, which the dragged
                        // element has now become. (#8809)
                        ui.position = sortable.position;
                    }
                } else {

                    // If it doesn't intersect with the sortable, and it intersected before,
                    // we fake the drag stop of the sortable, but make sure it doesn't remove
                    // the helper by using cancelHelperRemoval.
                    if (sortable.isOver) {

                        sortable.isOver = 0;
                        sortable.cancelHelperRemoval = true;

                        // Calling sortable's mouseStop would trigger a revert,
                        // so revert must be temporarily false until after mouseStop is called.
                        sortable.options._revert = sortable.options.revert;
                        sortable.options.revert = false;

                        sortable._trigger("out", event, sortable._uiHash(sortable));
                        sortable._mouseStop(event, true);

                        // Restore sortable behaviors that were modfied
                        // when the draggable entered the sortable area (#9481)
                        sortable.options.revert = sortable.options._revert;
                        sortable.options.helper = sortable.options._helper;

                        if (sortable.placeholder) {
                            sortable.placeholder.remove();
                        }

                        // Restore and recalculate the draggable's offset considering the sortable
                        // may have modified them in unexpected ways. (#8809, #10669)
                        ui.helper.appendTo(draggable._parent);
                        draggable._refreshOffsets(event);
                        ui.position = draggable._generatePosition(event, true);

                        draggable._trigger("fromSortable", event);

                        // Inform draggable that the helper is no longer in a valid drop zone
                        draggable.dropped = false;

                        // Need to refreshPositions of all sortables just in case removing
                        // from one sortable changes the location of other sortables (#9675)
                        $.each(draggable.sortables, function() {
                            this.refreshPositions();
                        });
                    }
                }
            });
        }
    });

    $.ui.plugin.add("draggable", "cursor", {
        start: function(event, ui, instance) {
            var t = $("body"),
                o = instance.options;

            if (t.css("cursor")) {
                o._cursor = t.css("cursor");
            }
            t.css("cursor", o.cursor);
        },
        stop: function(event, ui, instance) {
            var o = instance.options;
            if (o._cursor) {
                $("body").css("cursor", o._cursor);
            }
        }
    });

    $.ui.plugin.add("draggable", "opacity", {
        start: function(event, ui, instance) {
            var t = $(ui.helper),
                o = instance.options;
            if (t.css("opacity")) {
                o._opacity = t.css("opacity");
            }
            t.css("opacity", o.opacity);
        },
        stop: function(event, ui, instance) {
            var o = instance.options;
            if (o._opacity) {
                $(ui.helper).css("opacity", o._opacity);
            }
        }
    });

    $.ui.plugin.add("draggable", "scroll", {
        start: function(event, ui, i) {
            if (!i.scrollParentNotHidden) {
                i.scrollParentNotHidden = i.helper.scrollParent(false);
            }

            if (i.scrollParentNotHidden[0] !== i.document[0] &&
                i.scrollParentNotHidden[0].tagName !== "HTML") {
                i.overflowOffset = i.scrollParentNotHidden.offset();
            }
        },
        drag: function(event, ui, i) {

            var o = i.options,
                scrolled = false,
                scrollParent = i.scrollParentNotHidden[0],
                document = i.document[0];

            if (scrollParent !== document && scrollParent.tagName !== "HTML") {
                if (!o.axis || o.axis !== "x") {
                    if ((i.overflowOffset.top + scrollParent.offsetHeight) - event.pageY <
                        o.scrollSensitivity) {
                        scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
                    } else if (event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
                        scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
                    }
                }

                if (!o.axis || o.axis !== "y") {
                    if ((i.overflowOffset.left + scrollParent.offsetWidth) - event.pageX <
                        o.scrollSensitivity) {
                        scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
                    } else if (event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
                        scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
                    }
                }

            } else {

                if (!o.axis || o.axis !== "x") {
                    if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
                        scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
                    } else if ($(window).height() - (event.pageY - $(document).scrollTop()) <
                        o.scrollSensitivity) {
                        scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
                    }
                }

                if (!o.axis || o.axis !== "y") {
                    if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
                        scrolled = $(document).scrollLeft(
                            $(document).scrollLeft() - o.scrollSpeed
                        );
                    } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) <
                        o.scrollSensitivity) {
                        scrolled = $(document).scrollLeft(
                            $(document).scrollLeft() + o.scrollSpeed
                        );
                    }
                }

            }

            if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
                $.ui.ddmanager.prepareOffsets(i, event);
            }

        }
    });

    $.ui.plugin.add("draggable", "snap", {
        start: function(event, ui, i) {

            var o = i.options;

            i.snapElements = [];

            $(o.snap.constructor !== String ? (o.snap.items || ":data(ui-draggable)") : o.snap)
                .each(function() {
                    var $t = $(this),
                        $o = $t.offset();
                    if (this !== i.element[0]) {
                        i.snapElements.push({
                            item: this,
                            width: $t.outerWidth(),
                            height: $t.outerHeight(),
                            top: $o.top,
                            left: $o.left
                        });
                    }
                });

        },
        drag: function(event, ui, inst) {

            var ts, bs, ls, rs, l, r, t, b, i, first,
                o = inst.options,
                d = o.snapTolerance,
                x1 = ui.offset.left,
                x2 = x1 + inst.helperProportions.width,
                y1 = ui.offset.top,
                y2 = y1 + inst.helperProportions.height;

            for (i = inst.snapElements.length - 1; i >= 0; i--) {

                l = inst.snapElements[i].left - inst.margins.left;
                r = l + inst.snapElements[i].width;
                t = inst.snapElements[i].top - inst.margins.top;
                b = t + inst.snapElements[i].height;

                if (x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d ||
                    !$.contains(inst.snapElements[i].item.ownerDocument,
                        inst.snapElements[i].item)) {
                    if (inst.snapElements[i].snapping) {
                        (inst.options.snap.release &&
                            inst.options.snap.release.call(
                                inst.element,
                                event,
                                $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })
                            ));
                    }
                    inst.snapElements[i].snapping = false;
                    continue;
                }

                if (o.snapMode !== "inner") {
                    ts = Math.abs(t - y2) <= d;
                    bs = Math.abs(b - y1) <= d;
                    ls = Math.abs(l - x2) <= d;
                    rs = Math.abs(r - x1) <= d;
                    if (ts) {
                        ui.position.top = inst._convertPositionTo("relative", {
                            top: t - inst.helperProportions.height,
                            left: 0
                        }).top;
                    }
                    if (bs) {
                        ui.position.top = inst._convertPositionTo("relative", {
                            top: b,
                            left: 0
                        }).top;
                    }
                    if (ls) {
                        ui.position.left = inst._convertPositionTo("relative", {
                            top: 0,
                            left: l - inst.helperProportions.width
                        }).left;
                    }
                    if (rs) {
                        ui.position.left = inst._convertPositionTo("relative", {
                            top: 0,
                            left: r
                        }).left;
                    }
                }

                first = (ts || bs || ls || rs);

                if (o.snapMode !== "outer") {
                    ts = Math.abs(t - y1) <= d;
                    bs = Math.abs(b - y2) <= d;
                    ls = Math.abs(l - x1) <= d;
                    rs = Math.abs(r - x2) <= d;
                    if (ts) {
                        ui.position.top = inst._convertPositionTo("relative", {
                            top: t,
                            left: 0
                        }).top;
                    }
                    if (bs) {
                        ui.position.top = inst._convertPositionTo("relative", {
                            top: b - inst.helperProportions.height,
                            left: 0
                        }).top;
                    }
                    if (ls) {
                        ui.position.left = inst._convertPositionTo("relative", {
                            top: 0,
                            left: l
                        }).left;
                    }
                    if (rs) {
                        ui.position.left = inst._convertPositionTo("relative", {
                            top: 0,
                            left: r - inst.helperProportions.width
                        }).left;
                    }
                }

                if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
                    (inst.options.snap.snap &&
                        inst.options.snap.snap.call(
                            inst.element,
                            event,
                            $.extend(inst._uiHash(), {
                                snapItem: inst.snapElements[i].item
                            })));
                }
                inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

            }

        }
    });

    $.ui.plugin.add("draggable", "stack", {
        start: function(event, ui, instance) {
            var min,
                o = instance.options,
                group = $.makeArray($(o.stack)).sort(function(a, b) {
                    return (parseInt($(a).css("zIndex"), 10) || 0) -
                        (parseInt($(b).css("zIndex"), 10) || 0);
                });

            if (!group.length) { return; }

            min = parseInt($(group[0]).css("zIndex"), 10) || 0;
            $(group).each(function(i) {
                $(this).css("zIndex", min + i);
            });
            this.css("zIndex", (min + group.length));
        }
    });

    $.ui.plugin.add("draggable", "zIndex", {
        start: function(event, ui, instance) {
            var t = $(ui.helper),
                o = instance.options;

            if (t.css("zIndex")) {
                o._zIndex = t.css("zIndex");
            }
            t.css("zIndex", o.zIndex);
        },
        stop: function(event, ui, instance) {
            var o = instance.options;

            if (o._zIndex) {
                $(ui.helper).css("zIndex", o._zIndex);
            }
        }
    });

    var widgetsDraggable = $.ui.draggable;


    /*!
     * jQuery UI Droppable 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Droppable
    //>>group: Interactions
    //>>description: Enables drop targets for draggable elements.
    //>>docs: http://api.jqueryui.com/droppable/
    //>>demos: http://jqueryui.com/droppable/



    $.widget("ui.droppable", {
        version: "1.12.1",
        widgetEventPrefix: "drop",
        options: {
            accept: "*",
            addClasses: true,
            greedy: false,
            scope: "default",
            tolerance: "intersect",

            // Callbacks
            activate: null,
            deactivate: null,
            drop: null,
            out: null,
            over: null
        },
        _create: function() {

            var proportions,
                o = this.options,
                accept = o.accept;

            this.isover = false;
            this.isout = true;

            this.accept = $.isFunction(accept) ? accept : function(d) {
                return d.is(accept);
            };

            this.proportions = function( /* valueToWrite */ ) {
                if (arguments.length) {

                    // Store the droppable's proportions
                    proportions = arguments[0];
                } else {

                    // Retrieve or derive the droppable's proportions
                    return proportions ?
                        proportions :
                        proportions = {
                            width: this.element[0].offsetWidth,
                            height: this.element[0].offsetHeight
                        };
                }
            };

            this._addToManager(o.scope);

            o.addClasses && this._addClass("ui-droppable");

        },

        _addToManager: function(scope) {

            // Add the reference and positions to the manager
            $.ui.ddmanager.droppables[scope] = $.ui.ddmanager.droppables[scope] || [];
            $.ui.ddmanager.droppables[scope].push(this);
        },

        _splice: function(drop) {
            var i = 0;
            for (; i < drop.length; i++) {
                if (drop[i] === this) {
                    drop.splice(i, 1);
                }
            }
        },

        _destroy: function() {
            var drop = $.ui.ddmanager.droppables[this.options.scope];

            this._splice(drop);
        },

        _setOption: function(key, value) {

            if (key === "accept") {
                this.accept = $.isFunction(value) ? value : function(d) {
                    return d.is(value);
                };
            } else if (key === "scope") {
                var drop = $.ui.ddmanager.droppables[this.options.scope];

                this._splice(drop);
                this._addToManager(value);
            }

            this._super(key, value);
        },

        _activate: function(event) {
            var draggable = $.ui.ddmanager.current;

            this._addActiveClass();
            if (draggable) {
                this._trigger("activate", event, this.ui(draggable));
            }
        },

        _deactivate: function(event) {
            var draggable = $.ui.ddmanager.current;

            this._removeActiveClass();
            if (draggable) {
                this._trigger("deactivate", event, this.ui(draggable));
            }
        },

        _over: function(event) {

            var draggable = $.ui.ddmanager.current;

            // Bail if draggable and droppable are same element
            if (!draggable || (draggable.currentItem ||
                    draggable.element)[0] === this.element[0]) {
                return;
            }

            if (this.accept.call(this.element[0], (draggable.currentItem ||
                    draggable.element))) {
                this._addHoverClass();
                this._trigger("over", event, this.ui(draggable));
            }

        },

        _out: function(event) {

            var draggable = $.ui.ddmanager.current;

            // Bail if draggable and droppable are same element
            if (!draggable || (draggable.currentItem ||
                    draggable.element)[0] === this.element[0]) {
                return;
            }

            if (this.accept.call(this.element[0], (draggable.currentItem ||
                    draggable.element))) {
                this._removeHoverClass();
                this._trigger("out", event, this.ui(draggable));
            }

        },

        _drop: function(event, custom) {

            var draggable = custom || $.ui.ddmanager.current,
                childrenIntersection = false;

            // Bail if draggable and droppable are same element
            if (!draggable || (draggable.currentItem ||
                    draggable.element)[0] === this.element[0]) {
                return false;
            }

            this.element
                .find(":data(ui-droppable)")
                .not(".ui-draggable-dragging")
                .each(function() {
                    var inst = $(this).droppable("instance");
                    if (
                        inst.options.greedy &&
                        !inst.options.disabled &&
                        inst.options.scope === draggable.options.scope &&
                        inst.accept.call(
                            inst.element[0], (draggable.currentItem || draggable.element)
                        ) &&
                        intersect(
                            draggable,
                            $.extend(inst, { offset: inst.element.offset() }),
                            inst.options.tolerance, event
                        )
                    ) {
                        childrenIntersection = true;
                        return false;
                    }
                });
            if (childrenIntersection) {
                return false;
            }

            if (this.accept.call(this.element[0],
                    (draggable.currentItem || draggable.element))) {
                this._removeActiveClass();
                this._removeHoverClass();

                this._trigger("drop", event, this.ui(draggable));
                return this.element;
            }

            return false;

        },

        ui: function(c) {
            return {
                draggable: (c.currentItem || c.element),
                helper: c.helper,
                position: c.position,
                offset: c.positionAbs
            };
        },

        // Extension points just to make backcompat sane and avoid duplicating logic
        // TODO: Remove in 1.13 along with call to it below
        _addHoverClass: function() {
            this._addClass("ui-droppable-hover");
        },

        _removeHoverClass: function() {
            this._removeClass("ui-droppable-hover");
        },

        _addActiveClass: function() {
            this._addClass("ui-droppable-active");
        },

        _removeActiveClass: function() {
            this._removeClass("ui-droppable-active");
        }
    });

    var intersect = $.ui.intersect = (function() {
        function isOverAxis(x, reference, size) {
            return (x >= reference) && (x < (reference + size));
        }

        return function(draggable, droppable, toleranceMode, event) {

            if (!droppable.offset) {
                return false;
            }

            var x1 = (draggable.positionAbs ||
                    draggable.position.absolute).left + draggable.margins.left,
                y1 = (draggable.positionAbs ||
                    draggable.position.absolute).top + draggable.margins.top,
                x2 = x1 + draggable.helperProportions.width,
                y2 = y1 + draggable.helperProportions.height,
                l = droppable.offset.left,
                t = droppable.offset.top,
                r = l + droppable.proportions().width,
                b = t + droppable.proportions().height;

            switch (toleranceMode) {
                case "fit":
                    return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
                case "intersect":
                    return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
                        x2 - (draggable.helperProportions.width / 2) < r && // Left Half
                        t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
                        y2 - (draggable.helperProportions.height / 2) < b); // Top Half
                case "pointer":
                    return isOverAxis(event.pageY, t, droppable.proportions().height) &&
                        isOverAxis(event.pageX, l, droppable.proportions().width);
                case "touch":
                    return (
                        (y1 >= t && y1 <= b) || // Top edge touching
                        (y2 >= t && y2 <= b) || // Bottom edge touching
                        (y1 < t && y2 > b) // Surrounded vertically
                    ) && (
                        (x1 >= l && x1 <= r) || // Left edge touching
                        (x2 >= l && x2 <= r) || // Right edge touching
                        (x1 < l && x2 > r) // Surrounded horizontally
                    );
                default:
                    return false;
            }
        };
    })();

    /*
    	This manager tracks offsets of draggables and droppables
    */
    $.ui.ddmanager = {
        current: null,
        droppables: { "default": [] },
        prepareOffsets: function(t, event) {

            var i, j,
                m = $.ui.ddmanager.droppables[t.options.scope] || [],
                type = event ? event.type : null, // workaround for #2317
                list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack();

            droppablesLoop: for (i = 0; i < m.length; i++) {

                // No disabled and non-accepted
                if (m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],
                        (t.currentItem || t.element)))) {
                    continue;
                }

                // Filter out elements in the current dragged item
                for (j = 0; j < list.length; j++) {
                    if (list[j] === m[i].element[0]) {
                        m[i].proportions().height = 0;
                        continue droppablesLoop;
                    }
                }

                m[i].visible = m[i].element.css("display") !== "none";
                if (!m[i].visible) {
                    continue;
                }

                // Activate the droppable if used directly from draggables
                if (type === "mousedown") {
                    m[i]._activate.call(m[i], event);
                }

                m[i].offset = m[i].element.offset();
                m[i].proportions({
                    width: m[i].element[0].offsetWidth,
                    height: m[i].element[0].offsetHeight
                });

            }

        },
        drop: function(draggable, event) {

            var dropped = false;

            // Create a copy of the droppables in case the list changes during the drop (#9116)
            $.each(($.ui.ddmanager.droppables[draggable.options.scope] || []).slice(), function() {

                if (!this.options) {
                    return;
                }
                if (!this.options.disabled && this.visible &&
                    intersect(draggable, this, this.options.tolerance, event)) {
                    dropped = this._drop.call(this, event) || dropped;
                }

                if (!this.options.disabled && this.visible && this.accept.call(this.element[0],
                        (draggable.currentItem || draggable.element))) {
                    this.isout = true;
                    this.isover = false;
                    this._deactivate.call(this, event);
                }

            });
            return dropped;

        },
        dragStart: function(draggable, event) {

            // Listen for scrolling so that if the dragging causes scrolling the position of the
            // droppables can be recalculated (see #5003)
            draggable.element.parentsUntil("body").on("scroll.droppable", function() {
                if (!draggable.options.refreshPositions) {
                    $.ui.ddmanager.prepareOffsets(draggable, event);
                }
            });
        },
        drag: function(draggable, event) {

            // If you have a highly dynamic page, you might try this option. It renders positions
            // every time you move the mouse.
            if (draggable.options.refreshPositions) {
                $.ui.ddmanager.prepareOffsets(draggable, event);
            }

            // Run through all droppables and check their positions based on specific tolerance options
            $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {

                if (this.options.disabled || this.greedyChild || !this.visible) {
                    return;
                }

                var parentInstance, scope, parent,
                    intersects = intersect(draggable, this, this.options.tolerance, event),
                    c = !intersects && this.isover ?
                    "isout" :
                    (intersects && !this.isover ? "isover" : null);
                if (!c) {
                    return;
                }

                if (this.options.greedy) {

                    // find droppable parents with same scope
                    scope = this.options.scope;
                    parent = this.element.parents(":data(ui-droppable)").filter(function() {
                        return $(this).droppable("instance").options.scope === scope;
                    });

                    if (parent.length) {
                        parentInstance = $(parent[0]).droppable("instance");
                        parentInstance.greedyChild = (c === "isover");
                    }
                }

                // We just moved into a greedy child
                if (parentInstance && c === "isover") {
                    parentInstance.isover = false;
                    parentInstance.isout = true;
                    parentInstance._out.call(parentInstance, event);
                }

                this[c] = true;
                this[c === "isout" ? "isover" : "isout"] = false;
                this[c === "isover" ? "_over" : "_out"].call(this, event);

                // We just moved out of a greedy child
                if (parentInstance && c === "isout") {
                    parentInstance.isout = false;
                    parentInstance.isover = true;
                    parentInstance._over.call(parentInstance, event);
                }
            });

        },
        dragStop: function(draggable, event) {
            draggable.element.parentsUntil("body").off("scroll.droppable");

            // Call prepareOffsets one final time since IE does not fire return scroll events when
            // overflow was caused by drag (see #5003)
            if (!draggable.options.refreshPositions) {
                $.ui.ddmanager.prepareOffsets(draggable, event);
            }
        }
    };

    // DEPRECATED
    // TODO: switch return back to widget declaration at top of file when this is removed
    if ($.uiBackCompat !== false) {

        // Backcompat for activeClass and hoverClass options
        $.widget("ui.droppable", $.ui.droppable, {
            options: {
                hoverClass: false,
                activeClass: false
            },
            _addActiveClass: function() {
                this._super();
                if (this.options.activeClass) {
                    this.element.addClass(this.options.activeClass);
                }
            },
            _removeActiveClass: function() {
                this._super();
                if (this.options.activeClass) {
                    this.element.removeClass(this.options.activeClass);
                }
            },
            _addHoverClass: function() {
                this._super();
                if (this.options.hoverClass) {
                    this.element.addClass(this.options.hoverClass);
                }
            },
            _removeHoverClass: function() {
                this._super();
                if (this.options.hoverClass) {
                    this.element.removeClass(this.options.hoverClass);
                }
            }
        });
    }

    var widgetsDroppable = $.ui.droppable;


    /*!
     * jQuery UI Resizable 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Resizable
    //>>group: Interactions
    //>>description: Enables resize functionality for any element.
    //>>docs: http://api.jqueryui.com/resizable/
    //>>demos: http://jqueryui.com/resizable/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/resizable.css
    //>>css.theme: ../../themes/base/theme.css



    $.widget("ui.resizable", $.ui.mouse, {
        version: "1.12.1",
        widgetEventPrefix: "resize",
        options: {
            alsoResize: false,
            animate: false,
            animateDuration: "slow",
            animateEasing: "swing",
            aspectRatio: false,
            autoHide: false,
            classes: {
                "ui-resizable-se": "ui-icon ui-icon-gripsmall-diagonal-se"
            },
            containment: false,
            ghost: false,
            grid: false,
            handles: "e,s,se",
            helper: false,
            maxHeight: null,
            maxWidth: null,
            minHeight: 10,
            minWidth: 10,

            // See #7960
            zIndex: 90,

            // Callbacks
            resize: null,
            start: null,
            stop: null
        },

        _num: function(value) {
            return parseFloat(value) || 0;
        },

        _isNumber: function(value) {
            return !isNaN(parseFloat(value));
        },

        _hasScroll: function(el, a) {

            if ($(el).css("overflow") === "hidden") {
                return false;
            }

            var scroll = (a && a === "left") ? "scrollLeft" : "scrollTop",
                has = false;

            if (el[scroll] > 0) {
                return true;
            }

            // TODO: determine which cases actually cause this to happen
            // if the element doesn't have the scroll set, see if it's possible to
            // set the scroll
            el[scroll] = 1;
            has = (el[scroll] > 0);
            el[scroll] = 0;
            return has;
        },

        _create: function() {

            var margins,
                o = this.options,
                that = this;
            this._addClass("ui-resizable");

            $.extend(this, {
                _aspectRatio: !!(o.aspectRatio),
                aspectRatio: o.aspectRatio,
                originalElement: this.element,
                _proportionallyResizeElements: [],
                _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
            });

            // Wrap the element if it cannot hold child nodes
            if (this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)) {

                this.element.wrap(
                    $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
                        position: this.element.css("position"),
                        width: this.element.outerWidth(),
                        height: this.element.outerHeight(),
                        top: this.element.css("top"),
                        left: this.element.css("left")
                    })
                );

                this.element = this.element.parent().data(
                    "ui-resizable", this.element.resizable("instance")
                );

                this.elementIsWrapper = true;

                margins = {
                    marginTop: this.originalElement.css("marginTop"),
                    marginRight: this.originalElement.css("marginRight"),
                    marginBottom: this.originalElement.css("marginBottom"),
                    marginLeft: this.originalElement.css("marginLeft")
                };

                this.element.css(margins);
                this.originalElement.css("margin", 0);

                // support: Safari
                // Prevent Safari textarea resize
                this.originalResizeStyle = this.originalElement.css("resize");
                this.originalElement.css("resize", "none");

                this._proportionallyResizeElements.push(this.originalElement.css({
                    position: "static",
                    zoom: 1,
                    display: "block"
                }));

                // Support: IE9
                // avoid IE jump (hard set the margin)
                this.originalElement.css(margins);

                this._proportionallyResize();
            }

            this._setupHandles();

            if (o.autoHide) {
                $(this.element)
                    .on("mouseenter", function() {
                        if (o.disabled) {
                            return;
                        }
                        that._removeClass("ui-resizable-autohide");
                        that._handles.show();
                    })
                    .on("mouseleave", function() {
                        if (o.disabled) {
                            return;
                        }
                        if (!that.resizing) {
                            that._addClass("ui-resizable-autohide");
                            that._handles.hide();
                        }
                    });
            }

            this._mouseInit();
        },

        _destroy: function() {

            this._mouseDestroy();

            var wrapper,
                _destroy = function(exp) {
                    $(exp)
                        .removeData("resizable")
                        .removeData("ui-resizable")
                        .off(".resizable")
                        .find(".ui-resizable-handle")
                        .remove();
                };

            // TODO: Unwrap at same DOM position
            if (this.elementIsWrapper) {
                _destroy(this.element);
                wrapper = this.element;
                this.originalElement.css({
                    position: wrapper.css("position"),
                    width: wrapper.outerWidth(),
                    height: wrapper.outerHeight(),
                    top: wrapper.css("top"),
                    left: wrapper.css("left")
                }).insertAfter(wrapper);
                wrapper.remove();
            }

            this.originalElement.css("resize", this.originalResizeStyle);
            _destroy(this.originalElement);

            return this;
        },

        _setOption: function(key, value) {
            this._super(key, value);

            switch (key) {
                case "handles":
                    this._removeHandles();
                    this._setupHandles();
                    break;
                default:
                    break;
            }
        },

        _setupHandles: function() {
            var o = this.options,
                handle, i, n, hname, axis, that = this;
            this.handles = o.handles ||
                (!$(".ui-resizable-handle", this.element).length ?
                    "e,s,se" : {
                        n: ".ui-resizable-n",
                        e: ".ui-resizable-e",
                        s: ".ui-resizable-s",
                        w: ".ui-resizable-w",
                        se: ".ui-resizable-se",
                        sw: ".ui-resizable-sw",
                        ne: ".ui-resizable-ne",
                        nw: ".ui-resizable-nw"
                    });

            this._handles = $();
            if (this.handles.constructor === String) {

                if (this.handles === "all") {
                    this.handles = "n,e,s,w,se,sw,ne,nw";
                }

                n = this.handles.split(",");
                this.handles = {};

                for (i = 0; i < n.length; i++) {

                    handle = $.trim(n[i]);
                    hname = "ui-resizable-" + handle;
                    axis = $("<div>");
                    this._addClass(axis, "ui-resizable-handle " + hname);

                    axis.css({ zIndex: o.zIndex });

                    this.handles[handle] = ".ui-resizable-" + handle;
                    this.element.append(axis);
                }

            }

            this._renderAxis = function(target) {

                var i, axis, padPos, padWrapper;

                target = target || this.element;

                for (i in this.handles) {

                    if (this.handles[i].constructor === String) {
                        this.handles[i] = this.element.children(this.handles[i]).first().show();
                    } else if (this.handles[i].jquery || this.handles[i].nodeType) {
                        this.handles[i] = $(this.handles[i]);
                        this._on(this.handles[i], { "mousedown": that._mouseDown });
                    }

                    if (this.elementIsWrapper &&
                        this.originalElement[0]
                        .nodeName
                        .match(/^(textarea|input|select|button)$/i)) {
                        axis = $(this.handles[i], this.element);

                        padWrapper = /sw|ne|nw|se|n|s/.test(i) ?
                            axis.outerHeight() :
                            axis.outerWidth();

                        padPos = ["padding",
                            /ne|nw|n/.test(i) ? "Top" :
                            /se|sw|s/.test(i) ? "Bottom" :
                            /^e$/.test(i) ? "Right" : "Left"
                        ].join("");

                        target.css(padPos, padWrapper);

                        this._proportionallyResize();
                    }

                    this._handles = this._handles.add(this.handles[i]);
                }
            };

            // TODO: make renderAxis a prototype function
            this._renderAxis(this.element);

            this._handles = this._handles.add(this.element.find(".ui-resizable-handle"));
            this._handles.disableSelection();

            this._handles.on("mouseover", function() {
                if (!that.resizing) {
                    if (this.className) {
                        axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
                    }
                    that.axis = axis && axis[1] ? axis[1] : "se";
                }
            });

            if (o.autoHide) {
                this._handles.hide();
                this._addClass("ui-resizable-autohide");
            }
        },

        _removeHandles: function() {
            this._handles.remove();
        },

        _mouseCapture: function(event) {
            var i, handle,
                capture = false;

            for (i in this.handles) {
                handle = $(this.handles[i])[0];
                if (handle === event.target || $.contains(handle, event.target)) {
                    capture = true;
                }
            }

            return !this.options.disabled && capture;
        },

        _mouseStart: function(event) {

            var curleft, curtop, cursor,
                o = this.options,
                el = this.element;

            this.resizing = true;

            this._renderProxy();

            curleft = this._num(this.helper.css("left"));
            curtop = this._num(this.helper.css("top"));

            if (o.containment) {
                curleft += $(o.containment).scrollLeft() || 0;
                curtop += $(o.containment).scrollTop() || 0;
            }

            this.offset = this.helper.offset();
            this.position = { left: curleft, top: curtop };

            this.size = this._helper ? {
                width: this.helper.width(),
                height: this.helper.height()
            } : {
                width: el.width(),
                height: el.height()
            };

            this.originalSize = this._helper ? {
                width: el.outerWidth(),
                height: el.outerHeight()
            } : {
                width: el.width(),
                height: el.height()
            };

            this.sizeDiff = {
                width: el.outerWidth() - el.width(),
                height: el.outerHeight() - el.height()
            };

            this.originalPosition = { left: curleft, top: curtop };
            this.originalMousePosition = { left: event.pageX, top: event.pageY };

            this.aspectRatio = (typeof o.aspectRatio === "number") ?
                o.aspectRatio :
                ((this.originalSize.width / this.originalSize.height) || 1);

            cursor = $(".ui-resizable-" + this.axis).css("cursor");
            $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);

            this._addClass("ui-resizable-resizing");
            this._propagate("start", event);
            return true;
        },

        _mouseDrag: function(event) {

            var data, props,
                smp = this.originalMousePosition,
                a = this.axis,
                dx = (event.pageX - smp.left) || 0,
                dy = (event.pageY - smp.top) || 0,
                trigger = this._change[a];

            this._updatePrevProperties();

            if (!trigger) {
                return false;
            }

            data = trigger.apply(this, [event, dx, dy]);

            this._updateVirtualBoundaries(event.shiftKey);
            if (this._aspectRatio || event.shiftKey) {
                data = this._updateRatio(data, event);
            }

            data = this._respectSize(data, event);

            this._updateCache(data);

            this._propagate("resize", event);

            props = this._applyChanges();

            if (!this._helper && this._proportionallyResizeElements.length) {
                this._proportionallyResize();
            }

            if (!$.isEmptyObject(props)) {
                this._updatePrevProperties();
                this._trigger("resize", event, this.ui());
                this._applyChanges();
            }

            return false;
        },

        _mouseStop: function(event) {

            this.resizing = false;
            var pr, ista, soffseth, soffsetw, s, left, top,
                o = this.options,
                that = this;

            if (this._helper) {

                pr = this._proportionallyResizeElements;
                ista = pr.length && (/textarea/i).test(pr[0].nodeName);
                soffseth = ista && this._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height;
                soffsetw = ista ? 0 : that.sizeDiff.width;

                s = {
                    width: (that.helper.width() - soffsetw),
                    height: (that.helper.height() - soffseth)
                };
                left = (parseFloat(that.element.css("left")) +
                    (that.position.left - that.originalPosition.left)) || null;
                top = (parseFloat(that.element.css("top")) +
                    (that.position.top - that.originalPosition.top)) || null;

                if (!o.animate) {
                    this.element.css($.extend(s, { top: top, left: left }));
                }

                that.helper.height(that.size.height);
                that.helper.width(that.size.width);

                if (this._helper && !o.animate) {
                    this._proportionallyResize();
                }
            }

            $("body").css("cursor", "auto");

            this._removeClass("ui-resizable-resizing");

            this._propagate("stop", event);

            if (this._helper) {
                this.helper.remove();
            }

            return false;

        },

        _updatePrevProperties: function() {
            this.prevPosition = {
                top: this.position.top,
                left: this.position.left
            };
            this.prevSize = {
                width: this.size.width,
                height: this.size.height
            };
        },

        _applyChanges: function() {
            var props = {};

            if (this.position.top !== this.prevPosition.top) {
                props.top = this.position.top + "px";
            }
            if (this.position.left !== this.prevPosition.left) {
                props.left = this.position.left + "px";
            }
            if (this.size.width !== this.prevSize.width) {
                props.width = this.size.width + "px";
            }
            if (this.size.height !== this.prevSize.height) {
                props.height = this.size.height + "px";
            }

            this.helper.css(props);

            return props;
        },

        _updateVirtualBoundaries: function(forceAspectRatio) {
            var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
                o = this.options;

            b = {
                minWidth: this._isNumber(o.minWidth) ? o.minWidth : 0,
                maxWidth: this._isNumber(o.maxWidth) ? o.maxWidth : Infinity,
                minHeight: this._isNumber(o.minHeight) ? o.minHeight : 0,
                maxHeight: this._isNumber(o.maxHeight) ? o.maxHeight : Infinity
            };

            if (this._aspectRatio || forceAspectRatio) {
                pMinWidth = b.minHeight * this.aspectRatio;
                pMinHeight = b.minWidth / this.aspectRatio;
                pMaxWidth = b.maxHeight * this.aspectRatio;
                pMaxHeight = b.maxWidth / this.aspectRatio;

                if (pMinWidth > b.minWidth) {
                    b.minWidth = pMinWidth;
                }
                if (pMinHeight > b.minHeight) {
                    b.minHeight = pMinHeight;
                }
                if (pMaxWidth < b.maxWidth) {
                    b.maxWidth = pMaxWidth;
                }
                if (pMaxHeight < b.maxHeight) {
                    b.maxHeight = pMaxHeight;
                }
            }
            this._vBoundaries = b;
        },

        _updateCache: function(data) {
            this.offset = this.helper.offset();
            if (this._isNumber(data.left)) {
                this.position.left = data.left;
            }
            if (this._isNumber(data.top)) {
                this.position.top = data.top;
            }
            if (this._isNumber(data.height)) {
                this.size.height = data.height;
            }
            if (this._isNumber(data.width)) {
                this.size.width = data.width;
            }
        },

        _updateRatio: function(data) {

            var cpos = this.position,
                csize = this.size,
                a = this.axis;

            if (this._isNumber(data.height)) {
                data.width = (data.height * this.aspectRatio);
            } else if (this._isNumber(data.width)) {
                data.height = (data.width / this.aspectRatio);
            }

            if (a === "sw") {
                data.left = cpos.left + (csize.width - data.width);
                data.top = null;
            }
            if (a === "nw") {
                data.top = cpos.top + (csize.height - data.height);
                data.left = cpos.left + (csize.width - data.width);
            }

            return data;
        },

        _respectSize: function(data) {

            var o = this._vBoundaries,
                a = this.axis,
                ismaxw = this._isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width),
                ismaxh = this._isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
                isminw = this._isNumber(data.width) && o.minWidth && (o.minWidth > data.width),
                isminh = this._isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
                dw = this.originalPosition.left + this.originalSize.width,
                dh = this.originalPosition.top + this.originalSize.height,
                cw = /sw|nw|w/.test(a),
                ch = /nw|ne|n/.test(a);
            if (isminw) {
                data.width = o.minWidth;
            }
            if (isminh) {
                data.height = o.minHeight;
            }
            if (ismaxw) {
                data.width = o.maxWidth;
            }
            if (ismaxh) {
                data.height = o.maxHeight;
            }

            if (isminw && cw) {
                data.left = dw - o.minWidth;
            }
            if (ismaxw && cw) {
                data.left = dw - o.maxWidth;
            }
            if (isminh && ch) {
                data.top = dh - o.minHeight;
            }
            if (ismaxh && ch) {
                data.top = dh - o.maxHeight;
            }

            // Fixing jump error on top/left - bug #2330
            if (!data.width && !data.height && !data.left && data.top) {
                data.top = null;
            } else if (!data.width && !data.height && !data.top && data.left) {
                data.left = null;
            }

            return data;
        },

        _getPaddingPlusBorderDimensions: function(element) {
            var i = 0,
                widths = [],
                borders = [
                    element.css("borderTopWidth"),
                    element.css("borderRightWidth"),
                    element.css("borderBottomWidth"),
                    element.css("borderLeftWidth")
                ],
                paddings = [
                    element.css("paddingTop"),
                    element.css("paddingRight"),
                    element.css("paddingBottom"),
                    element.css("paddingLeft")
                ];

            for (; i < 4; i++) {
                widths[i] = (parseFloat(borders[i]) || 0);
                widths[i] += (parseFloat(paddings[i]) || 0);
            }

            return {
                height: widths[0] + widths[2],
                width: widths[1] + widths[3]
            };
        },

        _proportionallyResize: function() {

            if (!this._proportionallyResizeElements.length) {
                return;
            }

            var prel,
                i = 0,
                element = this.helper || this.element;

            for (; i < this._proportionallyResizeElements.length; i++) {

                prel = this._proportionallyResizeElements[i];

                // TODO: Seems like a bug to cache this.outerDimensions
                // considering that we are in a loop.
                if (!this.outerDimensions) {
                    this.outerDimensions = this._getPaddingPlusBorderDimensions(prel);
                }

                prel.css({
                    height: (element.height() - this.outerDimensions.height) || 0,
                    width: (element.width() - this.outerDimensions.width) || 0
                });

            }

        },

        _renderProxy: function() {

            var el = this.element,
                o = this.options;
            this.elementOffset = el.offset();

            if (this._helper) {

                this.helper = this.helper || $("<div style='overflow:hidden;'></div>");

                this._addClass(this.helper, this._helper);
                this.helper.css({
                    width: this.element.outerWidth(),
                    height: this.element.outerHeight(),
                    position: "absolute",
                    left: this.elementOffset.left + "px",
                    top: this.elementOffset.top + "px",
                    zIndex: ++o.zIndex //TODO: Don't modify option
                });

                this.helper
                    .appendTo("body")
                    .disableSelection();

            } else {
                this.helper = this.element;
            }

        },

        _change: {
            e: function(event, dx) {
                return { width: this.originalSize.width + dx };
            },
            w: function(event, dx) {
                var cs = this.originalSize,
                    sp = this.originalPosition;
                return { left: sp.left + dx, width: cs.width - dx };
            },
            n: function(event, dx, dy) {
                var cs = this.originalSize,
                    sp = this.originalPosition;
                return { top: sp.top + dy, height: cs.height - dy };
            },
            s: function(event, dx, dy) {
                return { height: this.originalSize.height + dy };
            },
            se: function(event, dx, dy) {
                return $.extend(this._change.s.apply(this, arguments),
                    this._change.e.apply(this, [event, dx, dy]));
            },
            sw: function(event, dx, dy) {
                return $.extend(this._change.s.apply(this, arguments),
                    this._change.w.apply(this, [event, dx, dy]));
            },
            ne: function(event, dx, dy) {
                return $.extend(this._change.n.apply(this, arguments),
                    this._change.e.apply(this, [event, dx, dy]));
            },
            nw: function(event, dx, dy) {
                return $.extend(this._change.n.apply(this, arguments),
                    this._change.w.apply(this, [event, dx, dy]));
            }
        },

        _propagate: function(n, event) {
            $.ui.plugin.call(this, n, [event, this.ui()]);
            (n !== "resize" && this._trigger(n, event, this.ui()));
        },

        plugins: {},

        ui: function() {
            return {
                originalElement: this.originalElement,
                element: this.element,
                helper: this.helper,
                position: this.position,
                size: this.size,
                originalSize: this.originalSize,
                originalPosition: this.originalPosition
            };
        }

    });

    /*
     * Resizable Extensions
     */

    $.ui.plugin.add("resizable", "animate", {

        stop: function(event) {
            var that = $(this).resizable("instance"),
                o = that.options,
                pr = that._proportionallyResizeElements,
                ista = pr.length && (/textarea/i).test(pr[0].nodeName),
                soffseth = ista && that._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height,
                soffsetw = ista ? 0 : that.sizeDiff.width,
                style = {
                    width: (that.size.width - soffsetw),
                    height: (that.size.height - soffseth)
                },
                left = (parseFloat(that.element.css("left")) +
                    (that.position.left - that.originalPosition.left)) || null,
                top = (parseFloat(that.element.css("top")) +
                    (that.position.top - that.originalPosition.top)) || null;

            that.element.animate(
                $.extend(style, top && left ? { top: top, left: left } : {}), {
                    duration: o.animateDuration,
                    easing: o.animateEasing,
                    step: function() {

                        var data = {
                            width: parseFloat(that.element.css("width")),
                            height: parseFloat(that.element.css("height")),
                            top: parseFloat(that.element.css("top")),
                            left: parseFloat(that.element.css("left"))
                        };

                        if (pr && pr.length) {
                            $(pr[0]).css({ width: data.width, height: data.height });
                        }

                        // Propagating resize, and updating values for each animation step
                        that._updateCache(data);
                        that._propagate("resize", event);

                    }
                }
            );
        }

    });

    $.ui.plugin.add("resizable", "containment", {

        start: function() {
            var element, p, co, ch, cw, width, height,
                that = $(this).resizable("instance"),
                o = that.options,
                el = that.element,
                oc = o.containment,
                ce = (oc instanceof $) ?
                oc.get(0) :
                (/parent/.test(oc)) ? el.parent().get(0) : oc;

            if (!ce) {
                return;
            }

            that.containerElement = $(ce);

            if (/document/.test(oc) || oc === document) {
                that.containerOffset = {
                    left: 0,
                    top: 0
                };
                that.containerPosition = {
                    left: 0,
                    top: 0
                };

                that.parentData = {
                    element: $(document),
                    left: 0,
                    top: 0,
                    width: $(document).width(),
                    height: $(document).height() || document.body.parentNode.scrollHeight
                };
            } else {
                element = $(ce);
                p = [];
                $(["Top", "Right", "Left", "Bottom"]).each(function(i, name) {
                    p[i] = that._num(element.css("padding" + name));
                });

                that.containerOffset = element.offset();
                that.containerPosition = element.position();
                that.containerSize = {
                    height: (element.innerHeight() - p[3]),
                    width: (element.innerWidth() - p[1])
                };

                co = that.containerOffset;
                ch = that.containerSize.height;
                cw = that.containerSize.width;
                width = (that._hasScroll(ce, "left") ? ce.scrollWidth : cw);
                height = (that._hasScroll(ce) ? ce.scrollHeight : ch);

                that.parentData = {
                    element: ce,
                    left: co.left,
                    top: co.top,
                    width: width,
                    height: height
                };
            }
        },

        resize: function(event) {
            var woset, hoset, isParent, isOffsetRelative,
                that = $(this).resizable("instance"),
                o = that.options,
                co = that.containerOffset,
                cp = that.position,
                pRatio = that._aspectRatio || event.shiftKey,
                cop = {
                    top: 0,
                    left: 0
                },
                ce = that.containerElement,
                continueResize = true;

            if (ce[0] !== document && (/static/).test(ce.css("position"))) {
                cop = co;
            }

            if (cp.left < (that._helper ? co.left : 0)) {
                that.size.width = that.size.width +
                    (that._helper ?
                        (that.position.left - co.left) :
                        (that.position.left - cop.left));

                if (pRatio) {
                    that.size.height = that.size.width / that.aspectRatio;
                    continueResize = false;
                }
                that.position.left = o.helper ? co.left : 0;
            }

            if (cp.top < (that._helper ? co.top : 0)) {
                that.size.height = that.size.height +
                    (that._helper ?
                        (that.position.top - co.top) :
                        that.position.top);

                if (pRatio) {
                    that.size.width = that.size.height * that.aspectRatio;
                    continueResize = false;
                }
                that.position.top = that._helper ? co.top : 0;
            }

            isParent = that.containerElement.get(0) === that.element.parent().get(0);
            isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position"));

            if (isParent && isOffsetRelative) {
                that.offset.left = that.parentData.left + that.position.left;
                that.offset.top = that.parentData.top + that.position.top;
            } else {
                that.offset.left = that.element.offset().left;
                that.offset.top = that.element.offset().top;
            }

            woset = Math.abs(that.sizeDiff.width +
                (that._helper ?
                    that.offset.left - cop.left :
                    (that.offset.left - co.left)));

            hoset = Math.abs(that.sizeDiff.height +
                (that._helper ?
                    that.offset.top - cop.top :
                    (that.offset.top - co.top)));

            if (woset + that.size.width >= that.parentData.width) {
                that.size.width = that.parentData.width - woset;
                if (pRatio) {
                    that.size.height = that.size.width / that.aspectRatio;
                    continueResize = false;
                }
            }

            if (hoset + that.size.height >= that.parentData.height) {
                that.size.height = that.parentData.height - hoset;
                if (pRatio) {
                    that.size.width = that.size.height * that.aspectRatio;
                    continueResize = false;
                }
            }

            if (!continueResize) {
                that.position.left = that.prevPosition.left;
                that.position.top = that.prevPosition.top;
                that.size.width = that.prevSize.width;
                that.size.height = that.prevSize.height;
            }
        },

        stop: function() {
            var that = $(this).resizable("instance"),
                o = that.options,
                co = that.containerOffset,
                cop = that.containerPosition,
                ce = that.containerElement,
                helper = $(that.helper),
                ho = helper.offset(),
                w = helper.outerWidth() - that.sizeDiff.width,
                h = helper.outerHeight() - that.sizeDiff.height;

            if (that._helper && !o.animate && (/relative/).test(ce.css("position"))) {
                $(this).css({
                    left: ho.left - cop.left - co.left,
                    width: w,
                    height: h
                });
            }

            if (that._helper && !o.animate && (/static/).test(ce.css("position"))) {
                $(this).css({
                    left: ho.left - cop.left - co.left,
                    width: w,
                    height: h
                });
            }
        }
    });

    $.ui.plugin.add("resizable", "alsoResize", {

        start: function() {
            var that = $(this).resizable("instance"),
                o = that.options;

            $(o.alsoResize).each(function() {
                var el = $(this);
                el.data("ui-resizable-alsoresize", {
                    width: parseFloat(el.width()),
                    height: parseFloat(el.height()),
                    left: parseFloat(el.css("left")),
                    top: parseFloat(el.css("top"))
                });
            });
        },

        resize: function(event, ui) {
            var that = $(this).resizable("instance"),
                o = that.options,
                os = that.originalSize,
                op = that.originalPosition,
                delta = {
                    height: (that.size.height - os.height) || 0,
                    width: (that.size.width - os.width) || 0,
                    top: (that.position.top - op.top) || 0,
                    left: (that.position.left - op.left) || 0
                };

            $(o.alsoResize).each(function() {
                var el = $(this),
                    start = $(this).data("ui-resizable-alsoresize"),
                    style = {},
                    css = el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"];

                $.each(css, function(i, prop) {
                    var sum = (start[prop] || 0) + (delta[prop] || 0);
                    if (sum && sum >= 0) {
                        style[prop] = sum || null;
                    }
                });

                el.css(style);
            });
        },

        stop: function() {
            $(this).removeData("ui-resizable-alsoresize");
        }
    });

    $.ui.plugin.add("resizable", "ghost", {

        start: function() {

            var that = $(this).resizable("instance"),
                cs = that.size;

            that.ghost = that.originalElement.clone();
            that.ghost.css({
                opacity: 0.25,
                display: "block",
                position: "relative",
                height: cs.height,
                width: cs.width,
                margin: 0,
                left: 0,
                top: 0
            });

            that._addClass(that.ghost, "ui-resizable-ghost");

            // DEPRECATED
            // TODO: remove after 1.12
            if ($.uiBackCompat !== false && typeof that.options.ghost === "string") {

                // Ghost option
                that.ghost.addClass(this.options.ghost);
            }

            that.ghost.appendTo(that.helper);

        },

        resize: function() {
            var that = $(this).resizable("instance");
            if (that.ghost) {
                that.ghost.css({
                    position: "relative",
                    height: that.size.height,
                    width: that.size.width
                });
            }
        },

        stop: function() {
            var that = $(this).resizable("instance");
            if (that.ghost && that.helper) {
                that.helper.get(0).removeChild(that.ghost.get(0));
            }
        }

    });

    $.ui.plugin.add("resizable", "grid", {

        resize: function() {
            var outerDimensions,
                that = $(this).resizable("instance"),
                o = that.options,
                cs = that.size,
                os = that.originalSize,
                op = that.originalPosition,
                a = that.axis,
                grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid,
                gridX = (grid[0] || 1),
                gridY = (grid[1] || 1),
                ox = Math.round((cs.width - os.width) / gridX) * gridX,
                oy = Math.round((cs.height - os.height) / gridY) * gridY,
                newWidth = os.width + ox,
                newHeight = os.height + oy,
                isMaxWidth = o.maxWidth && (o.maxWidth < newWidth),
                isMaxHeight = o.maxHeight && (o.maxHeight < newHeight),
                isMinWidth = o.minWidth && (o.minWidth > newWidth),
                isMinHeight = o.minHeight && (o.minHeight > newHeight);

            o.grid = grid;

            if (isMinWidth) {
                newWidth += gridX;
            }
            if (isMinHeight) {
                newHeight += gridY;
            }
            if (isMaxWidth) {
                newWidth -= gridX;
            }
            if (isMaxHeight) {
                newHeight -= gridY;
            }

            if (/^(se|s|e)$/.test(a)) {
                that.size.width = newWidth;
                that.size.height = newHeight;
            } else if (/^(ne)$/.test(a)) {
                that.size.width = newWidth;
                that.size.height = newHeight;
                that.position.top = op.top - oy;
            } else if (/^(sw)$/.test(a)) {
                that.size.width = newWidth;
                that.size.height = newHeight;
                that.position.left = op.left - ox;
            } else {
                if (newHeight - gridY <= 0 || newWidth - gridX <= 0) {
                    outerDimensions = that._getPaddingPlusBorderDimensions(this);
                }

                if (newHeight - gridY > 0) {
                    that.size.height = newHeight;
                    that.position.top = op.top - oy;
                } else {
                    newHeight = gridY - outerDimensions.height;
                    that.size.height = newHeight;
                    that.position.top = op.top + os.height - newHeight;
                }
                if (newWidth - gridX > 0) {
                    that.size.width = newWidth;
                    that.position.left = op.left - ox;
                } else {
                    newWidth = gridX - outerDimensions.width;
                    that.size.width = newWidth;
                    that.position.left = op.left + os.width - newWidth;
                }
            }
        }

    });

    var widgetsResizable = $.ui.resizable;


    /*!
     * jQuery UI Selectable 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Selectable
    //>>group: Interactions
    //>>description: Allows groups of elements to be selected with the mouse.
    //>>docs: http://api.jqueryui.com/selectable/
    //>>demos: http://jqueryui.com/selectable/
    //>>css.structure: ../../themes/base/selectable.css



    var widgetsSelectable = $.widget("ui.selectable", $.ui.mouse, {
        version: "1.12.1",
        options: {
            appendTo: "body",
            autoRefresh: true,
            distance: 0,
            filter: "*",
            tolerance: "touch",

            // Callbacks
            selected: null,
            selecting: null,
            start: null,
            stop: null,
            unselected: null,
            unselecting: null
        },
        _create: function() {
            var that = this;

            this._addClass("ui-selectable");

            this.dragged = false;

            // Cache selectee children based on filter
            this.refresh = function() {
                that.elementPos = $(that.element[0]).offset();
                that.selectees = $(that.options.filter, that.element[0]);
                that._addClass(that.selectees, "ui-selectee");
                that.selectees.each(function() {
                    var $this = $(this),
                        selecteeOffset = $this.offset(),
                        pos = {
                            left: selecteeOffset.left - that.elementPos.left,
                            top: selecteeOffset.top - that.elementPos.top
                        };
                    $.data(this, "selectable-item", {
                        element: this,
                        $element: $this,
                        left: pos.left,
                        top: pos.top,
                        right: pos.left + $this.outerWidth(),
                        bottom: pos.top + $this.outerHeight(),
                        startselected: false,
                        selected: $this.hasClass("ui-selected"),
                        selecting: $this.hasClass("ui-selecting"),
                        unselecting: $this.hasClass("ui-unselecting")
                    });
                });
            };
            this.refresh();

            this._mouseInit();

            this.helper = $("<div>");
            this._addClass(this.helper, "ui-selectable-helper");
        },

        _destroy: function() {
            this.selectees.removeData("selectable-item");
            this._mouseDestroy();
        },

        _mouseStart: function(event) {
            var that = this,
                options = this.options;

            this.opos = [event.pageX, event.pageY];
            this.elementPos = $(this.element[0]).offset();

            if (this.options.disabled) {
                return;
            }

            this.selectees = $(options.filter, this.element[0]);

            this._trigger("start", event);

            $(options.appendTo).append(this.helper);

            // position helper (lasso)
            this.helper.css({
                "left": event.pageX,
                "top": event.pageY,
                "width": 0,
                "height": 0
            });

            if (options.autoRefresh) {
                this.refresh();
            }

            this.selectees.filter(".ui-selected").each(function() {
                var selectee = $.data(this, "selectable-item");
                selectee.startselected = true;
                if (!event.metaKey && !event.ctrlKey) {
                    that._removeClass(selectee.$element, "ui-selected");
                    selectee.selected = false;
                    that._addClass(selectee.$element, "ui-unselecting");
                    selectee.unselecting = true;

                    // selectable UNSELECTING callback
                    that._trigger("unselecting", event, {
                        unselecting: selectee.element
                    });
                }
            });

            $(event.target).parents().addBack().each(function() {
                var doSelect,
                    selectee = $.data(this, "selectable-item");
                if (selectee) {
                    doSelect = (!event.metaKey && !event.ctrlKey) ||
                        !selectee.$element.hasClass("ui-selected");
                    that._removeClass(selectee.$element, doSelect ? "ui-unselecting" : "ui-selected")
                        ._addClass(selectee.$element, doSelect ? "ui-selecting" : "ui-unselecting");
                    selectee.unselecting = !doSelect;
                    selectee.selecting = doSelect;
                    selectee.selected = doSelect;

                    // selectable (UN)SELECTING callback
                    if (doSelect) {
                        that._trigger("selecting", event, {
                            selecting: selectee.element
                        });
                    } else {
                        that._trigger("unselecting", event, {
                            unselecting: selectee.element
                        });
                    }
                    return false;
                }
            });

        },

        _mouseDrag: function(event) {

            this.dragged = true;

            if (this.options.disabled) {
                return;
            }

            var tmp,
                that = this,
                options = this.options,
                x1 = this.opos[0],
                y1 = this.opos[1],
                x2 = event.pageX,
                y2 = event.pageY;

            if (x1 > x2) {
                tmp = x2;
                x2 = x1;
                x1 = tmp;
            }
            if (y1 > y2) {
                tmp = y2;
                y2 = y1;
                y1 = tmp;
            }
            this.helper.css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1 });

            this.selectees.each(function() {
                var selectee = $.data(this, "selectable-item"),
                    hit = false,
                    offset = {};

                //prevent helper from being selected if appendTo: selectable
                if (!selectee || selectee.element === that.element[0]) {
                    return;
                }

                offset.left = selectee.left + that.elementPos.left;
                offset.right = selectee.right + that.elementPos.left;
                offset.top = selectee.top + that.elementPos.top;
                offset.bottom = selectee.bottom + that.elementPos.top;

                if (options.tolerance === "touch") {
                    hit = (!(offset.left > x2 || offset.right < x1 || offset.top > y2 ||
                        offset.bottom < y1));
                } else if (options.tolerance === "fit") {
                    hit = (offset.left > x1 && offset.right < x2 && offset.top > y1 &&
                        offset.bottom < y2);
                }

                if (hit) {

                    // SELECT
                    if (selectee.selected) {
                        that._removeClass(selectee.$element, "ui-selected");
                        selectee.selected = false;
                    }
                    if (selectee.unselecting) {
                        that._removeClass(selectee.$element, "ui-unselecting");
                        selectee.unselecting = false;
                    }
                    if (!selectee.selecting) {
                        that._addClass(selectee.$element, "ui-selecting");
                        selectee.selecting = true;

                        // selectable SELECTING callback
                        that._trigger("selecting", event, {
                            selecting: selectee.element
                        });
                    }
                } else {

                    // UNSELECT
                    if (selectee.selecting) {
                        if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
                            that._removeClass(selectee.$element, "ui-selecting");
                            selectee.selecting = false;
                            that._addClass(selectee.$element, "ui-selected");
                            selectee.selected = true;
                        } else {
                            that._removeClass(selectee.$element, "ui-selecting");
                            selectee.selecting = false;
                            if (selectee.startselected) {
                                that._addClass(selectee.$element, "ui-unselecting");
                                selectee.unselecting = true;
                            }

                            // selectable UNSELECTING callback
                            that._trigger("unselecting", event, {
                                unselecting: selectee.element
                            });
                        }
                    }
                    if (selectee.selected) {
                        if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
                            that._removeClass(selectee.$element, "ui-selected");
                            selectee.selected = false;

                            that._addClass(selectee.$element, "ui-unselecting");
                            selectee.unselecting = true;

                            // selectable UNSELECTING callback
                            that._trigger("unselecting", event, {
                                unselecting: selectee.element
                            });
                        }
                    }
                }
            });

            return false;
        },

        _mouseStop: function(event) {
            var that = this;

            this.dragged = false;

            $(".ui-unselecting", this.element[0]).each(function() {
                var selectee = $.data(this, "selectable-item");
                that._removeClass(selectee.$element, "ui-unselecting");
                selectee.unselecting = false;
                selectee.startselected = false;
                that._trigger("unselected", event, {
                    unselected: selectee.element
                });
            });
            $(".ui-selecting", this.element[0]).each(function() {
                var selectee = $.data(this, "selectable-item");
                that._removeClass(selectee.$element, "ui-selecting")
                    ._addClass(selectee.$element, "ui-selected");
                selectee.selecting = false;
                selectee.selected = true;
                selectee.startselected = true;
                that._trigger("selected", event, {
                    selected: selectee.element
                });
            });
            this._trigger("stop", event);

            this.helper.remove();

            return false;
        }

    });


    /*!
     * jQuery UI Sortable 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Sortable
    //>>group: Interactions
    //>>description: Enables items in a list to be sorted using the mouse.
    //>>docs: http://api.jqueryui.com/sortable/
    //>>demos: http://jqueryui.com/sortable/
    //>>css.structure: ../../themes/base/sortable.css



    var widgetsSortable = $.widget("ui.sortable", $.ui.mouse, {
        version: "1.12.1",
        widgetEventPrefix: "sort",
        ready: false,
        options: {
            appendTo: "parent",
            axis: false,
            connectWith: false,
            containment: false,
            cursor: "auto",
            cursorAt: false,
            dropOnEmpty: true,
            forcePlaceholderSize: false,
            forceHelperSize: false,
            grid: false,
            handle: false,
            helper: "original",
            items: "> *",
            opacity: false,
            placeholder: false,
            revert: false,
            scroll: true,
            scrollSensitivity: 20,
            scrollSpeed: 20,
            scope: "default",
            tolerance: "intersect",
            zIndex: 1000,

            // Callbacks
            activate: null,
            beforeStop: null,
            change: null,
            deactivate: null,
            out: null,
            over: null,
            receive: null,
            remove: null,
            sort: null,
            start: null,
            stop: null,
            update: null
        },

        _isOverAxis: function(x, reference, size) {
            return (x >= reference) && (x < (reference + size));
        },

        _isFloating: function(item) {
            return (/left|right/).test(item.css("float")) ||
                (/inline|table-cell/).test(item.css("display"));
        },

        _create: function() {
            this.containerCache = {};
            this._addClass("ui-sortable");

            //Get the items
            this.refresh();

            //Let's determine the parent's offset
            this.offset = this.element.offset();

            //Initialize mouse events for interaction
            this._mouseInit();

            this._setHandleClassName();

            //We're ready to go
            this.ready = true;

        },

        _setOption: function(key, value) {
            this._super(key, value);

            if (key === "handle") {
                this._setHandleClassName();
            }
        },

        _setHandleClassName: function() {
            var that = this;
            this._removeClass(this.element.find(".ui-sortable-handle"), "ui-sortable-handle");
            $.each(this.items, function() {
                that._addClass(
                    this.instance.options.handle ?
                    this.item.find(this.instance.options.handle) :
                    this.item,
                    "ui-sortable-handle"
                );
            });
        },

        _destroy: function() {
            this._mouseDestroy();

            for (var i = this.items.length - 1; i >= 0; i--) {
                this.items[i].item.removeData(this.widgetName + "-item");
            }

            return this;
        },

        _mouseCapture: function(event, overrideHandle) {
            var currentItem = null,
                validHandle = false,
                that = this;

            if (this.reverting) {
                return false;
            }

            if (this.options.disabled || this.options.type === "static") {
                return false;
            }

            //We have to refresh the items data once first
            this._refreshItems(event);

            //Find out if the clicked node (or one of its parents) is a actual item in this.items
            $(event.target).parents().each(function() {
                if ($.data(this, that.widgetName + "-item") === that) {
                    currentItem = $(this);
                    return false;
                }
            });
            if ($.data(event.target, that.widgetName + "-item") === that) {
                currentItem = $(event.target);
            }

            if (!currentItem) {
                return false;
            }
            if (this.options.handle && !overrideHandle) {
                $(this.options.handle, currentItem).find("*").addBack().each(function() {
                    if (this === event.target) {
                        validHandle = true;
                    }
                });
                if (!validHandle) {
                    return false;
                }
            }

            this.currentItem = currentItem;
            this._removeCurrentsFromItems();
            return true;

        },

        _mouseStart: function(event, overrideHandle, noActivation) {

            var i, body,
                o = this.options;

            this.currentContainer = this;

            //We only need to call refreshPositions, because the refreshItems call has been moved to
            // mouseCapture
            this.refreshPositions();

            //Create and append the visible helper
            this.helper = this._createHelper(event);

            //Cache the helper size
            this._cacheHelperProportions();

            /*
             * - Position generation -
             * This block generates everything position related - it's the core of draggables.
             */

            //Cache the margins of the original element
            this._cacheMargins();

            //Get the next scrolling parent
            this.scrollParent = this.helper.scrollParent();

            //The element's absolute position on the page minus margins
            this.offset = this.currentItem.offset();
            this.offset = {
                top: this.offset.top - this.margins.top,
                left: this.offset.left - this.margins.left
            };

            $.extend(this.offset, {
                click: { //Where the click happened, relative to the element
                    left: event.pageX - this.offset.left,
                    top: event.pageY - this.offset.top
                },
                parent: this._getParentOffset(),

                // This is a relative to absolute position minus the actual position calculation -
                // only used for relative positioned helper
                relative: this._getRelativeOffset()
            });

            // Only after we got the offset, we can change the helper's position to absolute
            // TODO: Still need to figure out a way to make relative sorting possible
            this.helper.css("position", "absolute");
            this.cssPosition = this.helper.css("position");

            //Generate the original position
            this.originalPosition = this._generatePosition(event);
            this.originalPageX = event.pageX;
            this.originalPageY = event.pageY;

            //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
            (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

            //Cache the former DOM position
            this.domPosition = {
                prev: this.currentItem.prev()[0],
                parent: this.currentItem.parent()[0]
            };

            // If the helper is not the original, hide the original so it's not playing any role during
            // the drag, won't cause anything bad this way
            if (this.helper[0] !== this.currentItem[0]) {
                this.currentItem.hide();
            }

            //Create the placeholder
            this._createPlaceholder();

            //Set a containment if given in the options
            if (o.containment) {
                this._setContainment();
            }

            if (o.cursor && o.cursor !== "auto") { // cursor option
                body = this.document.find("body");

                // Support: IE
                this.storedCursor = body.css("cursor");
                body.css("cursor", o.cursor);

                this.storedStylesheet =
                    $("<style>*{ cursor: " + o.cursor + " !important; }</style>").appendTo(body);
            }

            if (o.opacity) { // opacity option
                if (this.helper.css("opacity")) {
                    this._storedOpacity = this.helper.css("opacity");
                }
                this.helper.css("opacity", o.opacity);
            }

            if (o.zIndex) { // zIndex option
                if (this.helper.css("zIndex")) {
                    this._storedZIndex = this.helper.css("zIndex");
                }
                this.helper.css("zIndex", o.zIndex);
            }

            //Prepare scrolling
            if (this.scrollParent[0] !== this.document[0] &&
                this.scrollParent[0].tagName !== "HTML") {
                this.overflowOffset = this.scrollParent.offset();
            }

            //Call callbacks
            this._trigger("start", event, this._uiHash());

            //Recache the helper size
            if (!this._preserveHelperProportions) {
                this._cacheHelperProportions();
            }

            //Post "activate" events to possible containers
            if (!noActivation) {
                for (i = this.containers.length - 1; i >= 0; i--) {
                    this.containers[i]._trigger("activate", event, this._uiHash(this));
                }
            }

            //Prepare possible droppables
            if ($.ui.ddmanager) {
                $.ui.ddmanager.current = this;
            }

            if ($.ui.ddmanager && !o.dropBehaviour) {
                $.ui.ddmanager.prepareOffsets(this, event);
            }

            this.dragging = true;

            this._addClass(this.helper, "ui-sortable-helper");

            // Execute the drag once - this causes the helper not to be visiblebefore getting its
            // correct position
            this._mouseDrag(event);
            return true;

        },

        _mouseDrag: function(event) {
            var i, item, itemElement, intersection,
                o = this.options,
                scrolled = false;

            //Compute the helpers position
            this.position = this._generatePosition(event);
            this.positionAbs = this._convertPositionTo("absolute");

            if (!this.lastPositionAbs) {
                this.lastPositionAbs = this.positionAbs;
            }

            //Do scrolling
            if (this.options.scroll) {
                if (this.scrollParent[0] !== this.document[0] &&
                    this.scrollParent[0].tagName !== "HTML") {

                    if ((this.overflowOffset.top + this.scrollParent[0].offsetHeight) -
                        event.pageY < o.scrollSensitivity) {
                        this.scrollParent[0].scrollTop =
                            scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
                    } else if (event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
                        this.scrollParent[0].scrollTop =
                            scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
                    }

                    if ((this.overflowOffset.left + this.scrollParent[0].offsetWidth) -
                        event.pageX < o.scrollSensitivity) {
                        this.scrollParent[0].scrollLeft = scrolled =
                            this.scrollParent[0].scrollLeft + o.scrollSpeed;
                    } else if (event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
                        this.scrollParent[0].scrollLeft = scrolled =
                            this.scrollParent[0].scrollLeft - o.scrollSpeed;
                    }

                } else {

                    if (event.pageY - this.document.scrollTop() < o.scrollSensitivity) {
                        scrolled = this.document.scrollTop(this.document.scrollTop() - o.scrollSpeed);
                    } else if (this.window.height() - (event.pageY - this.document.scrollTop()) <
                        o.scrollSensitivity) {
                        scrolled = this.document.scrollTop(this.document.scrollTop() + o.scrollSpeed);
                    }

                    if (event.pageX - this.document.scrollLeft() < o.scrollSensitivity) {
                        scrolled = this.document.scrollLeft(
                            this.document.scrollLeft() - o.scrollSpeed
                        );
                    } else if (this.window.width() - (event.pageX - this.document.scrollLeft()) <
                        o.scrollSensitivity) {
                        scrolled = this.document.scrollLeft(
                            this.document.scrollLeft() + o.scrollSpeed
                        );
                    }

                }

                if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
                    $.ui.ddmanager.prepareOffsets(this, event);
                }
            }

            //Regenerate the absolute position used for position checks
            this.positionAbs = this._convertPositionTo("absolute");

            //Set the helper position
            if (!this.options.axis || this.options.axis !== "y") {
                this.helper[0].style.left = this.position.left + "px";
            }
            if (!this.options.axis || this.options.axis !== "x") {
                this.helper[0].style.top = this.position.top + "px";
            }

            //Rearrange
            for (i = this.items.length - 1; i >= 0; i--) {

                //Cache variables and intersection, continue if no intersection
                item = this.items[i];
                itemElement = item.item[0];
                intersection = this._intersectsWithPointer(item);
                if (!intersection) {
                    continue;
                }

                // Only put the placeholder inside the current Container, skip all
                // items from other containers. This works because when moving
                // an item from one container to another the
                // currentContainer is switched before the placeholder is moved.
                //
                // Without this, moving items in "sub-sortables" can cause
                // the placeholder to jitter between the outer and inner container.
                if (item.instance !== this.currentContainer) {
                    continue;
                }

                // Cannot intersect with itself
                // no useless actions that have been done before
                // no action if the item moved is the parent of the item checked
                if (itemElement !== this.currentItem[0] &&
                    this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
                    !$.contains(this.placeholder[0], itemElement) &&
                    (this.options.type === "semi-dynamic" ?
                        !$.contains(this.element[0], itemElement) :
                        true
                    )
                ) {

                    this.direction = intersection === 1 ? "down" : "up";

                    if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
                        this._rearrange(event, item);
                    } else {
                        break;
                    }

                    this._trigger("change", event, this._uiHash());
                    break;
                }
            }

            //Post events to containers
            this._contactContainers(event);

            //Interconnect with droppables
            if ($.ui.ddmanager) {
                $.ui.ddmanager.drag(this, event);
            }

            //Call callbacks
            this._trigger("sort", event, this._uiHash());

            this.lastPositionAbs = this.positionAbs;
            return false;

        },

        _mouseStop: function(event, noPropagation) {

            if (!event) {
                return;
            }

            //If we are using droppables, inform the manager about the drop
            if ($.ui.ddmanager && !this.options.dropBehaviour) {
                $.ui.ddmanager.drop(this, event);
            }

            if (this.options.revert) {
                var that = this,
                    cur = this.placeholder.offset(),
                    axis = this.options.axis,
                    animation = {};

                if (!axis || axis === "x") {
                    animation.left = cur.left - this.offset.parent.left - this.margins.left +
                        (this.offsetParent[0] === this.document[0].body ?
                            0 :
                            this.offsetParent[0].scrollLeft
                        );
                }
                if (!axis || axis === "y") {
                    animation.top = cur.top - this.offset.parent.top - this.margins.top +
                        (this.offsetParent[0] === this.document[0].body ?
                            0 :
                            this.offsetParent[0].scrollTop
                        );
                }
                this.reverting = true;
                $(this.helper).animate(
                    animation,
                    parseInt(this.options.revert, 10) || 500,
                    function() {
                        that._clear(event);
                    }
                );
            } else {
                this._clear(event, noPropagation);
            }

            return false;

        },

        cancel: function() {

            if (this.dragging) {

                this._mouseUp(new $.Event("mouseup", { target: null }));

                if (this.options.helper === "original") {
                    this.currentItem.css(this._storedCSS);
                    this._removeClass(this.currentItem, "ui-sortable-helper");
                } else {
                    this.currentItem.show();
                }

                //Post deactivating events to containers
                for (var i = this.containers.length - 1; i >= 0; i--) {
                    this.containers[i]._trigger("deactivate", null, this._uiHash(this));
                    if (this.containers[i].containerCache.over) {
                        this.containers[i]._trigger("out", null, this._uiHash(this));
                        this.containers[i].containerCache.over = 0;
                    }
                }

            }

            if (this.placeholder) {

                //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
                // it unbinds ALL events from the original node!
                if (this.placeholder[0].parentNode) {
                    this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
                }
                if (this.options.helper !== "original" && this.helper &&
                    this.helper[0].parentNode) {
                    this.helper.remove();
                }

                $.extend(this, {
                    helper: null,
                    dragging: false,
                    reverting: false,
                    _noFinalSort: null
                });

                if (this.domPosition.prev) {
                    $(this.domPosition.prev).after(this.currentItem);
                } else {
                    $(this.domPosition.parent).prepend(this.currentItem);
                }
            }

            return this;

        },

        serialize: function(o) {

            var items = this._getItemsAsjQuery(o && o.connected),
                str = [];
            o = o || {};

            $(items).each(function() {
                var res = ($(o.item || this).attr(o.attribute || "id") || "")
                    .match(o.expression || (/(.+)[\-=_](.+)/));
                if (res) {
                    str.push(
                        (o.key || res[1] + "[]") +
                        "=" + (o.key && o.expression ? res[1] : res[2]));
                }
            });

            if (!str.length && o.key) {
                str.push(o.key + "=");
            }

            return str.join("&");

        },

        toArray: function(o) {

            var items = this._getItemsAsjQuery(o && o.connected),
                ret = [];

            o = o || {};

            items.each(function() {
                ret.push($(o.item || this).attr(o.attribute || "id") || "");
            });
            return ret;

        },

        /* Be careful with the following core functions */
        _intersectsWith: function(item) {

            var x1 = this.positionAbs.left,
                x2 = x1 + this.helperProportions.width,
                y1 = this.positionAbs.top,
                y2 = y1 + this.helperProportions.height,
                l = item.left,
                r = l + item.width,
                t = item.top,
                b = t + item.height,
                dyClick = this.offset.click.top,
                dxClick = this.offset.click.left,
                isOverElementHeight = (this.options.axis === "x") || ((y1 + dyClick) > t &&
                    (y1 + dyClick) < b),
                isOverElementWidth = (this.options.axis === "y") || ((x1 + dxClick) > l &&
                    (x1 + dxClick) < r),
                isOverElement = isOverElementHeight && isOverElementWidth;

            if (this.options.tolerance === "pointer" ||
                this.options.forcePointerForContainers ||
                (this.options.tolerance !== "pointer" &&
                    this.helperProportions[this.floating ? "width" : "height"] >
                    item[this.floating ? "width" : "height"])
            ) {
                return isOverElement;
            } else {

                return (l < x1 + (this.helperProportions.width / 2) && // Right Half
                    x2 - (this.helperProportions.width / 2) < r && // Left Half
                    t < y1 + (this.helperProportions.height / 2) && // Bottom Half
                    y2 - (this.helperProportions.height / 2) < b); // Top Half

            }
        },

        _intersectsWithPointer: function(item) {
            var verticalDirection, horizontalDirection,
                isOverElementHeight = (this.options.axis === "x") ||
                this._isOverAxis(
                    this.positionAbs.top + this.offset.click.top, item.top, item.height),
                isOverElementWidth = (this.options.axis === "y") ||
                this._isOverAxis(
                    this.positionAbs.left + this.offset.click.left, item.left, item.width),
                isOverElement = isOverElementHeight && isOverElementWidth;

            if (!isOverElement) {
                return false;
            }

            verticalDirection = this._getDragVerticalDirection();
            horizontalDirection = this._getDragHorizontalDirection();

            return this.floating ?
                ((horizontalDirection === "right" || verticalDirection === "down") ? 2 : 1) :
                (verticalDirection && (verticalDirection === "down" ? 2 : 1));

        },

        _intersectsWithSides: function(item) {

            var isOverBottomHalf = this._isOverAxis(this.positionAbs.top +
                    this.offset.click.top, item.top + (item.height / 2), item.height),
                isOverRightHalf = this._isOverAxis(this.positionAbs.left +
                    this.offset.click.left, item.left + (item.width / 2), item.width),
                verticalDirection = this._getDragVerticalDirection(),
                horizontalDirection = this._getDragHorizontalDirection();

            if (this.floating && horizontalDirection) {
                return ((horizontalDirection === "right" && isOverRightHalf) ||
                    (horizontalDirection === "left" && !isOverRightHalf));
            } else {
                return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) ||
                    (verticalDirection === "up" && !isOverBottomHalf));
            }

        },

        _getDragVerticalDirection: function() {
            var delta = this.positionAbs.top - this.lastPositionAbs.top;
            return delta !== 0 && (delta > 0 ? "down" : "up");
        },

        _getDragHorizontalDirection: function() {
            var delta = this.positionAbs.left - this.lastPositionAbs.left;
            return delta !== 0 && (delta > 0 ? "right" : "left");
        },

        refresh: function(event) {
            this._refreshItems(event);
            this._setHandleClassName();
            this.refreshPositions();
            return this;
        },

        _connectWith: function() {
            var options = this.options;
            return options.connectWith.constructor === String ? [options.connectWith] :
                options.connectWith;
        },

        _getItemsAsjQuery: function(connected) {

            var i, j, cur, inst,
                items = [],
                queries = [],
                connectWith = this._connectWith();

            if (connectWith && connected) {
                for (i = connectWith.length - 1; i >= 0; i--) {
                    cur = $(connectWith[i], this.document[0]);
                    for (j = cur.length - 1; j >= 0; j--) {
                        inst = $.data(cur[j], this.widgetFullName);
                        if (inst && inst !== this && !inst.options.disabled) {
                            queries.push([$.isFunction(inst.options.items) ?
                                inst.options.items.call(inst.element) :
                                $(inst.options.items, inst.element)
                                .not(".ui-sortable-helper")
                                .not(".ui-sortable-placeholder"), inst
                            ]);
                        }
                    }
                }
            }

            queries.push([$.isFunction(this.options.items) ?
                this.options.items
                .call(this.element, null, { options: this.options, item: this.currentItem }) :
                $(this.options.items, this.element)
                .not(".ui-sortable-helper")
                .not(".ui-sortable-placeholder"), this
            ]);

            function addItems() {
                items.push(this);
            }
            for (i = queries.length - 1; i >= 0; i--) {
                queries[i][0].each(addItems);
            }

            return $(items);

        },

        _removeCurrentsFromItems: function() {

            var list = this.currentItem.find(":data(" + this.widgetName + "-item)");

            this.items = $.grep(this.items, function(item) {
                for (var j = 0; j < list.length; j++) {
                    if (list[j] === item.item[0]) {
                        return false;
                    }
                }
                return true;
            });

        },

        _refreshItems: function(event) {

            this.items = [];
            this.containers = [this];

            var i, j, cur, inst, targetData, _queries, item, queriesLength,
                items = this.items,
                queries = [
                    [$.isFunction(this.options.items) ?
                        this.options.items.call(this.element[0], event, { item: this.currentItem }) :
                        $(this.options.items, this.element), this
                    ]
                ],
                connectWith = this._connectWith();

            //Shouldn't be run the first time through due to massive slow-down
            if (connectWith && this.ready) {
                for (i = connectWith.length - 1; i >= 0; i--) {
                    cur = $(connectWith[i], this.document[0]);
                    for (j = cur.length - 1; j >= 0; j--) {
                        inst = $.data(cur[j], this.widgetFullName);
                        if (inst && inst !== this && !inst.options.disabled) {
                            queries.push([$.isFunction(inst.options.items) ?
                                inst.options.items
                                .call(inst.element[0], event, { item: this.currentItem }) :
                                $(inst.options.items, inst.element), inst
                            ]);
                            this.containers.push(inst);
                        }
                    }
                }
            }

            for (i = queries.length - 1; i >= 0; i--) {
                targetData = queries[i][1];
                _queries = queries[i][0];

                for (j = 0, queriesLength = _queries.length; j < queriesLength; j++) {
                    item = $(_queries[j]);

                    // Data for target checking (mouse manager)
                    item.data(this.widgetName + "-item", targetData);

                    items.push({
                        item: item,
                        instance: targetData,
                        width: 0,
                        height: 0,
                        left: 0,
                        top: 0
                    });
                }
            }

        },

        refreshPositions: function(fast) {

            // Determine whether items are being displayed horizontally
            this.floating = this.items.length ?
                this.options.axis === "x" || this._isFloating(this.items[0].item) :
                false;

            //This has to be redone because due to the item being moved out/into the offsetParent,
            // the offsetParent's position will change
            if (this.offsetParent && this.helper) {
                this.offset.parent = this._getParentOffset();
            }

            var i, item, t, p;

            for (i = this.items.length - 1; i >= 0; i--) {
                item = this.items[i];

                //We ignore calculating positions of all connected containers when we're not over them
                if (item.instance !== this.currentContainer && this.currentContainer &&
                    item.item[0] !== this.currentItem[0]) {
                    continue;
                }

                t = this.options.toleranceElement ?
                    $(this.options.toleranceElement, item.item) :
                    item.item;

                if (!fast) {
                    item.width = t.outerWidth();
                    item.height = t.outerHeight();
                }

                p = t.offset();
                item.left = p.left;
                item.top = p.top;
            }

            if (this.options.custom && this.options.custom.refreshContainers) {
                this.options.custom.refreshContainers.call(this);
            } else {
                for (i = this.containers.length - 1; i >= 0; i--) {
                    p = this.containers[i].element.offset();
                    this.containers[i].containerCache.left = p.left;
                    this.containers[i].containerCache.top = p.top;
                    this.containers[i].containerCache.width =
                        this.containers[i].element.outerWidth();
                    this.containers[i].containerCache.height =
                        this.containers[i].element.outerHeight();
                }
            }

            return this;
        },

        _createPlaceholder: function(that) {
            that = that || this;
            var className,
                o = that.options;

            if (!o.placeholder || o.placeholder.constructor === String) {
                className = o.placeholder;
                o.placeholder = {
                    element: function() {

                        var nodeName = that.currentItem[0].nodeName.toLowerCase(),
                            element = $("<" + nodeName + ">", that.document[0]);

                        that._addClass(element, "ui-sortable-placeholder",
                                className || that.currentItem[0].className)
                            ._removeClass(element, "ui-sortable-helper");

                        if (nodeName === "tbody") {
                            that._createTrPlaceholder(
                                that.currentItem.find("tr").eq(0),
                                $("<tr>", that.document[0]).appendTo(element)
                            );
                        } else if (nodeName === "tr") {
                            that._createTrPlaceholder(that.currentItem, element);
                        } else if (nodeName === "img") {
                            element.attr("src", that.currentItem.attr("src"));
                        }

                        if (!className) {
                            element.css("visibility", "hidden");
                        }

                        return element;
                    },
                    update: function(container, p) {

                        // 1. If a className is set as 'placeholder option, we don't force sizes -
                        // the class is responsible for that
                        // 2. The option 'forcePlaceholderSize can be enabled to force it even if a
                        // class name is specified
                        if (className && !o.forcePlaceholderSize) {
                            return;
                        }

                        //If the element doesn't have a actual height by itself (without styles coming
                        // from a stylesheet), it receives the inline height from the dragged item
                        if (!p.height()) {
                            p.height(
                                that.currentItem.innerHeight() -
                                parseInt(that.currentItem.css("paddingTop") || 0, 10) -
                                parseInt(that.currentItem.css("paddingBottom") || 0, 10));
                        }
                        if (!p.width()) {
                            p.width(
                                that.currentItem.innerWidth() -
                                parseInt(that.currentItem.css("paddingLeft") || 0, 10) -
                                parseInt(that.currentItem.css("paddingRight") || 0, 10));
                        }
                    }
                };
            }

            //Create the placeholder
            that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));

            //Append it after the actual current item
            that.currentItem.after(that.placeholder);

            //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
            o.placeholder.update(that, that.placeholder);

        },

        _createTrPlaceholder: function(sourceTr, targetTr) {
            var that = this;

            sourceTr.children().each(function() {
                $("<td>&#160;</td>", that.document[0])
                    .attr("colspan", $(this).attr("colspan") || 1)
                    .appendTo(targetTr);
            });
        },

        _contactContainers: function(event) {
            var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom,
                floating, axis,
                innermostContainer = null,
                innermostIndex = null;

            // Get innermost container that intersects with item
            for (i = this.containers.length - 1; i >= 0; i--) {

                // Never consider a container that's located within the item itself
                if ($.contains(this.currentItem[0], this.containers[i].element[0])) {
                    continue;
                }

                if (this._intersectsWith(this.containers[i].containerCache)) {

                    // If we've already found a container and it's more "inner" than this, then continue
                    if (innermostContainer &&
                        $.contains(
                            this.containers[i].element[0],
                            innermostContainer.element[0])) {
                        continue;
                    }

                    innermostContainer = this.containers[i];
                    innermostIndex = i;

                } else {

                    // container doesn't intersect. trigger "out" event if necessary
                    if (this.containers[i].containerCache.over) {
                        this.containers[i]._trigger("out", event, this._uiHash(this));
                        this.containers[i].containerCache.over = 0;
                    }
                }

            }

            // If no intersecting containers found, return
            if (!innermostContainer) {
                return;
            }

            // Move the item into the container if it's not there already
            if (this.containers.length === 1) {
                if (!this.containers[innermostIndex].containerCache.over) {
                    this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
                    this.containers[innermostIndex].containerCache.over = 1;
                }
            } else {

                // When entering a new container, we will find the item with the least distance and
                // append our item near it
                dist = 10000;
                itemWithLeastDistance = null;
                floating = innermostContainer.floating || this._isFloating(this.currentItem);
                posProperty = floating ? "left" : "top";
                sizeProperty = floating ? "width" : "height";
                axis = floating ? "pageX" : "pageY";

                for (j = this.items.length - 1; j >= 0; j--) {
                    if (!$.contains(
                            this.containers[innermostIndex].element[0], this.items[j].item[0])) {
                        continue;
                    }
                    if (this.items[j].item[0] === this.currentItem[0]) {
                        continue;
                    }

                    cur = this.items[j].item.offset()[posProperty];
                    nearBottom = false;
                    if (event[axis] - cur > this.items[j][sizeProperty] / 2) {
                        nearBottom = true;
                    }

                    if (Math.abs(event[axis] - cur) < dist) {
                        dist = Math.abs(event[axis] - cur);
                        itemWithLeastDistance = this.items[j];
                        this.direction = nearBottom ? "up" : "down";
                    }
                }

                //Check if dropOnEmpty is enabled
                if (!itemWithLeastDistance && !this.options.dropOnEmpty) {
                    return;
                }

                if (this.currentContainer === this.containers[innermostIndex]) {
                    if (!this.currentContainer.containerCache.over) {
                        this.containers[innermostIndex]._trigger("over", event, this._uiHash());
                        this.currentContainer.containerCache.over = 1;
                    }
                    return;
                }

                itemWithLeastDistance ?
                    this._rearrange(event, itemWithLeastDistance, null, true) :
                    this._rearrange(event, null, this.containers[innermostIndex].element, true);
                this._trigger("change", event, this._uiHash());
                this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
                this.currentContainer = this.containers[innermostIndex];

                //Update the placeholder
                this.options.placeholder.update(this.currentContainer, this.placeholder);

                this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
                this.containers[innermostIndex].containerCache.over = 1;
            }

        },

        _createHelper: function(event) {

            var o = this.options,
                helper = $.isFunction(o.helper) ?
                $(o.helper.apply(this.element[0], [event, this.currentItem])) :
                (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);

            //Add the helper to the DOM if that didn't happen already
            if (!helper.parents("body").length) {
                $(o.appendTo !== "parent" ?
                    o.appendTo :
                    this.currentItem[0].parentNode)[0].appendChild(helper[0]);
            }

            if (helper[0] === this.currentItem[0]) {
                this._storedCSS = {
                    width: this.currentItem[0].style.width,
                    height: this.currentItem[0].style.height,
                    position: this.currentItem.css("position"),
                    top: this.currentItem.css("top"),
                    left: this.currentItem.css("left")
                };
            }

            if (!helper[0].style.width || o.forceHelperSize) {
                helper.width(this.currentItem.width());
            }
            if (!helper[0].style.height || o.forceHelperSize) {
                helper.height(this.currentItem.height());
            }

            return helper;

        },

        _adjustOffsetFromHelper: function(obj) {
            if (typeof obj === "string") {
                obj = obj.split(" ");
            }
            if ($.isArray(obj)) {
                obj = { left: +obj[0], top: +obj[1] || 0 };
            }
            if ("left" in obj) {
                this.offset.click.left = obj.left + this.margins.left;
            }
            if ("right" in obj) {
                this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
            }
            if ("top" in obj) {
                this.offset.click.top = obj.top + this.margins.top;
            }
            if ("bottom" in obj) {
                this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
            }
        },

        _getParentOffset: function() {

            //Get the offsetParent and cache its position
            this.offsetParent = this.helper.offsetParent();
            var po = this.offsetParent.offset();

            // This is a special case where we need to modify a offset calculated on start, since the
            // following happened:
            // 1. The position of the helper is absolute, so it's position is calculated based on the
            // next positioned parent
            // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
            // the document, which means that the scroll is included in the initial calculation of the
            // offset of the parent, and never recalculated upon drag
            if (this.cssPosition === "absolute" && this.scrollParent[0] !== this.document[0] &&
                $.contains(this.scrollParent[0], this.offsetParent[0])) {
                po.left += this.scrollParent.scrollLeft();
                po.top += this.scrollParent.scrollTop();
            }

            // This needs to be actually done for all browsers, since pageX/pageY includes this
            // information with an ugly IE fix
            if (this.offsetParent[0] === this.document[0].body ||
                (this.offsetParent[0].tagName &&
                    this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
                po = { top: 0, left: 0 };
            }

            return {
                top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0),
                left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)
            };

        },

        _getRelativeOffset: function() {

            if (this.cssPosition === "relative") {
                var p = this.currentItem.position();
                return {
                    top: p.top - (parseInt(this.helper.css("top"), 10) || 0) +
                        this.scrollParent.scrollTop(),
                    left: p.left - (parseInt(this.helper.css("left"), 10) || 0) +
                        this.scrollParent.scrollLeft()
                };
            } else {
                return { top: 0, left: 0 };
            }

        },

        _cacheMargins: function() {
            this.margins = {
                left: (parseInt(this.currentItem.css("marginLeft"), 10) || 0),
                top: (parseInt(this.currentItem.css("marginTop"), 10) || 0)
            };
        },

        _cacheHelperProportions: function() {
            this.helperProportions = {
                width: this.helper.outerWidth(),
                height: this.helper.outerHeight()
            };
        },

        _setContainment: function() {

            var ce, co, over,
                o = this.options;
            if (o.containment === "parent") {
                o.containment = this.helper[0].parentNode;
            }
            if (o.containment === "document" || o.containment === "window") {
                this.containment = [
                    0 - this.offset.relative.left - this.offset.parent.left,
                    0 - this.offset.relative.top - this.offset.parent.top,
                    o.containment === "document" ?
                    this.document.width() :
                    this.window.width() - this.helperProportions.width - this.margins.left,
                    (o.containment === "document" ?
                        (this.document.height() || document.body.parentNode.scrollHeight) :
                        this.window.height() || this.document[0].body.parentNode.scrollHeight
                    ) - this.helperProportions.height - this.margins.top
                ];
            }

            if (!(/^(document|window|parent)$/).test(o.containment)) {
                ce = $(o.containment)[0];
                co = $(o.containment).offset();
                over = ($(ce).css("overflow") !== "hidden");

                this.containment = [
                    co.left + (parseInt($(ce).css("borderLeftWidth"), 10) || 0) +
                    (parseInt($(ce).css("paddingLeft"), 10) || 0) - this.margins.left,
                    co.top + (parseInt($(ce).css("borderTopWidth"), 10) || 0) +
                    (parseInt($(ce).css("paddingTop"), 10) || 0) - this.margins.top,
                    co.left + (over ? Math.max(ce.scrollWidth, ce.offsetWidth) : ce.offsetWidth) -
                    (parseInt($(ce).css("borderLeftWidth"), 10) || 0) -
                    (parseInt($(ce).css("paddingRight"), 10) || 0) -
                    this.helperProportions.width - this.margins.left,
                    co.top + (over ? Math.max(ce.scrollHeight, ce.offsetHeight) : ce.offsetHeight) -
                    (parseInt($(ce).css("borderTopWidth"), 10) || 0) -
                    (parseInt($(ce).css("paddingBottom"), 10) || 0) -
                    this.helperProportions.height - this.margins.top
                ];
            }

        },

        _convertPositionTo: function(d, pos) {

            if (!pos) {
                pos = this.position;
            }
            var mod = d === "absolute" ? 1 : -1,
                scroll = this.cssPosition === "absolute" &&
                !(this.scrollParent[0] !== this.document[0] &&
                    $.contains(this.scrollParent[0], this.offsetParent[0])) ?
                this.offsetParent :
                this.scrollParent,
                scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

            return {
                top: (

                    // The absolute mouse position
                    pos.top +

                    // Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.relative.top * mod +

                    // The offsetParent's offset without borders (offset + border)
                    this.offset.parent.top * mod -
                    ((this.cssPosition === "fixed" ?
                        -this.scrollParent.scrollTop() :
                        (scrollIsRootNode ? 0 : scroll.scrollTop())) * mod)
                ),
                left: (

                    // The absolute mouse position
                    pos.left +

                    // Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.relative.left * mod +

                    // The offsetParent's offset without borders (offset + border)
                    this.offset.parent.left * mod -
                    ((this.cssPosition === "fixed" ?
                        -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 :
                        scroll.scrollLeft()) * mod)
                )
            };

        },

        _generatePosition: function(event) {

            var top, left,
                o = this.options,
                pageX = event.pageX,
                pageY = event.pageY,
                scroll = this.cssPosition === "absolute" &&
                !(this.scrollParent[0] !== this.document[0] &&
                    $.contains(this.scrollParent[0], this.offsetParent[0])) ?
                this.offsetParent :
                this.scrollParent,
                scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

            // This is another very weird special case that only happens for relative elements:
            // 1. If the css position is relative
            // 2. and the scroll parent is the document or similar to the offset parent
            // we have to refresh the relative offset during the scroll so there are no jumps
            if (this.cssPosition === "relative" && !(this.scrollParent[0] !== this.document[0] &&
                    this.scrollParent[0] !== this.offsetParent[0])) {
                this.offset.relative = this._getRelativeOffset();
            }

            /*
             * - Position constraining -
             * Constrain the position to a mix of grid, containment.
             */

            if (this.originalPosition) { //If we are not dragging yet, we won't check for options

                if (this.containment) {
                    if (event.pageX - this.offset.click.left < this.containment[0]) {
                        pageX = this.containment[0] + this.offset.click.left;
                    }
                    if (event.pageY - this.offset.click.top < this.containment[1]) {
                        pageY = this.containment[1] + this.offset.click.top;
                    }
                    if (event.pageX - this.offset.click.left > this.containment[2]) {
                        pageX = this.containment[2] + this.offset.click.left;
                    }
                    if (event.pageY - this.offset.click.top > this.containment[3]) {
                        pageY = this.containment[3] + this.offset.click.top;
                    }
                }

                if (o.grid) {
                    top = this.originalPageY + Math.round((pageY - this.originalPageY) /
                        o.grid[1]) * o.grid[1];
                    pageY = this.containment ?
                        ((top - this.offset.click.top >= this.containment[1] &&
                                top - this.offset.click.top <= this.containment[3]) ?
                            top :
                            ((top - this.offset.click.top >= this.containment[1]) ?
                                top - o.grid[1] : top + o.grid[1])) :
                        top;

                    left = this.originalPageX + Math.round((pageX - this.originalPageX) /
                        o.grid[0]) * o.grid[0];
                    pageX = this.containment ?
                        ((left - this.offset.click.left >= this.containment[0] &&
                                left - this.offset.click.left <= this.containment[2]) ?
                            left :
                            ((left - this.offset.click.left >= this.containment[0]) ?
                                left - o.grid[0] : left + o.grid[0])) :
                        left;
                }

            }

            return {
                top: (

                    // The absolute mouse position
                    pageY -

                    // Click offset (relative to the element)
                    this.offset.click.top -

                    // Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.relative.top -

                    // The offsetParent's offset without borders (offset + border)
                    this.offset.parent.top +
                    ((this.cssPosition === "fixed" ?
                        -this.scrollParent.scrollTop() :
                        (scrollIsRootNode ? 0 : scroll.scrollTop())))
                ),
                left: (

                    // The absolute mouse position
                    pageX -

                    // Click offset (relative to the element)
                    this.offset.click.left -

                    // Only for relative positioned nodes: Relative offset from element to offset parent
                    this.offset.relative.left -

                    // The offsetParent's offset without borders (offset + border)
                    this.offset.parent.left +
                    ((this.cssPosition === "fixed" ?
                        -this.scrollParent.scrollLeft() :
                        scrollIsRootNode ? 0 : scroll.scrollLeft()))
                )
            };

        },

        _rearrange: function(event, i, a, hardRefresh) {

            a ? a[0].appendChild(this.placeholder[0]) :
                i.item[0].parentNode.insertBefore(this.placeholder[0],
                    (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));

            //Various things done here to improve the performance:
            // 1. we create a setTimeout, that calls refreshPositions
            // 2. on the instance, we have a counter variable, that get's higher after every append
            // 3. on the local scope, we copy the counter variable, and check in the timeout,
            // if it's still the same
            // 4. this lets only the last addition to the timeout stack through
            this.counter = this.counter ? ++this.counter : 1;
            var counter = this.counter;

            this._delay(function() {
                if (counter === this.counter) {

                    //Precompute after each DOM insertion, NOT on mousemove
                    this.refreshPositions(!hardRefresh);
                }
            });

        },

        _clear: function(event, noPropagation) {

            this.reverting = false;

            // We delay all events that have to be triggered to after the point where the placeholder
            // has been removed and everything else normalized again
            var i,
                delayedTriggers = [];

            // We first have to update the dom position of the actual currentItem
            // Note: don't do it if the current item is already removed (by a user), or it gets
            // reappended (see #4088)
            if (!this._noFinalSort && this.currentItem.parent().length) {
                this.placeholder.before(this.currentItem);
            }
            this._noFinalSort = null;

            if (this.helper[0] === this.currentItem[0]) {
                for (i in this._storedCSS) {
                    if (this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
                        this._storedCSS[i] = "";
                    }
                }
                this.currentItem.css(this._storedCSS);
                this._removeClass(this.currentItem, "ui-sortable-helper");
            } else {
                this.currentItem.show();
            }

            if (this.fromOutside && !noPropagation) {
                delayedTriggers.push(function(event) {
                    this._trigger("receive", event, this._uiHash(this.fromOutside));
                });
            }
            if ((this.fromOutside ||
                    this.domPosition.prev !==
                    this.currentItem.prev().not(".ui-sortable-helper")[0] ||
                    this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {

                // Trigger update callback if the DOM position has changed
                delayedTriggers.push(function(event) {
                    this._trigger("update", event, this._uiHash());
                });
            }

            // Check if the items Container has Changed and trigger appropriate
            // events.
            if (this !== this.currentContainer) {
                if (!noPropagation) {
                    delayedTriggers.push(function(event) {
                        this._trigger("remove", event, this._uiHash());
                    });
                    delayedTriggers.push((function(c) {
                        return function(event) {
                            c._trigger("receive", event, this._uiHash(this));
                        };
                    }).call(this, this.currentContainer));
                    delayedTriggers.push((function(c) {
                        return function(event) {
                            c._trigger("update", event, this._uiHash(this));
                        };
                    }).call(this, this.currentContainer));
                }
            }

            //Post events to containers
            function delayEvent(type, instance, container) {
                return function(event) {
                    container._trigger(type, event, instance._uiHash(instance));
                };
            }
            for (i = this.containers.length - 1; i >= 0; i--) {
                if (!noPropagation) {
                    delayedTriggers.push(delayEvent("deactivate", this, this.containers[i]));
                }
                if (this.containers[i].containerCache.over) {
                    delayedTriggers.push(delayEvent("out", this, this.containers[i]));
                    this.containers[i].containerCache.over = 0;
                }
            }

            //Do what was originally in plugins
            if (this.storedCursor) {
                this.document.find("body").css("cursor", this.storedCursor);
                this.storedStylesheet.remove();
            }
            if (this._storedOpacity) {
                this.helper.css("opacity", this._storedOpacity);
            }
            if (this._storedZIndex) {
                this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
            }

            this.dragging = false;

            if (!noPropagation) {
                this._trigger("beforeStop", event, this._uiHash());
            }

            //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
            // it unbinds ALL events from the original node!
            this.placeholder[0].parentNode.removeChild(this.placeholder[0]);

            if (!this.cancelHelperRemoval) {
                if (this.helper[0] !== this.currentItem[0]) {
                    this.helper.remove();
                }
                this.helper = null;
            }

            if (!noPropagation) {
                for (i = 0; i < delayedTriggers.length; i++) {

                    // Trigger all delayed events
                    delayedTriggers[i].call(this, event);
                }
                this._trigger("stop", event, this._uiHash());
            }

            this.fromOutside = false;
            return !this.cancelHelperRemoval;

        },

        _trigger: function() {
            if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
                this.cancel();
            }
        },

        _uiHash: function(_inst) {
            var inst = _inst || this;
            return {
                helper: inst.helper,
                placeholder: inst.placeholder || $([]),
                position: inst.position,
                originalPosition: inst.originalPosition,
                offset: inst.positionAbs,
                item: inst.currentItem,
                sender: _inst ? _inst.element : null
            };
        }

    });


    /*!
     * jQuery UI Accordion 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Accordion
    //>>group: Widgets
    // jscs:disable maximumLineLength
    //>>description: Displays collapsible content panels for presenting information in a limited amount of space.
    // jscs:enable maximumLineLength
    //>>docs: http://api.jqueryui.com/accordion/
    //>>demos: http://jqueryui.com/accordion/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/accordion.css
    //>>css.theme: ../../themes/base/theme.css



    var widgetsAccordion = $.widget("ui.accordion", {
        version: "1.12.1",
        options: {
            active: 0,
            animate: {},
            classes: {
                "ui-accordion-header": "ui-corner-top",
                "ui-accordion-header-collapsed": "ui-corner-all",
                "ui-accordion-content": "ui-corner-bottom"
            },
            collapsible: false,
            event: "click",
            header: "> li > :first-child, > :not(li):even",
            heightStyle: "auto",
            icons: {
                activeHeader: "ui-icon-triangle-1-s",
                header: "ui-icon-triangle-1-e"
            },

            // Callbacks
            activate: null,
            beforeActivate: null
        },

        hideProps: {
            borderTopWidth: "hide",
            borderBottomWidth: "hide",
            paddingTop: "hide",
            paddingBottom: "hide",
            height: "hide"
        },

        showProps: {
            borderTopWidth: "show",
            borderBottomWidth: "show",
            paddingTop: "show",
            paddingBottom: "show",
            height: "show"
        },

        _create: function() {
            var options = this.options;

            this.prevShow = this.prevHide = $();
            this._addClass("ui-accordion", "ui-widget ui-helper-reset");
            this.element.attr("role", "tablist");

            // Don't allow collapsible: false and active: false / null
            if (!options.collapsible && (options.active === false || options.active == null)) {
                options.active = 0;
            }

            this._processPanels();

            // handle negative values
            if (options.active < 0) {
                options.active += this.headers.length;
            }
            this._refresh();
        },

        _getCreateEventData: function() {
            return {
                header: this.active,
                panel: !this.active.length ? $() : this.active.next()
            };
        },

        _createIcons: function() {
            var icon, children,
                icons = this.options.icons;

            if (icons) {
                icon = $("<span>");
                this._addClass(icon, "ui-accordion-header-icon", "ui-icon " + icons.header);
                icon.prependTo(this.headers);
                children = this.active.children(".ui-accordion-header-icon");
                this._removeClass(children, icons.header)
                    ._addClass(children, null, icons.activeHeader)
                    ._addClass(this.headers, "ui-accordion-icons");
            }
        },

        _destroyIcons: function() {
            this._removeClass(this.headers, "ui-accordion-icons");
            this.headers.children(".ui-accordion-header-icon").remove();
        },

        _destroy: function() {
            var contents;

            // Clean up main element
            this.element.removeAttr("role");

            // Clean up headers
            this.headers
                .removeAttr("role aria-expanded aria-selected aria-controls tabIndex")
                .removeUniqueId();

            this._destroyIcons();

            // Clean up content panels
            contents = this.headers.next()
                .css("display", "")
                .removeAttr("role aria-hidden aria-labelledby")
                .removeUniqueId();

            if (this.options.heightStyle !== "content") {
                contents.css("height", "");
            }
        },

        _setOption: function(key, value) {
            if (key === "active") {

                // _activate() will handle invalid values and update this.options
                this._activate(value);
                return;
            }

            if (key === "event") {
                if (this.options.event) {
                    this._off(this.headers, this.options.event);
                }
                this._setupEvents(value);
            }

            this._super(key, value);

            // Setting collapsible: false while collapsed; open first panel
            if (key === "collapsible" && !value && this.options.active === false) {
                this._activate(0);
            }

            if (key === "icons") {
                this._destroyIcons();
                if (value) {
                    this._createIcons();
                }
            }
        },

        _setOptionDisabled: function(value) {
            this._super(value);

            this.element.attr("aria-disabled", value);

            // Support: IE8 Only
            // #5332 / #6059 - opacity doesn't cascade to positioned elements in IE
            // so we need to add the disabled class to the headers and panels
            this._toggleClass(null, "ui-state-disabled", !!value);
            this._toggleClass(this.headers.add(this.headers.next()), null, "ui-state-disabled", !!value);
        },

        _keydown: function(event) {
            if (event.altKey || event.ctrlKey) {
                return;
            }

            var keyCode = $.ui.keyCode,
                length = this.headers.length,
                currentIndex = this.headers.index(event.target),
                toFocus = false;

            switch (event.keyCode) {
                case keyCode.RIGHT:
                case keyCode.DOWN:
                    toFocus = this.headers[(currentIndex + 1) % length];
                    break;
                case keyCode.LEFT:
                case keyCode.UP:
                    toFocus = this.headers[(currentIndex - 1 + length) % length];
                    break;
                case keyCode.SPACE:
                case keyCode.ENTER:
                    this._eventHandler(event);
                    break;
                case keyCode.HOME:
                    toFocus = this.headers[0];
                    break;
                case keyCode.END:
                    toFocus = this.headers[length - 1];
                    break;
            }

            if (toFocus) {
                $(event.target).attr("tabIndex", -1);
                $(toFocus).attr("tabIndex", 0);
                $(toFocus).trigger("focus");
                event.preventDefault();
            }
        },

        _panelKeyDown: function(event) {
            if (event.keyCode === $.ui.keyCode.UP && event.ctrlKey) {
                $(event.currentTarget).prev().trigger("focus");
            }
        },

        refresh: function() {
            var options = this.options;
            this._processPanels();

            // Was collapsed or no panel
            if ((options.active === false && options.collapsible === true) ||
                !this.headers.length) {
                options.active = false;
                this.active = $();

                // active false only when collapsible is true
            } else if (options.active === false) {
                this._activate(0);

                // was active, but active panel is gone
            } else if (this.active.length && !$.contains(this.element[0], this.active[0])) {

                // all remaining panel are disabled
                if (this.headers.length === this.headers.find(".ui-state-disabled").length) {
                    options.active = false;
                    this.active = $();

                    // activate previous panel
                } else {
                    this._activate(Math.max(0, options.active - 1));
                }

                // was active, active panel still exists
            } else {

                // make sure active index is correct
                options.active = this.headers.index(this.active);
            }

            this._destroyIcons();

            this._refresh();
        },

        _processPanels: function() {
            var prevHeaders = this.headers,
                prevPanels = this.panels;

            this.headers = this.element.find(this.options.header);
            this._addClass(this.headers, "ui-accordion-header ui-accordion-header-collapsed",
                "ui-state-default");

            this.panels = this.headers.next().filter(":not(.ui-accordion-content-active)").hide();
            this._addClass(this.panels, "ui-accordion-content", "ui-helper-reset ui-widget-content");

            // Avoid memory leaks (#10056)
            if (prevPanels) {
                this._off(prevHeaders.not(this.headers));
                this._off(prevPanels.not(this.panels));
            }
        },

        _refresh: function() {
            var maxHeight,
                options = this.options,
                heightStyle = options.heightStyle,
                parent = this.element.parent();

            this.active = this._findActive(options.active);
            this._addClass(this.active, "ui-accordion-header-active", "ui-state-active")
                ._removeClass(this.active, "ui-accordion-header-collapsed");
            this._addClass(this.active.next(), "ui-accordion-content-active");
            this.active.next().show();

            this.headers
                .attr("role", "tab")
                .each(function() {
                    var header = $(this),
                        headerId = header.uniqueId().attr("id"),
                        panel = header.next(),
                        panelId = panel.uniqueId().attr("id");
                    header.attr("aria-controls", panelId);
                    panel.attr("aria-labelledby", headerId);
                })
                .next()
                .attr("role", "tabpanel");

            this.headers
                .not(this.active)
                .attr({
                    "aria-selected": "false",
                    "aria-expanded": "false",
                    tabIndex: -1
                })
                .next()
                .attr({
                    "aria-hidden": "true"
                })
                .hide();

            // Make sure at least one header is in the tab order
            if (!this.active.length) {
                this.headers.eq(0).attr("tabIndex", 0);
            } else {
                this.active.attr({
                        "aria-selected": "true",
                        "aria-expanded": "true",
                        tabIndex: 0
                    })
                    .next()
                    .attr({
                        "aria-hidden": "false"
                    });
            }

            this._createIcons();

            this._setupEvents(options.event);

            if (heightStyle === "fill") {
                maxHeight = parent.height();
                this.element.siblings(":visible").each(function() {
                    var elem = $(this),
                        position = elem.css("position");

                    if (position === "absolute" || position === "fixed") {
                        return;
                    }
                    maxHeight -= elem.outerHeight(true);
                });

                this.headers.each(function() {
                    maxHeight -= $(this).outerHeight(true);
                });

                this.headers.next()
                    .each(function() {
                        $(this).height(Math.max(0, maxHeight -
                            $(this).innerHeight() + $(this).height()));
                    })
                    .css("overflow", "auto");
            } else if (heightStyle === "auto") {
                maxHeight = 0;
                this.headers.next()
                    .each(function() {
                        var isVisible = $(this).is(":visible");
                        if (!isVisible) {
                            $(this).show();
                        }
                        maxHeight = Math.max(maxHeight, $(this).css("height", "").height());
                        if (!isVisible) {
                            $(this).hide();
                        }
                    })
                    .height(maxHeight);
            }
        },

        _activate: function(index) {
            var active = this._findActive(index)[0];

            // Trying to activate the already active panel
            if (active === this.active[0]) {
                return;
            }

            // Trying to collapse, simulate a click on the currently active header
            active = active || this.active[0];

            this._eventHandler({
                target: active,
                currentTarget: active,
                preventDefault: $.noop
            });
        },

        _findActive: function(selector) {
            return typeof selector === "number" ? this.headers.eq(selector) : $();
        },

        _setupEvents: function(event) {
            var events = {
                keydown: "_keydown"
            };
            if (event) {
                $.each(event.split(" "), function(index, eventName) {
                    events[eventName] = "_eventHandler";
                });
            }

            this._off(this.headers.add(this.headers.next()));
            this._on(this.headers, events);
            this._on(this.headers.next(), { keydown: "_panelKeyDown" });
            this._hoverable(this.headers);
            this._focusable(this.headers);
        },

        _eventHandler: function(event) {
            var activeChildren, clickedChildren,
                options = this.options,
                active = this.active,
                clicked = $(event.currentTarget),
                clickedIsActive = clicked[0] === active[0],
                collapsing = clickedIsActive && options.collapsible,
                toShow = collapsing ? $() : clicked.next(),
                toHide = active.next(),
                eventData = {
                    oldHeader: active,
                    oldPanel: toHide,
                    newHeader: collapsing ? $() : clicked,
                    newPanel: toShow
                };

            event.preventDefault();

            if (

                // click on active header, but not collapsible
                (clickedIsActive && !options.collapsible) ||

                // allow canceling activation
                (this._trigger("beforeActivate", event, eventData) === false)) {
                return;
            }

            options.active = collapsing ? false : this.headers.index(clicked);

            // When the call to ._toggle() comes after the class changes
            // it causes a very odd bug in IE 8 (see #6720)
            this.active = clickedIsActive ? $() : clicked;
            this._toggle(eventData);

            // Switch classes
            // corner classes on the previously active header stay after the animation
            this._removeClass(active, "ui-accordion-header-active", "ui-state-active");
            if (options.icons) {
                activeChildren = active.children(".ui-accordion-header-icon");
                this._removeClass(activeChildren, null, options.icons.activeHeader)
                    ._addClass(activeChildren, null, options.icons.header);
            }

            if (!clickedIsActive) {
                this._removeClass(clicked, "ui-accordion-header-collapsed")
                    ._addClass(clicked, "ui-accordion-header-active", "ui-state-active");
                if (options.icons) {
                    clickedChildren = clicked.children(".ui-accordion-header-icon");
                    this._removeClass(clickedChildren, null, options.icons.header)
                        ._addClass(clickedChildren, null, options.icons.activeHeader);
                }

                this._addClass(clicked.next(), "ui-accordion-content-active");
            }
        },

        _toggle: function(data) {
            var toShow = data.newPanel,
                toHide = this.prevShow.length ? this.prevShow : data.oldPanel;

            // Handle activating a panel during the animation for another activation
            this.prevShow.add(this.prevHide).stop(true, true);
            this.prevShow = toShow;
            this.prevHide = toHide;

            if (this.options.animate) {
                this._animate(toShow, toHide, data);
            } else {
                toHide.hide();
                toShow.show();
                this._toggleComplete(data);
            }

            toHide.attr({
                "aria-hidden": "true"
            });
            toHide.prev().attr({
                "aria-selected": "false",
                "aria-expanded": "false"
            });

            // if we're switching panels, remove the old header from the tab order
            // if we're opening from collapsed state, remove the previous header from the tab order
            // if we're collapsing, then keep the collapsing header in the tab order
            if (toShow.length && toHide.length) {
                toHide.prev().attr({
                    "tabIndex": -1,
                    "aria-expanded": "false"
                });
            } else if (toShow.length) {
                this.headers.filter(function() {
                        return parseInt($(this).attr("tabIndex"), 10) === 0;
                    })
                    .attr("tabIndex", -1);
            }

            toShow
                .attr("aria-hidden", "false")
                .prev()
                .attr({
                    "aria-selected": "true",
                    "aria-expanded": "true",
                    tabIndex: 0
                });
        },

        _animate: function(toShow, toHide, data) {
            var total, easing, duration,
                that = this,
                adjust = 0,
                boxSizing = toShow.css("box-sizing"),
                down = toShow.length &&
                (!toHide.length || (toShow.index() < toHide.index())),
                animate = this.options.animate || {},
                options = down && animate.down || animate,
                complete = function() {
                    that._toggleComplete(data);
                };

            if (typeof options === "number") {
                duration = options;
            }
            if (typeof options === "string") {
                easing = options;
            }

            // fall back from options to animation in case of partial down settings
            easing = easing || options.easing || animate.easing;
            duration = duration || options.duration || animate.duration;

            if (!toHide.length) {
                return toShow.animate(this.showProps, duration, easing, complete);
            }
            if (!toShow.length) {
                return toHide.animate(this.hideProps, duration, easing, complete);
            }

            total = toShow.show().outerHeight();
            toHide.animate(this.hideProps, {
                duration: duration,
                easing: easing,
                step: function(now, fx) {
                    fx.now = Math.round(now);
                }
            });
            toShow
                .hide()
                .animate(this.showProps, {
                    duration: duration,
                    easing: easing,
                    complete: complete,
                    step: function(now, fx) {
                        fx.now = Math.round(now);
                        if (fx.prop !== "height") {
                            if (boxSizing === "content-box") {
                                adjust += fx.now;
                            }
                        } else if (that.options.heightStyle !== "content") {
                            fx.now = Math.round(total - toHide.outerHeight() - adjust);
                            adjust = 0;
                        }
                    }
                });
        },

        _toggleComplete: function(data) {
            var toHide = data.oldPanel,
                prev = toHide.prev();

            this._removeClass(toHide, "ui-accordion-content-active");
            this._removeClass(prev, "ui-accordion-header-active")
                ._addClass(prev, "ui-accordion-header-collapsed");

            // Work around for rendering bug in IE (#5421)
            if (toHide.length) {
                toHide.parent()[0].className = toHide.parent()[0].className;
            }
            this._trigger("activate", null, data);
        }
    });


    /*!
     * jQuery UI Menu 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Menu
    //>>group: Widgets
    //>>description: Creates nestable menus.
    //>>docs: http://api.jqueryui.com/menu/
    //>>demos: http://jqueryui.com/menu/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/menu.css
    //>>css.theme: ../../themes/base/theme.css



    var widgetsMenu = $.widget("ui.menu", {
        version: "1.12.1",
        defaultElement: "<ul>",
        delay: 300,
        options: {
            icons: {
                submenu: "ui-icon-caret-1-e"
            },
            items: "> *",
            menus: "ul",
            position: {
                my: "left top",
                at: "right top"
            },
            role: "menu",

            // Callbacks
            blur: null,
            focus: null,
            select: null
        },

        _create: function() {
            this.activeMenu = this.element;

            // Flag used to prevent firing of the click handler
            // as the event bubbles up through nested menus
            this.mouseHandled = false;
            this.element
                .uniqueId()
                .attr({
                    role: this.options.role,
                    tabIndex: 0
                });

            this._addClass("ui-menu", "ui-widget ui-widget-content");
            this._on({

                // Prevent focus from sticking to links inside menu after clicking
                // them (focus should always stay on UL during navigation).
                "mousedown .ui-menu-item": function(event) {
                    event.preventDefault();
                },
                "click .ui-menu-item": function(event) {
                    var target = $(event.target);
                    var active = $($.ui.safeActiveElement(this.document[0]));
                    if (!this.mouseHandled && target.not(".ui-state-disabled").length) {
                        this.select(event);

                        // Only set the mouseHandled flag if the event will bubble, see #9469.
                        if (!event.isPropagationStopped()) {
                            this.mouseHandled = true;
                        }

                        // Open submenu on click
                        if (target.has(".ui-menu").length) {
                            this.expand(event);
                        } else if (!this.element.is(":focus") &&
                            active.closest(".ui-menu").length) {

                            // Redirect focus to the menu
                            this.element.trigger("focus", [true]);

                            // If the active item is on the top level, let it stay active.
                            // Otherwise, blur the active item since it is no longer visible.
                            if (this.active && this.active.parents(".ui-menu").length === 1) {
                                clearTimeout(this.timer);
                            }
                        }
                    }
                },
                "mouseenter .ui-menu-item": function(event) {

                    // Ignore mouse events while typeahead is active, see #10458.
                    // Prevents focusing the wrong item when typeahead causes a scroll while the mouse
                    // is over an item in the menu
                    if (this.previousFilter) {
                        return;
                    }

                    var actualTarget = $(event.target).closest(".ui-menu-item"),
                        target = $(event.currentTarget);

                    // Ignore bubbled events on parent items, see #11641
                    if (actualTarget[0] !== target[0]) {
                        return;
                    }

                    // Remove ui-state-active class from siblings of the newly focused menu item
                    // to avoid a jump caused by adjacent elements both having a class with a border
                    this._removeClass(target.siblings().children(".ui-state-active"),
                        null, "ui-state-active");
                    this.focus(event, target);
                },
                mouseleave: "collapseAll",
                "mouseleave .ui-menu": "collapseAll",
                focus: function(event, keepActiveItem) {

                    // If there's already an active item, keep it active
                    // If not, activate the first item
                    var item = this.active || this.element.find(this.options.items).eq(0);

                    if (!keepActiveItem) {
                        this.focus(event, item);
                    }
                },
                blur: function(event) {
                    this._delay(function() {
                        var notContained = !$.contains(
                            this.element[0],
                            $.ui.safeActiveElement(this.document[0])
                        );
                        if (notContained) {
                            this.collapseAll(event);
                        }
                    });
                },
                keydown: "_keydown"
            });

            this.refresh();

            // Clicks outside of a menu collapse any open menus
            this._on(this.document, {
                click: function(event) {
                    if (this._closeOnDocumentClick(event)) {
                        this.collapseAll(event);
                    }

                    // Reset the mouseHandled flag
                    this.mouseHandled = false;
                }
            });
        },

        _destroy: function() {
            var items = this.element.find(".ui-menu-item")
                .removeAttr("role aria-disabled"),
                submenus = items.children(".ui-menu-item-wrapper")
                .removeUniqueId()
                .removeAttr("tabIndex role aria-haspopup");

            // Destroy (sub)menus
            this.element
                .removeAttr("aria-activedescendant")
                .find(".ui-menu").addBack()
                .removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled " +
                    "tabIndex")
                .removeUniqueId()
                .show();

            submenus.children().each(function() {
                var elem = $(this);
                if (elem.data("ui-menu-submenu-caret")) {
                    elem.remove();
                }
            });
        },

        _keydown: function(event) {
            var match, prev, character, skip,
                preventDefault = true;

            switch (event.keyCode) {
                case $.ui.keyCode.PAGE_UP:
                    this.previousPage(event);
                    break;
                case $.ui.keyCode.PAGE_DOWN:
                    this.nextPage(event);
                    break;
                case $.ui.keyCode.HOME:
                    this._move("first", "first", event);
                    break;
                case $.ui.keyCode.END:
                    this._move("last", "last", event);
                    break;
                case $.ui.keyCode.UP:
                    this.previous(event);
                    break;
                case $.ui.keyCode.DOWN:
                    this.next(event);
                    break;
                case $.ui.keyCode.LEFT:
                    this.collapse(event);
                    break;
                case $.ui.keyCode.RIGHT:
                    if (this.active && !this.active.is(".ui-state-disabled")) {
                        this.expand(event);
                    }
                    break;
                case $.ui.keyCode.ENTER:
                case $.ui.keyCode.SPACE:
                    this._activate(event);
                    break;
                case $.ui.keyCode.ESCAPE:
                    this.collapse(event);
                    break;
                default:
                    preventDefault = false;
                    prev = this.previousFilter || "";
                    skip = false;

                    // Support number pad values
                    character = event.keyCode >= 96 && event.keyCode <= 105 ?
                        (event.keyCode - 96).toString() : String.fromCharCode(event.keyCode);

                    clearTimeout(this.filterTimer);

                    if (character === prev) {
                        skip = true;
                    } else {
                        character = prev + character;
                    }

                    match = this._filterMenuItems(character);
                    match = skip && match.index(this.active.next()) !== -1 ?
                        this.active.nextAll(".ui-menu-item") :
                        match;

                    // If no matches on the current filter, reset to the last character pressed
                    // to move down the menu to the first item that starts with that character
                    if (!match.length) {
                        character = String.fromCharCode(event.keyCode);
                        match = this._filterMenuItems(character);
                    }

                    if (match.length) {
                        this.focus(event, match);
                        this.previousFilter = character;
                        this.filterTimer = this._delay(function() {
                            delete this.previousFilter;
                        }, 1000);
                    } else {
                        delete this.previousFilter;
                    }
            }

            if (preventDefault) {
                event.preventDefault();
            }
        },

        _activate: function(event) {
            if (this.active && !this.active.is(".ui-state-disabled")) {
                if (this.active.children("[aria-haspopup='true']").length) {
                    this.expand(event);
                } else {
                    this.select(event);
                }
            }
        },

        refresh: function() {
            var menus, items, newSubmenus, newItems, newWrappers,
                that = this,
                icon = this.options.icons.submenu,
                submenus = this.element.find(this.options.menus);

            this._toggleClass("ui-menu-icons", null, !!this.element.find(".ui-icon").length);

            // Initialize nested menus
            newSubmenus = submenus.filter(":not(.ui-menu)")
                .hide()
                .attr({
                    role: this.options.role,
                    "aria-hidden": "true",
                    "aria-expanded": "false"
                })
                .each(function() {
                    var menu = $(this),
                        item = menu.prev(),
                        submenuCaret = $("<span>").data("ui-menu-submenu-caret", true);

                    that._addClass(submenuCaret, "ui-menu-icon", "ui-icon " + icon);
                    item
                        .attr("aria-haspopup", "true")
                        .prepend(submenuCaret);
                    menu.attr("aria-labelledby", item.attr("id"));
                });

            this._addClass(newSubmenus, "ui-menu", "ui-widget ui-widget-content ui-front");

            menus = submenus.add(this.element);
            items = menus.find(this.options.items);

            // Initialize menu-items containing spaces and/or dashes only as dividers
            items.not(".ui-menu-item").each(function() {
                var item = $(this);
                if (that._isDivider(item)) {
                    that._addClass(item, "ui-menu-divider", "ui-widget-content");
                }
            });

            // Don't refresh list items that are already adapted
            newItems = items.not(".ui-menu-item, .ui-menu-divider");
            newWrappers = newItems.children()
                .not(".ui-menu")
                .uniqueId()
                .attr({
                    tabIndex: -1,
                    role: this._itemRole()
                });
            this._addClass(newItems, "ui-menu-item")
                ._addClass(newWrappers, "ui-menu-item-wrapper");

            // Add aria-disabled attribute to any disabled menu item
            items.filter(".ui-state-disabled").attr("aria-disabled", "true");

            // If the active item has been removed, blur the menu
            if (this.active && !$.contains(this.element[0], this.active[0])) {
                this.blur();
            }
        },

        _itemRole: function() {
            return {
                menu: "menuitem",
                listbox: "option"
            }[this.options.role];
        },

        _setOption: function(key, value) {
            if (key === "icons") {
                var icons = this.element.find(".ui-menu-icon");
                this._removeClass(icons, null, this.options.icons.submenu)
                    ._addClass(icons, null, value.submenu);
            }
            this._super(key, value);
        },

        _setOptionDisabled: function(value) {
            this._super(value);

            this.element.attr("aria-disabled", String(value));
            this._toggleClass(null, "ui-state-disabled", !!value);
        },

        focus: function(event, item) {
            var nested, focused, activeParent;
            this.blur(event, event && event.type === "focus");

            this._scrollIntoView(item);

            this.active = item.first();

            focused = this.active.children(".ui-menu-item-wrapper");
            this._addClass(focused, null, "ui-state-active");

            // Only update aria-activedescendant if there's a role
            // otherwise we assume focus is managed elsewhere
            if (this.options.role) {
                this.element.attr("aria-activedescendant", focused.attr("id"));
            }

            // Highlight active parent menu item, if any
            activeParent = this.active
                .parent()
                .closest(".ui-menu-item")
                .children(".ui-menu-item-wrapper");
            this._addClass(activeParent, null, "ui-state-active");

            if (event && event.type === "keydown") {
                this._close();
            } else {
                this.timer = this._delay(function() {
                    this._close();
                }, this.delay);
            }

            nested = item.children(".ui-menu");
            if (nested.length && event && (/^mouse/.test(event.type))) {
                this._startOpening(nested);
            }
            this.activeMenu = item.parent();

            this._trigger("focus", event, { item: item });
        },

        _scrollIntoView: function(item) {
            var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
            if (this._hasScroll()) {
                borderTop = parseFloat($.css(this.activeMenu[0], "borderTopWidth")) || 0;
                paddingTop = parseFloat($.css(this.activeMenu[0], "paddingTop")) || 0;
                offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
                scroll = this.activeMenu.scrollTop();
                elementHeight = this.activeMenu.height();
                itemHeight = item.outerHeight();

                if (offset < 0) {
                    this.activeMenu.scrollTop(scroll + offset);
                } else if (offset + itemHeight > elementHeight) {
                    this.activeMenu.scrollTop(scroll + offset - elementHeight + itemHeight);
                }
            }
        },

        blur: function(event, fromFocus) {
            if (!fromFocus) {
                clearTimeout(this.timer);
            }

            if (!this.active) {
                return;
            }

            this._removeClass(this.active.children(".ui-menu-item-wrapper"),
                null, "ui-state-active");

            this._trigger("blur", event, { item: this.active });
            this.active = null;
        },

        _startOpening: function(submenu) {
            clearTimeout(this.timer);

            // Don't open if already open fixes a Firefox bug that caused a .5 pixel
            // shift in the submenu position when mousing over the caret icon
            if (submenu.attr("aria-hidden") !== "true") {
                return;
            }

            this.timer = this._delay(function() {
                this._close();
                this._open(submenu);
            }, this.delay);
        },

        _open: function(submenu) {
            var position = $.extend({
                of: this.active
            }, this.options.position);

            clearTimeout(this.timer);
            this.element.find(".ui-menu").not(submenu.parents(".ui-menu"))
                .hide()
                .attr("aria-hidden", "true");

            submenu
                .show()
                .removeAttr("aria-hidden")
                .attr("aria-expanded", "true")
                .position(position);
        },

        collapseAll: function(event, all) {
            clearTimeout(this.timer);
            this.timer = this._delay(function() {

                // If we were passed an event, look for the submenu that contains the event
                var currentMenu = all ? this.element :
                    $(event && event.target).closest(this.element.find(".ui-menu"));

                // If we found no valid submenu ancestor, use the main menu to close all
                // sub menus anyway
                if (!currentMenu.length) {
                    currentMenu = this.element;
                }

                this._close(currentMenu);

                this.blur(event);

                // Work around active item staying active after menu is blurred
                this._removeClass(currentMenu.find(".ui-state-active"), null, "ui-state-active");

                this.activeMenu = currentMenu;
            }, this.delay);
        },

        // With no arguments, closes the currently active menu - if nothing is active
        // it closes all menus.  If passed an argument, it will search for menus BELOW
        _close: function(startMenu) {
            if (!startMenu) {
                startMenu = this.active ? this.active.parent() : this.element;
            }

            startMenu.find(".ui-menu")
                .hide()
                .attr("aria-hidden", "true")
                .attr("aria-expanded", "false");
        },

        _closeOnDocumentClick: function(event) {
            return !$(event.target).closest(".ui-menu").length;
        },

        _isDivider: function(item) {

            // Match hyphen, em dash, en dash
            return !/[^\-\u2014\u2013\s]/.test(item.text());
        },

        collapse: function(event) {
            var newItem = this.active &&
                this.active.parent().closest(".ui-menu-item", this.element);
            if (newItem && newItem.length) {
                this._close();
                this.focus(event, newItem);
            }
        },

        expand: function(event) {
            var newItem = this.active &&
                this.active
                .children(".ui-menu ")
                .find(this.options.items)
                .first();

            if (newItem && newItem.length) {
                this._open(newItem.parent());

                // Delay so Firefox will not hide activedescendant change in expanding submenu from AT
                this._delay(function() {
                    this.focus(event, newItem);
                });
            }
        },

        next: function(event) {
            this._move("next", "first", event);
        },

        previous: function(event) {
            this._move("prev", "last", event);
        },

        isFirstItem: function() {
            return this.active && !this.active.prevAll(".ui-menu-item").length;
        },

        isLastItem: function() {
            return this.active && !this.active.nextAll(".ui-menu-item").length;
        },

        _move: function(direction, filter, event) {
            var next;
            if (this.active) {
                if (direction === "first" || direction === "last") {
                    next = this.active[direction === "first" ? "prevAll" : "nextAll"](".ui-menu-item")
                        .eq(-1);
                } else {
                    next = this.active[direction + "All"](".ui-menu-item")
                        .eq(0);
                }
            }
            if (!next || !next.length || !this.active) {
                next = this.activeMenu.find(this.options.items)[filter]();
            }

            this.focus(event, next);
        },

        nextPage: function(event) {
            var item, base, height;

            if (!this.active) {
                this.next(event);
                return;
            }
            if (this.isLastItem()) {
                return;
            }
            if (this._hasScroll()) {
                base = this.active.offset().top;
                height = this.element.height();
                this.active.nextAll(".ui-menu-item").each(function() {
                    item = $(this);
                    return item.offset().top - base - height < 0;
                });

                this.focus(event, item);
            } else {
                this.focus(event, this.activeMenu.find(this.options.items)[!this.active ? "first" : "last"]());
            }
        },

        previousPage: function(event) {
            var item, base, height;
            if (!this.active) {
                this.next(event);
                return;
            }
            if (this.isFirstItem()) {
                return;
            }
            if (this._hasScroll()) {
                base = this.active.offset().top;
                height = this.element.height();
                this.active.prevAll(".ui-menu-item").each(function() {
                    item = $(this);
                    return item.offset().top - base + height > 0;
                });

                this.focus(event, item);
            } else {
                this.focus(event, this.activeMenu.find(this.options.items).first());
            }
        },

        _hasScroll: function() {
            return this.element.outerHeight() < this.element.prop("scrollHeight");
        },

        select: function(event) {

            // TODO: It should never be possible to not have an active item at this
            // point, but the tests don't trigger mouseenter before click.
            this.active = this.active || $(event.target).closest(".ui-menu-item");
            var ui = { item: this.active };
            if (!this.active.has(".ui-menu").length) {
                this.collapseAll(event, true);
            }
            this._trigger("select", event, ui);
        },

        _filterMenuItems: function(character) {
            var escapedCharacter = character.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"),
                regex = new RegExp("^" + escapedCharacter, "i");

            return this.activeMenu
                .find(this.options.items)

            // Only match on items, not dividers or other content (#10571)
            .filter(".ui-menu-item")
                .filter(function() {
                    return regex.test(
                        $.trim($(this).children(".ui-menu-item-wrapper").text()));
                });
        }
    });


    /*!
     * jQuery UI Autocomplete 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Autocomplete
    //>>group: Widgets
    //>>description: Lists suggested words as the user is typing.
    //>>docs: http://api.jqueryui.com/autocomplete/
    //>>demos: http://jqueryui.com/autocomplete/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/autocomplete.css
    //>>css.theme: ../../themes/base/theme.css



    $.widget("ui.autocomplete", {
        version: "1.12.1",
        defaultElement: "<input>",
        options: {
            appendTo: null,
            autoFocus: false,
            delay: 300,
            minLength: 1,
            position: {
                my: "left top",
                at: "left bottom",
                collision: "none"
            },
            source: null,

            // Callbacks
            change: null,
            close: null,
            focus: null,
            open: null,
            response: null,
            search: null,
            select: null
        },

        requestIndex: 0,
        pending: 0,

        _create: function() {

            // Some browsers only repeat keydown events, not keypress events,
            // so we use the suppressKeyPress flag to determine if we've already
            // handled the keydown event. #7269
            // Unfortunately the code for & in keypress is the same as the up arrow,
            // so we use the suppressKeyPressRepeat flag to avoid handling keypress
            // events when we know the keydown event was used to modify the
            // search term. #7799
            var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
                nodeName = this.element[0].nodeName.toLowerCase(),
                isTextarea = nodeName === "textarea",
                isInput = nodeName === "input";

            // Textareas are always multi-line
            // Inputs are always single-line, even if inside a contentEditable element
            // IE also treats inputs as contentEditable
            // All other element types are determined by whether or not they're contentEditable
            this.isMultiLine = isTextarea || !isInput && this._isContentEditable(this.element);

            this.valueMethod = this.element[isTextarea || isInput ? "val" : "text"];
            this.isNewMenu = true;

            this._addClass("ui-autocomplete-input");
            this.element.attr("autocomplete", "off");

            this._on(this.element, {
                keydown: function(event) {
                    if (this.element.prop("readOnly")) {
                        suppressKeyPress = true;
                        suppressInput = true;
                        suppressKeyPressRepeat = true;
                        return;
                    }

                    suppressKeyPress = false;
                    suppressInput = false;
                    suppressKeyPressRepeat = false;
                    var keyCode = $.ui.keyCode;
                    switch (event.keyCode) {
                        case keyCode.PAGE_UP:
                            suppressKeyPress = true;
                            this._move("previousPage", event);
                            break;
                        case keyCode.PAGE_DOWN:
                            suppressKeyPress = true;
                            this._move("nextPage", event);
                            break;
                        case keyCode.UP:
                            suppressKeyPress = true;
                            this._keyEvent("previous", event);
                            break;
                        case keyCode.DOWN:
                            suppressKeyPress = true;
                            this._keyEvent("next", event);
                            break;
                        case keyCode.ENTER:

                            // when menu is open and has focus
                            if (this.menu.active) {

                                // #6055 - Opera still allows the keypress to occur
                                // which causes forms to submit
                                suppressKeyPress = true;
                                event.preventDefault();
                                this.menu.select(event);
                            }
                            break;
                        case keyCode.TAB:
                            if (this.menu.active) {
                                this.menu.select(event);
                            }
                            break;
                        case keyCode.ESCAPE:
                            if (this.menu.element.is(":visible")) {
                                if (!this.isMultiLine) {
                                    this._value(this.term);
                                }
                                this.close(event);

                                // Different browsers have different default behavior for escape
                                // Single press can mean undo or clear
                                // Double press in IE means clear the whole form
                                event.preventDefault();
                            }
                            break;
                        default:
                            suppressKeyPressRepeat = true;

                            // search timeout should be triggered before the input value is changed
                            this._searchTimeout(event);
                            break;
                    }
                },
                keypress: function(event) {
                    if (suppressKeyPress) {
                        suppressKeyPress = false;
                        if (!this.isMultiLine || this.menu.element.is(":visible")) {
                            event.preventDefault();
                        }
                        return;
                    }
                    if (suppressKeyPressRepeat) {
                        return;
                    }

                    // Replicate some key handlers to allow them to repeat in Firefox and Opera
                    var keyCode = $.ui.keyCode;
                    switch (event.keyCode) {
                        case keyCode.PAGE_UP:
                            this._move("previousPage", event);
                            break;
                        case keyCode.PAGE_DOWN:
                            this._move("nextPage", event);
                            break;
                        case keyCode.UP:
                            this._keyEvent("previous", event);
                            break;
                        case keyCode.DOWN:
                            this._keyEvent("next", event);
                            break;
                    }
                },
                input: function(event) {
                    if (suppressInput) {
                        suppressInput = false;
                        event.preventDefault();
                        return;
                    }
                    this._searchTimeout(event);
                },
                focus: function() {
                    this.selectedItem = null;
                    this.previous = this._value();
                },
                blur: function(event) {
                    if (this.cancelBlur) {
                        delete this.cancelBlur;
                        return;
                    }

                    clearTimeout(this.searching);
                    this.close(event);
                    this._change(event);
                }
            });

            this._initSource();
            this.menu = $("<ul>")
                .appendTo(this._appendTo())
                .menu({

                    // disable ARIA support, the live region takes care of that
                    role: null
                })
                .hide()
                .menu("instance");

            this._addClass(this.menu.element, "ui-autocomplete", "ui-front");
            this._on(this.menu.element, {
                mousedown: function(event) {

                    // prevent moving focus out of the text field
                    event.preventDefault();

                    // IE doesn't prevent moving focus even with event.preventDefault()
                    // so we set a flag to know when we should ignore the blur event
                    this.cancelBlur = true;
                    this._delay(function() {
                        delete this.cancelBlur;

                        // Support: IE 8 only
                        // Right clicking a menu item or selecting text from the menu items will
                        // result in focus moving out of the input. However, we've already received
                        // and ignored the blur event because of the cancelBlur flag set above. So
                        // we restore focus to ensure that the menu closes properly based on the user's
                        // next actions.
                        if (this.element[0] !== $.ui.safeActiveElement(this.document[0])) {
                            this.element.trigger("focus");
                        }
                    });
                },
                menufocus: function(event, ui) {
                    var label, item;

                    // support: Firefox
                    // Prevent accidental activation of menu items in Firefox (#7024 #9118)
                    if (this.isNewMenu) {
                        this.isNewMenu = false;
                        if (event.originalEvent && /^mouse/.test(event.originalEvent.type)) {
                            this.menu.blur();

                            this.document.one("mousemove", function() {
                                $(event.target).trigger(event.originalEvent);
                            });

                            return;
                        }
                    }

                    item = ui.item.data("ui-autocomplete-item");
                    if (false !== this._trigger("focus", event, { item: item })) {

                        // use value to match what will end up in the input, if it was a key event
                        if (event.originalEvent && /^key/.test(event.originalEvent.type)) {
                            this._value(item.value);
                        }
                    }

                    // Announce the value in the liveRegion
                    label = ui.item.attr("aria-label") || item.value;
                    if (label && $.trim(label).length) {
                        this.liveRegion.children().hide();
                        $("<div>").text(label).appendTo(this.liveRegion);
                    }
                },
                menuselect: function(event, ui) {
                    var item = ui.item.data("ui-autocomplete-item"),
                        previous = this.previous;

                    // Only trigger when focus was lost (click on menu)
                    if (this.element[0] !== $.ui.safeActiveElement(this.document[0])) {
                        this.element.trigger("focus");
                        this.previous = previous;

                        // #6109 - IE triggers two focus events and the second
                        // is asynchronous, so we need to reset the previous
                        // term synchronously and asynchronously :-(
                        this._delay(function() {
                            this.previous = previous;
                            this.selectedItem = item;
                        });
                    }

                    if (false !== this._trigger("select", event, { item: item })) {
                        this._value(item.value);
                    }

                    // reset the term after the select event
                    // this allows custom select handling to work properly
                    this.term = this._value();

                    this.close(event);
                    this.selectedItem = item;
                }
            });

            this.liveRegion = $("<div>", {
                    role: "status",
                    "aria-live": "assertive",
                    "aria-relevant": "additions"
                })
                .appendTo(this.document[0].body);

            this._addClass(this.liveRegion, null, "ui-helper-hidden-accessible");

            // Turning off autocomplete prevents the browser from remembering the
            // value when navigating through history, so we re-enable autocomplete
            // if the page is unloaded before the widget is destroyed. #7790
            this._on(this.window, {
                beforeunload: function() {
                    this.element.removeAttr("autocomplete");
                }
            });
        },

        _destroy: function() {
            clearTimeout(this.searching);
            this.element.removeAttr("autocomplete");
            this.menu.element.remove();
            this.liveRegion.remove();
        },

        _setOption: function(key, value) {
            this._super(key, value);
            if (key === "source") {
                this._initSource();
            }
            if (key === "appendTo") {
                this.menu.element.appendTo(this._appendTo());
            }
            if (key === "disabled" && value && this.xhr) {
                this.xhr.abort();
            }
        },

        _isEventTargetInWidget: function(event) {
            var menuElement = this.menu.element[0];

            return event.target === this.element[0] ||
                event.target === menuElement ||
                $.contains(menuElement, event.target);
        },

        _closeOnClickOutside: function(event) {
            if (!this._isEventTargetInWidget(event)) {
                this.close();
            }
        },

        _appendTo: function() {
            var element = this.options.appendTo;

            if (element) {
                element = element.jquery || element.nodeType ?
                    $(element) :
                    this.document.find(element).eq(0);
            }

            if (!element || !element[0]) {
                element = this.element.closest(".ui-front, dialog");
            }

            if (!element.length) {
                element = this.document[0].body;
            }

            return element;
        },

        _initSource: function() {
            var array, url,
                that = this;
            if ($.isArray(this.options.source)) {
                array = this.options.source;
                this.source = function(request, response) {
                    response($.ui.autocomplete.filter(array, request.term));
                };
            } else if (typeof this.options.source === "string") {
                url = this.options.source;
                this.source = function(request, response) {
                    if (that.xhr) {
                        that.xhr.abort();
                    }
                    that.xhr = $.ajax({
                        url: url,
                        data: request,
                        dataType: "json",
                        success: function(data) {
                            response(data);
                        },
                        error: function() {
                            response([]);
                        }
                    });
                };
            } else {
                this.source = this.options.source;
            }
        },

        _searchTimeout: function(event) {
            clearTimeout(this.searching);
            this.searching = this._delay(function() {

                // Search if the value has changed, or if the user retypes the same value (see #7434)
                var equalValues = this.term === this._value(),
                    menuVisible = this.menu.element.is(":visible"),
                    modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;

                if (!equalValues || (equalValues && !menuVisible && !modifierKey)) {
                    this.selectedItem = null;
                    this.search(null, event);
                }
            }, this.options.delay);
        },

        search: function(value, event) {
            value = value != null ? value : this._value();

            // Always save the actual value, not the one passed as an argument
            this.term = this._value();

            if (value.length < this.options.minLength) {
                return this.close(event);
            }

            if (this._trigger("search", event) === false) {
                return;
            }

            return this._search(value);
        },

        _search: function(value) {
            this.pending++;
            this._addClass("ui-autocomplete-loading");
            this.cancelSearch = false;

            this.source({ term: value }, this._response());
        },

        _response: function() {
            var index = ++this.requestIndex;

            return $.proxy(function(content) {
                if (index === this.requestIndex) {
                    this.__response(content);
                }

                this.pending--;
                if (!this.pending) {
                    this._removeClass("ui-autocomplete-loading");
                }
            }, this);
        },

        __response: function(content) {
            if (content) {
                content = this._normalize(content);
            }
            this._trigger("response", null, { content: content });
            if (!this.options.disabled && content && content.length && !this.cancelSearch) {
                this._suggest(content);
                this._trigger("open");
            } else {

                // use ._close() instead of .close() so we don't cancel future searches
                this._close();
            }
        },

        close: function(event) {
            this.cancelSearch = true;
            this._close(event);
        },

        _close: function(event) {

            // Remove the handler that closes the menu on outside clicks
            this._off(this.document, "mousedown");

            if (this.menu.element.is(":visible")) {
                this.menu.element.hide();
                this.menu.blur();
                this.isNewMenu = true;
                this._trigger("close", event);
            }
        },

        _change: function(event) {
            if (this.previous !== this._value()) {
                this._trigger("change", event, { item: this.selectedItem });
            }
        },

        _normalize: function(items) {

            // assume all items have the right format when the first item is complete
            if (items.length && items[0].label && items[0].value) {
                return items;
            }
            return $.map(items, function(item) {
                if (typeof item === "string") {
                    return {
                        label: item,
                        value: item
                    };
                }
                return $.extend({}, item, {
                    label: item.label || item.value,
                    value: item.value || item.label
                });
            });
        },

        _suggest: function(items) {
            var ul = this.menu.element.empty();
            this._renderMenu(ul, items);
            this.isNewMenu = true;
            this.menu.refresh();

            // Size and position menu
            ul.show();
            this._resizeMenu();
            ul.position($.extend({
                of: this.element
            }, this.options.position));

            if (this.options.autoFocus) {
                this.menu.next();
            }

            // Listen for interactions outside of the widget (#6642)
            this._on(this.document, {
                mousedown: "_closeOnClickOutside"
            });
        },

        _resizeMenu: function() {
            var ul = this.menu.element;
            ul.outerWidth(Math.max(

                // Firefox wraps long text (possibly a rounding bug)
                // so we add 1px to avoid the wrapping (#7513)
                ul.width("").outerWidth() + 1,
                this.element.outerWidth()
            ));
        },

        _renderMenu: function(ul, items) {
            var that = this;
            $.each(items, function(index, item) {
                that._renderItemData(ul, item);
            });
        },

        _renderItemData: function(ul, item) {
            return this._renderItem(ul, item).data("ui-autocomplete-item", item);
        },

        _renderItem: function(ul, item) {
            return $("<li>")
                .append($("<div>").text(item.label))
                .appendTo(ul);
        },

        _move: function(direction, event) {
            if (!this.menu.element.is(":visible")) {
                this.search(null, event);
                return;
            }
            if (this.menu.isFirstItem() && /^previous/.test(direction) ||
                this.menu.isLastItem() && /^next/.test(direction)) {

                if (!this.isMultiLine) {
                    this._value(this.term);
                }

                this.menu.blur();
                return;
            }
            this.menu[direction](event);
        },

        widget: function() {
            return this.menu.element;
        },

        _value: function() {
            return this.valueMethod.apply(this.element, arguments);
        },

        _keyEvent: function(keyEvent, event) {
            if (!this.isMultiLine || this.menu.element.is(":visible")) {
                this._move(keyEvent, event);

                // Prevents moving cursor to beginning/end of the text field in some browsers
                event.preventDefault();
            }
        },

        // Support: Chrome <=50
        // We should be able to just use this.element.prop( "isContentEditable" )
        // but hidden elements always report false in Chrome.
        // https://code.google.com/p/chromium/issues/detail?id=313082
        _isContentEditable: function(element) {
            if (!element.length) {
                return false;
            }

            var editable = element.prop("contentEditable");

            if (editable === "inherit") {
                return this._isContentEditable(element.parent());
            }

            return editable === "true";
        }
    });

    $.extend($.ui.autocomplete, {
        escapeRegex: function(value) {
            return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
        },
        filter: function(array, term) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
            return $.grep(array, function(value) {
                return matcher.test(value.label || value.value || value);
            });
        }
    });

    // Live region extension, adding a `messages` option
    // NOTE: This is an experimental API. We are still investigating
    // a full solution for string manipulation and internationalization.
    $.widget("ui.autocomplete", $.ui.autocomplete, {
        options: {
            messages: {
                noResults: "No search results.",
                results: function(amount) {
                    return amount + (amount > 1 ? " results are" : " result is") +
                        " available, use up and down arrow keys to navigate.";
                }
            }
        },

        __response: function(content) {
            var message;
            this._superApply(arguments);
            if (this.options.disabled || this.cancelSearch) {
                return;
            }
            if (content && content.length) {
                message = this.options.messages.results(content.length);
            } else {
                message = this.options.messages.noResults;
            }
            this.liveRegion.children().hide();
            $("<div>").text(message).appendTo(this.liveRegion);
        }
    });

    var widgetsAutocomplete = $.ui.autocomplete;


    /*!
     * jQuery UI Controlgroup 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Controlgroup
    //>>group: Widgets
    //>>description: Visually groups form control widgets
    //>>docs: http://api.jqueryui.com/controlgroup/
    //>>demos: http://jqueryui.com/controlgroup/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/controlgroup.css
    //>>css.theme: ../../themes/base/theme.css


    var controlgroupCornerRegex = /ui-corner-([a-z]){2,6}/g;

    var widgetsControlgroup = $.widget("ui.controlgroup", {
        version: "1.12.1",
        defaultElement: "<div>",
        options: {
            direction: "horizontal",
            disabled: null,
            onlyVisible: true,
            items: {
                "button": "input[type=button], input[type=submit], input[type=reset], button, a",
                "controlgroupLabel": ".ui-controlgroup-label",
                "checkboxradio": "input[type='checkbox'], input[type='radio']",
                "selectmenu": "select",
                "spinner": ".ui-spinner-input"
            }
        },

        _create: function() {
            this._enhance();
        },

        // To support the enhanced option in jQuery Mobile, we isolate DOM manipulation
        _enhance: function() {
            this.element.attr("role", "toolbar");
            this.refresh();
        },

        _destroy: function() {
            this._callChildMethod("destroy");
            this.childWidgets.removeData("ui-controlgroup-data");
            this.element.removeAttr("role");
            if (this.options.items.controlgroupLabel) {
                this.element
                    .find(this.options.items.controlgroupLabel)
                    .find(".ui-controlgroup-label-contents")
                    .contents().unwrap();
            }
        },

        _initWidgets: function() {
            var that = this,
                childWidgets = [];

            // First we iterate over each of the items options
            $.each(this.options.items, function(widget, selector) {
                var labels;
                var options = {};

                // Make sure the widget has a selector set
                if (!selector) {
                    return;
                }

                if (widget === "controlgroupLabel") {
                    labels = that.element.find(selector);
                    labels.each(function() {
                        var element = $(this);

                        if (element.children(".ui-controlgroup-label-contents").length) {
                            return;
                        }
                        element.contents()
                            .wrapAll("<span class='ui-controlgroup-label-contents'></span>");
                    });
                    that._addClass(labels, null, "ui-widget ui-widget-content ui-state-default");
                    childWidgets = childWidgets.concat(labels.get());
                    return;
                }

                // Make sure the widget actually exists
                if (!$.fn[widget]) {
                    return;
                }

                // We assume everything is in the middle to start because we can't determine
                // first / last elements until all enhancments are done.
                if (that["_" + widget + "Options"]) {
                    options = that["_" + widget + "Options"]("middle");
                } else {
                    options = { classes: {} };
                }

                // Find instances of this widget inside controlgroup and init them
                that.element
                    .find(selector)
                    .each(function() {
                        var element = $(this);
                        var instance = element[widget]("instance");

                        // We need to clone the default options for this type of widget to avoid
                        // polluting the variable options which has a wider scope than a single widget.
                        var instanceOptions = $.widget.extend({}, options);

                        // If the button is the child of a spinner ignore it
                        // TODO: Find a more generic solution
                        if (widget === "button" && element.parent(".ui-spinner").length) {
                            return;
                        }

                        // Create the widget if it doesn't exist
                        if (!instance) {
                            instance = element[widget]()[widget]("instance");
                        }
                        if (instance) {
                            instanceOptions.classes =
                                that._resolveClassesValues(instanceOptions.classes, instance);
                        }
                        element[widget](instanceOptions);

                        // Store an instance of the controlgroup to be able to reference
                        // from the outermost element for changing options and refresh
                        var widgetElement = element[widget]("widget");
                        $.data(widgetElement[0], "ui-controlgroup-data",
                            instance ? instance : element[widget]("instance"));

                        childWidgets.push(widgetElement[0]);
                    });
            });

            this.childWidgets = $($.unique(childWidgets));
            this._addClass(this.childWidgets, "ui-controlgroup-item");
        },

        _callChildMethod: function(method) {
            this.childWidgets.each(function() {
                var element = $(this),
                    data = element.data("ui-controlgroup-data");
                if (data && data[method]) {
                    data[method]();
                }
            });
        },

        _updateCornerClass: function(element, position) {
            var remove = "ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all";
            var add = this._buildSimpleOptions(position, "label").classes.label;

            this._removeClass(element, null, remove);
            this._addClass(element, null, add);
        },

        _buildSimpleOptions: function(position, key) {
            var direction = this.options.direction === "vertical";
            var result = {
                classes: {}
            };
            result.classes[key] = {
                "middle": "",
                "first": "ui-corner-" + (direction ? "top" : "left"),
                "last": "ui-corner-" + (direction ? "bottom" : "right"),
                "only": "ui-corner-all"
            }[position];

            return result;
        },

        _spinnerOptions: function(position) {
            var options = this._buildSimpleOptions(position, "ui-spinner");

            options.classes["ui-spinner-up"] = "";
            options.classes["ui-spinner-down"] = "";

            return options;
        },

        _buttonOptions: function(position) {
            return this._buildSimpleOptions(position, "ui-button");
        },

        _checkboxradioOptions: function(position) {
            return this._buildSimpleOptions(position, "ui-checkboxradio-label");
        },

        _selectmenuOptions: function(position) {
            var direction = this.options.direction === "vertical";
            return {
                width: direction ? "auto" : false,
                classes: {
                    middle: {
                        "ui-selectmenu-button-open": "",
                        "ui-selectmenu-button-closed": ""
                    },
                    first: {
                        "ui-selectmenu-button-open": "ui-corner-" + (direction ? "top" : "tl"),
                        "ui-selectmenu-button-closed": "ui-corner-" + (direction ? "top" : "left")
                    },
                    last: {
                        "ui-selectmenu-button-open": direction ? "" : "ui-corner-tr",
                        "ui-selectmenu-button-closed": "ui-corner-" + (direction ? "bottom" : "right")
                    },
                    only: {
                        "ui-selectmenu-button-open": "ui-corner-top",
                        "ui-selectmenu-button-closed": "ui-corner-all"
                    }

                }[position]
            };
        },

        _resolveClassesValues: function(classes, instance) {
            var result = {};
            $.each(classes, function(key) {
                var current = instance.options.classes[key] || "";
                current = $.trim(current.replace(controlgroupCornerRegex, ""));
                result[key] = (current + " " + classes[key]).replace(/\s+/g, " ");
            });
            return result;
        },

        _setOption: function(key, value) {
            if (key === "direction") {
                this._removeClass("ui-controlgroup-" + this.options.direction);
            }

            this._super(key, value);
            if (key === "disabled") {
                this._callChildMethod(value ? "disable" : "enable");
                return;
            }

            this.refresh();
        },

        refresh: function() {
            var children,
                that = this;

            this._addClass("ui-controlgroup ui-controlgroup-" + this.options.direction);

            if (this.options.direction === "horizontal") {
                this._addClass(null, "ui-helper-clearfix");
            }
            this._initWidgets();

            children = this.childWidgets;

            // We filter here because we need to track all childWidgets not just the visible ones
            if (this.options.onlyVisible) {
                children = children.filter(":visible");
            }

            if (children.length) {

                // We do this last because we need to make sure all enhancment is done
                // before determining first and last
                $.each(["first", "last"], function(index, value) {
                    var instance = children[value]().data("ui-controlgroup-data");

                    if (instance && that["_" + instance.widgetName + "Options"]) {
                        var options = that["_" + instance.widgetName + "Options"](
                            children.length === 1 ? "only" : value
                        );
                        options.classes = that._resolveClassesValues(options.classes, instance);
                        instance.element[instance.widgetName](options);
                    } else {
                        that._updateCornerClass(children[value](), value);
                    }
                });

                // Finally call the refresh method on each of the child widgets.
                this._callChildMethod("refresh");
            }
        }
    });

    /*!
     * jQuery UI Checkboxradio 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Checkboxradio
    //>>group: Widgets
    //>>description: Enhances a form with multiple themeable checkboxes or radio buttons.
    //>>docs: http://api.jqueryui.com/checkboxradio/
    //>>demos: http://jqueryui.com/checkboxradio/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/button.css
    //>>css.structure: ../../themes/base/checkboxradio.css
    //>>css.theme: ../../themes/base/theme.css



    $.widget("ui.checkboxradio", [$.ui.formResetMixin, {
        version: "1.12.1",
        options: {
            disabled: null,
            label: null,
            icon: true,
            classes: {
                "ui-checkboxradio-label": "ui-corner-all",
                "ui-checkboxradio-icon": "ui-corner-all"
            }
        },

        _getCreateOptions: function() {
            var disabled, labels;
            var that = this;
            var options = this._super() || {};

            // We read the type here, because it makes more sense to throw a element type error first,
            // rather then the error for lack of a label. Often if its the wrong type, it
            // won't have a label (e.g. calling on a div, btn, etc)
            this._readType();

            labels = this.element.labels();

            // If there are multiple labels, use the last one
            this.label = $(labels[labels.length - 1]);
            if (!this.label.length) {
                $.error("No label found for checkboxradio widget");
            }

            this.originalLabel = "";

            // We need to get the label text but this may also need to make sure it does not contain the
            // input itself.
            this.label.contents().not(this.element[0]).each(function() {

                // The label contents could be text, html, or a mix. We concat each element to get a
                // string representation of the label, without the input as part of it.
                that.originalLabel += this.nodeType === 3 ? $(this).text() : this.outerHTML;
            });

            // Set the label option if we found label text
            if (this.originalLabel) {
                options.label = this.originalLabel;
            }

            disabled = this.element[0].disabled;
            if (disabled != null) {
                options.disabled = disabled;
            }
            return options;
        },

        _create: function() {
            var checked = this.element[0].checked;

            this._bindFormResetHandler();

            if (this.options.disabled == null) {
                this.options.disabled = this.element[0].disabled;
            }

            this._setOption("disabled", this.options.disabled);
            this._addClass("ui-checkboxradio", "ui-helper-hidden-accessible");
            this._addClass(this.label, "ui-checkboxradio-label", "ui-button ui-widget");

            if (this.type === "radio") {
                this._addClass(this.label, "ui-checkboxradio-radio-label");
            }

            if (this.options.label && this.options.label !== this.originalLabel) {
                this._updateLabel();
            } else if (this.originalLabel) {
                this.options.label = this.originalLabel;
            }

            this._enhance();

            if (checked) {
                this._addClass(this.label, "ui-checkboxradio-checked", "ui-state-active");
                if (this.icon) {
                    this._addClass(this.icon, null, "ui-state-hover");
                }
            }

            this._on({
                change: "_toggleClasses",
                focus: function() {
                    this._addClass(this.label, null, "ui-state-focus ui-visual-focus");
                },
                blur: function() {
                    this._removeClass(this.label, null, "ui-state-focus ui-visual-focus");
                }
            });
        },

        _readType: function() {
            var nodeName = this.element[0].nodeName.toLowerCase();
            this.type = this.element[0].type;
            if (nodeName !== "input" || !/radio|checkbox/.test(this.type)) {
                $.error("Can't create checkboxradio on element.nodeName=" + nodeName +
                    " and element.type=" + this.type);
            }
        },

        // Support jQuery Mobile enhanced option
        _enhance: function() {
            this._updateIcon(this.element[0].checked);
        },

        widget: function() {
            return this.label;
        },

        _getRadioGroup: function() {
            var group;
            var name = this.element[0].name;
            var nameSelector = "input[name='" + $.ui.escapeSelector(name) + "']";

            if (!name) {
                return $([]);
            }

            if (this.form.length) {
                group = $(this.form[0].elements).filter(nameSelector);
            } else {

                // Not inside a form, check all inputs that also are not inside a form
                group = $(nameSelector).filter(function() {
                    return $(this).form().length === 0;
                });
            }

            return group.not(this.element);
        },

        _toggleClasses: function() {
            var checked = this.element[0].checked;
            this._toggleClass(this.label, "ui-checkboxradio-checked", "ui-state-active", checked);

            if (this.options.icon && this.type === "checkbox") {
                this._toggleClass(this.icon, null, "ui-icon-check ui-state-checked", checked)
                    ._toggleClass(this.icon, null, "ui-icon-blank", !checked);
            }

            if (this.type === "radio") {
                this._getRadioGroup()
                    .each(function() {
                        var instance = $(this).checkboxradio("instance");

                        if (instance) {
                            instance._removeClass(instance.label,
                                "ui-checkboxradio-checked", "ui-state-active");
                        }
                    });
            }
        },

        _destroy: function() {
            this._unbindFormResetHandler();

            if (this.icon) {
                this.icon.remove();
                this.iconSpace.remove();
            }
        },

        _setOption: function(key, value) {

            // We don't allow the value to be set to nothing
            if (key === "label" && !value) {
                return;
            }

            this._super(key, value);

            if (key === "disabled") {
                this._toggleClass(this.label, null, "ui-state-disabled", value);
                this.element[0].disabled = value;

                // Don't refresh when setting disabled
                return;
            }
            this.refresh();
        },

        _updateIcon: function(checked) {
            var toAdd = "ui-icon ui-icon-background ";

            if (this.options.icon) {
                if (!this.icon) {
                    this.icon = $("<span>");
                    this.iconSpace = $("<span> </span>");
                    this._addClass(this.iconSpace, "ui-checkboxradio-icon-space");
                }

                if (this.type === "checkbox") {
                    toAdd += checked ? "ui-icon-check ui-state-checked" : "ui-icon-blank";
                    this._removeClass(this.icon, null, checked ? "ui-icon-blank" : "ui-icon-check");
                } else {
                    toAdd += "ui-icon-blank";
                }
                this._addClass(this.icon, "ui-checkboxradio-icon", toAdd);
                if (!checked) {
                    this._removeClass(this.icon, null, "ui-icon-check ui-state-checked");
                }
                this.icon.prependTo(this.label).after(this.iconSpace);
            } else if (this.icon !== undefined) {
                this.icon.remove();
                this.iconSpace.remove();
                delete this.icon;
            }
        },

        _updateLabel: function() {

            // Remove the contents of the label ( minus the icon, icon space, and input )
            var contents = this.label.contents().not(this.element[0]);
            if (this.icon) {
                contents = contents.not(this.icon[0]);
            }
            if (this.iconSpace) {
                contents = contents.not(this.iconSpace[0]);
            }
            contents.remove();

            this.label.append(this.options.label);
        },

        refresh: function() {
            var checked = this.element[0].checked,
                isDisabled = this.element[0].disabled;

            this._updateIcon(checked);
            this._toggleClass(this.label, "ui-checkboxradio-checked", "ui-state-active", checked);
            if (this.options.label !== null) {
                this._updateLabel();
            }

            if (isDisabled !== this.options.disabled) {
                this._setOptions({ "disabled": isDisabled });
            }
        }

    }]);

    var widgetsCheckboxradio = $.ui.checkboxradio;


    /*!
     * jQuery UI Button 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Button
    //>>group: Widgets
    //>>description: Enhances a form with themeable buttons.
    //>>docs: http://api.jqueryui.com/button/
    //>>demos: http://jqueryui.com/button/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/button.css
    //>>css.theme: ../../themes/base/theme.css



    $.widget("ui.button", {
        version: "1.12.1",
        defaultElement: "<button>",
        options: {
            classes: {
                "ui-button": "ui-corner-all"
            },
            disabled: null,
            icon: null,
            iconPosition: "beginning",
            label: null,
            showLabel: true
        },

        _getCreateOptions: function() {
            var disabled,

                // This is to support cases like in jQuery Mobile where the base widget does have
                // an implementation of _getCreateOptions
                options = this._super() || {};

            this.isInput = this.element.is("input");

            disabled = this.element[0].disabled;
            if (disabled != null) {
                options.disabled = disabled;
            }

            this.originalLabel = this.isInput ? this.element.val() : this.element.html();
            if (this.originalLabel) {
                options.label = this.originalLabel;
            }

            return options;
        },

        _create: function() {
            if (!this.option.showLabel & !this.options.icon) {
                this.options.showLabel = true;
            }

            // We have to check the option again here even though we did in _getCreateOptions,
            // because null may have been passed on init which would override what was set in
            // _getCreateOptions
            if (this.options.disabled == null) {
                this.options.disabled = this.element[0].disabled || false;
            }

            this.hasTitle = !!this.element.attr("title");

            // Check to see if the label needs to be set or if its already correct
            if (this.options.label && this.options.label !== this.originalLabel) {
                if (this.isInput) {
                    this.element.val(this.options.label);
                } else {
                    this.element.html(this.options.label);
                }
            }
            this._addClass("ui-button", "ui-widget");
            this._setOption("disabled", this.options.disabled);
            this._enhance();

            if (this.element.is("a")) {
                this._on({
                    "keyup": function(event) {
                        if (event.keyCode === $.ui.keyCode.SPACE) {
                            event.preventDefault();

                            // Support: PhantomJS <= 1.9, IE 8 Only
                            // If a native click is available use it so we actually cause navigation
                            // otherwise just trigger a click event
                            if (this.element[0].click) {
                                this.element[0].click();
                            } else {
                                this.element.trigger("click");
                            }
                        }
                    }
                });
            }
        },

        _enhance: function() {
            if (!this.element.is("button")) {
                this.element.attr("role", "button");
            }

            if (this.options.icon) {
                this._updateIcon("icon", this.options.icon);
                this._updateTooltip();
            }
        },

        _updateTooltip: function() {
            this.title = this.element.attr("title");

            if (!this.options.showLabel && !this.title) {
                this.element.attr("title", this.options.label);
            }
        },

        _updateIcon: function(option, value) {
            var icon = option !== "iconPosition",
                position = icon ? this.options.iconPosition : value,
                displayBlock = position === "top" || position === "bottom";

            // Create icon
            if (!this.icon) {
                this.icon = $("<span>");

                this._addClass(this.icon, "ui-button-icon", "ui-icon");

                if (!this.options.showLabel) {
                    this._addClass("ui-button-icon-only");
                }
            } else if (icon) {

                // If we are updating the icon remove the old icon class
                this._removeClass(this.icon, null, this.options.icon);
            }

            // If we are updating the icon add the new icon class
            if (icon) {
                this._addClass(this.icon, null, value);
            }

            this._attachIcon(position);

            // If the icon is on top or bottom we need to add the ui-widget-icon-block class and remove
            // the iconSpace if there is one.
            if (displayBlock) {
                this._addClass(this.icon, null, "ui-widget-icon-block");
                if (this.iconSpace) {
                    this.iconSpace.remove();
                }
            } else {

                // Position is beginning or end so remove the ui-widget-icon-block class and add the
                // space if it does not exist
                if (!this.iconSpace) {
                    this.iconSpace = $("<span> </span>");
                    this._addClass(this.iconSpace, "ui-button-icon-space");
                }
                this._removeClass(this.icon, null, "ui-wiget-icon-block");
                this._attachIconSpace(position);
            }
        },

        _destroy: function() {
            this.element.removeAttr("role");

            if (this.icon) {
                this.icon.remove();
            }
            if (this.iconSpace) {
                this.iconSpace.remove();
            }
            if (!this.hasTitle) {
                this.element.removeAttr("title");
            }
        },

        _attachIconSpace: function(iconPosition) {
            this.icon[/^(?:end|bottom)/.test(iconPosition) ? "before" : "after"](this.iconSpace);
        },

        _attachIcon: function(iconPosition) {
            this.element[/^(?:end|bottom)/.test(iconPosition) ? "append" : "prepend"](this.icon);
        },

        _setOptions: function(options) {
            var newShowLabel = options.showLabel === undefined ?
                this.options.showLabel :
                options.showLabel,
                newIcon = options.icon === undefined ? this.options.icon : options.icon;

            if (!newShowLabel && !newIcon) {
                options.showLabel = true;
            }
            this._super(options);
        },

        _setOption: function(key, value) {
            if (key === "icon") {
                if (value) {
                    this._updateIcon(key, value);
                } else if (this.icon) {
                    this.icon.remove();
                    if (this.iconSpace) {
                        this.iconSpace.remove();
                    }
                }
            }

            if (key === "iconPosition") {
                this._updateIcon(key, value);
            }

            // Make sure we can't end up with a button that has neither text nor icon
            if (key === "showLabel") {
                this._toggleClass("ui-button-icon-only", null, !value);
                this._updateTooltip();
            }

            if (key === "label") {
                if (this.isInput) {
                    this.element.val(value);
                } else {

                    // If there is an icon, append it, else nothing then append the value
                    // this avoids removal of the icon when setting label text
                    this.element.html(value);
                    if (this.icon) {
                        this._attachIcon(this.options.iconPosition);
                        this._attachIconSpace(this.options.iconPosition);
                    }
                }
            }

            this._super(key, value);

            if (key === "disabled") {
                this._toggleClass(null, "ui-state-disabled", value);
                this.element[0].disabled = value;
                if (value) {
                    this.element.blur();
                }
            }
        },

        refresh: function() {

            // Make sure to only check disabled if its an element that supports this otherwise
            // check for the disabled class to determine state
            var isDisabled = this.element.is("input, button") ?
                this.element[0].disabled : this.element.hasClass("ui-button-disabled");

            if (isDisabled !== this.options.disabled) {
                this._setOptions({ disabled: isDisabled });
            }

            this._updateTooltip();
        }
    });

    // DEPRECATED
    if ($.uiBackCompat !== false) {

        // Text and Icons options
        $.widget("ui.button", $.ui.button, {
            options: {
                text: true,
                icons: {
                    primary: null,
                    secondary: null
                }
            },

            _create: function() {
                if (this.options.showLabel && !this.options.text) {
                    this.options.showLabel = this.options.text;
                }
                if (!this.options.showLabel && this.options.text) {
                    this.options.text = this.options.showLabel;
                }
                if (!this.options.icon && (this.options.icons.primary ||
                        this.options.icons.secondary)) {
                    if (this.options.icons.primary) {
                        this.options.icon = this.options.icons.primary;
                    } else {
                        this.options.icon = this.options.icons.secondary;
                        this.options.iconPosition = "end";
                    }
                } else if (this.options.icon) {
                    this.options.icons.primary = this.options.icon;
                }
                this._super();
            },

            _setOption: function(key, value) {
                if (key === "text") {
                    this._super("showLabel", value);
                    return;
                }
                if (key === "showLabel") {
                    this.options.text = value;
                }
                if (key === "icon") {
                    this.options.icons.primary = value;
                }
                if (key === "icons") {
                    if (value.primary) {
                        this._super("icon", value.primary);
                        this._super("iconPosition", "beginning");
                    } else if (value.secondary) {
                        this._super("icon", value.secondary);
                        this._super("iconPosition", "end");
                    }
                }
                this._superApply(arguments);
            }
        });

        $.fn.button = (function(orig) {
            return function() {
                if (!this.length || (this.length && this[0].tagName !== "INPUT") ||
                    (this.length && this[0].tagName === "INPUT" && (
                        this.attr("type") !== "checkbox" && this.attr("type") !== "radio"
                    ))) {
                    return orig.apply(this, arguments);
                }
                if (!$.ui.checkboxradio) {
                    $.error("Checkboxradio widget missing");
                }
                if (arguments.length === 0) {
                    return this.checkboxradio({
                        "icon": false
                    });
                }
                return this.checkboxradio.apply(this, arguments);
            };
        })($.fn.button);

        $.fn.buttonset = function() {
            if (!$.ui.controlgroup) {
                $.error("Controlgroup widget missing");
            }
            if (arguments[0] === "option" && arguments[1] === "items" && arguments[2]) {
                return this.controlgroup.apply(this, [arguments[0], "items.button", arguments[2]]);
            }
            if (arguments[0] === "option" && arguments[1] === "items") {
                return this.controlgroup.apply(this, [arguments[0], "items.button"]);
            }
            if (typeof arguments[0] === "object" && arguments[0].items) {
                arguments[0].items = {
                    button: arguments[0].items
                };
            }
            return this.controlgroup.apply(this, arguments);
        };
    }

    var widgetsButton = $.ui.button;


    // jscs:disable maximumLineLength
    /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
    /*!
     * jQuery UI Datepicker 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Datepicker
    //>>group: Widgets
    //>>description: Displays a calendar from an input or inline for selecting dates.
    //>>docs: http://api.jqueryui.com/datepicker/
    //>>demos: http://jqueryui.com/datepicker/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/datepicker.css
    //>>css.theme: ../../themes/base/theme.css



    $.extend($.ui, { datepicker: { version: "1.12.1" } });

    var datepicker_instActive;

    function datepicker_getZindex(elem) {
        var position, value;
        while (elem.length && elem[0] !== document) {

            // Ignore z-index if position is set to a value where z-index is ignored by the browser
            // This makes behavior of this function consistent across browsers
            // WebKit always returns auto if the element is positioned
            position = elem.css("position");
            if (position === "absolute" || position === "relative" || position === "fixed") {

                // IE returns 0 when zIndex is not specified
                // other browsers return a string
                // we ignore the case of nested elements with an explicit value of 0
                // <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
                value = parseInt(elem.css("zIndex"), 10);
                if (!isNaN(value) && value !== 0) {
                    return value;
                }
            }
            elem = elem.parent();
        }

        return 0;
    }
    /* Date picker manager.
       Use the singleton instance of this class, $.datepicker, to interact with the date picker.
       Settings for (groups of) date pickers are maintained in an instance object,
       allowing multiple different settings on the same page. */

    function Datepicker() {
        this._curInst = null; // The current instance in use
        this._keyEvent = false; // If the last event was a key event
        this._disabledInputs = []; // List of date picker inputs that have been disabled
        this._datepickerShowing = false; // True if the popup picker is showing , false if not
        this._inDialog = false; // True if showing within a "dialog", false if not
        this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
        this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
        this._appendClass = "ui-datepicker-append"; // The name of the append marker class
        this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
        this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
        this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
        this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
        this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
        this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
        this.regional = []; // Available regional settings, indexed by language code
        this.regional[""] = { // Default regional settings
            closeText: "Done", // Display text for close link
            prevText: "Prev", // Display text for previous month link
            nextText: "Next", // Display text for next month link
            currentText: "Today", // Display text for current month link
            monthNames: ["January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"
            ], // Names of months for drop-down and formatting
            monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
            dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
            dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
            dayNamesMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], // Column headings for days starting at Sunday
            weekHeader: "Wk", // Column header for week of the year
            dateFormat: "mm/dd/yy", // See format options on parseDate
            firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
            isRTL: false, // True if right-to-left language, false if left-to-right
            showMonthAfterYear: false, // True if the year select precedes month, false for month then year
            yearSuffix: "" // Additional text to append to the year in the month headers
        };
        this._defaults = { // Global defaults for all the date picker instances
            showOn: "focus", // "focus" for popup on focus,
            // "button" for trigger button, or "both" for either
            showAnim: "fadeIn", // Name of jQuery animation for popup
            showOptions: {}, // Options for enhanced animations
            defaultDate: null, // Used when field is blank: actual date,
            // +/-number for offset from today, null for today
            appendText: "", // Display text following the input box, e.g. showing the format
            buttonText: "...", // Text for trigger button
            buttonImage: "", // URL for trigger button image
            buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
            hideIfNoPrevNext: false, // True to hide next/previous month links
            // if not applicable, false to just disable them
            navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
            gotoCurrent: false, // True if today link goes back to current selection instead
            changeMonth: false, // True if month can be selected directly, false if only prev/next
            changeYear: false, // True if year can be selected directly, false if only prev/next
            yearRange: "c-10:c+10", // Range of years to display in drop-down,
            // either relative to today's year (-nn:+nn), relative to currently displayed year
            // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
            showOtherMonths: false, // True to show dates in other months, false to leave blank
            selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
            showWeek: false, // True to show week of the year, false to not show it
            calculateWeek: this.iso8601Week, // How to calculate the week of the year,
            // takes a Date and returns the number of the week for it
            shortYearCutoff: "+10", // Short year values < this are in the current century,
            // > this are in the previous century,
            // string value starting with "+" for current year + value
            minDate: null, // The earliest selectable date, or null for no limit
            maxDate: null, // The latest selectable date, or null for no limit
            duration: "fast", // Duration of display/closure
            beforeShowDay: null, // Function that takes a date and returns an array with
            // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
            // [2] = cell title (optional), e.g. $.datepicker.noWeekends
            beforeShow: null, // Function that takes an input field and
            // returns a set of custom settings for the date picker
            onSelect: null, // Define a callback function when a date is selected
            onChangeMonthYear: null, // Define a callback function when the month or year is changed
            onClose: null, // Define a callback function when the datepicker is closed
            numberOfMonths: 1, // Number of months to show at a time
            showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
            stepMonths: 1, // Number of months to step back/forward
            stepBigMonths: 12, // Number of months to step back/forward for the big links
            altField: "", // Selector for an alternate field to store selected dates into
            altFormat: "", // The date format to use for the alternate field
            constrainInput: true, // The input is constrained by the current date format
            showButtonPanel: false, // True to show button panel, false to not show it
            autoSize: false, // True to size the input for the date format, false to leave as is
            disabled: false // The initial disabled state
        };
        $.extend(this._defaults, this.regional[""]);
        this.regional.en = $.extend(true, {}, this.regional[""]);
        this.regional["en-US"] = $.extend(true, {}, this.regional.en);
        this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
    }

    $.extend(Datepicker.prototype, {
        /* Class name added to elements to indicate already configured with a date picker. */
        markerClassName: "hasDatepicker",

        //Keep track of the maximum number of rows displayed (see #7043)
        maxRows: 4,

        // TODO rename to "widget" when switching to widget factory
        _widgetDatepicker: function() {
            return this.dpDiv;
        },

        /* Override the default settings for all instances of the date picker.
         * @param  settings  object - the new settings to use as defaults (anonymous object)
         * @return the manager object
         */
        setDefaults: function(settings) {
            datepicker_extendRemove(this._defaults, settings || {});
            return this;
        },

        /* Attach the date picker to a jQuery selection.
         * @param  target	element - the target input field or division or span
         * @param  settings  object - the new settings to use for this date picker instance (anonymous)
         */
        _attachDatepicker: function(target, settings) {
            var nodeName, inline, inst;
            nodeName = target.nodeName.toLowerCase();
            inline = (nodeName === "div" || nodeName === "span");
            if (!target.id) {
                this.uuid += 1;
                target.id = "dp" + this.uuid;
            }
            inst = this._newInst($(target), inline);
            inst.settings = $.extend({}, settings || {});
            if (nodeName === "input") {
                this._connectDatepicker(target, inst);
            } else if (inline) {
                this._inlineDatepicker(target, inst);
            }
        },

        /* Create a new instance object. */
        _newInst: function(target, inline) {
            var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
            return {
                id: id,
                input: target, // associated target
                selectedDay: 0,
                selectedMonth: 0,
                selectedYear: 0, // current selection
                drawMonth: 0,
                drawYear: 0, // month being drawn
                inline: inline, // is datepicker inline or not
                dpDiv: (!inline ? this.dpDiv : // presentation div
                    datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))
            };
        },

        /* Attach the date picker to an input field. */
        _connectDatepicker: function(target, inst) {
            var input = $(target);
            inst.append = $([]);
            inst.trigger = $([]);
            if (input.hasClass(this.markerClassName)) {
                return;
            }
            this._attachments(input, inst);
            input.addClass(this.markerClassName).on("keydown", this._doKeyDown).
            on("keypress", this._doKeyPress).on("keyup", this._doKeyUp);
            this._autoSize(inst);
            $.data(target, "datepicker", inst);

            //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
            if (inst.settings.disabled) {
                this._disableDatepicker(target);
            }
        },

        /* Make attachments based on settings. */
        _attachments: function(input, inst) {
            var showOn, buttonText, buttonImage,
                appendText = this._get(inst, "appendText"),
                isRTL = this._get(inst, "isRTL");

            if (inst.append) {
                inst.append.remove();
            }
            if (appendText) {
                inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
                input[isRTL ? "before" : "after"](inst.append);
            }

            input.off("focus", this._showDatepicker);

            if (inst.trigger) {
                inst.trigger.remove();
            }

            showOn = this._get(inst, "showOn");
            if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
                input.on("focus", this._showDatepicker);
            }
            if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
                buttonText = this._get(inst, "buttonText");
                buttonImage = this._get(inst, "buttonImage");
                inst.trigger = $(this._get(inst, "buttonImageOnly") ?
                    $("<img/>").addClass(this._triggerClass).attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
                    $("<button type='button'></button>").addClass(this._triggerClass).html(!buttonImage ? buttonText : $("<img/>").attr({ src: buttonImage, alt: buttonText, title: buttonText })));
                input[isRTL ? "before" : "after"](inst.trigger);
                inst.trigger.on("click", function() {
                    if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
                        $.datepicker._hideDatepicker();
                    } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
                        $.datepicker._hideDatepicker();
                        $.datepicker._showDatepicker(input[0]);
                    } else {
                        $.datepicker._showDatepicker(input[0]);
                    }
                    return false;
                });
            }
        },

        /* Apply the maximum length for the date format. */
        _autoSize: function(inst) {
            if (this._get(inst, "autoSize") && !inst.inline) {
                var findMax, max, maxI, i,
                    date = new Date(2009, 12 - 1, 20), // Ensure double digits
                    dateFormat = this._get(inst, "dateFormat");

                if (dateFormat.match(/[DM]/)) {
                    findMax = function(names) {
                        max = 0;
                        maxI = 0;
                        for (i = 0; i < names.length; i++) {
                            if (names[i].length > max) {
                                max = names[i].length;
                                maxI = i;
                            }
                        }
                        return maxI;
                    };
                    date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
                        "monthNames" : "monthNamesShort"))));
                    date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
                        "dayNames" : "dayNamesShort"))) + 20 - date.getDay());
                }
                inst.input.attr("size", this._formatDate(inst, date).length);
            }
        },

        /* Attach an inline date picker to a div. */
        _inlineDatepicker: function(target, inst) {
            var divSpan = $(target);
            if (divSpan.hasClass(this.markerClassName)) {
                return;
            }
            divSpan.addClass(this.markerClassName).append(inst.dpDiv);
            $.data(target, "datepicker", inst);
            this._setDate(inst, this._getDefaultDate(inst), true);
            this._updateDatepicker(inst);
            this._updateAlternate(inst);

            //If disabled option is true, disable the datepicker before showing it (see ticket #5665)
            if (inst.settings.disabled) {
                this._disableDatepicker(target);
            }

            // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
            // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
            inst.dpDiv.css("display", "block");
        },

        /* Pop-up the date picker in a "dialog" box.
         * @param  input element - ignored
         * @param  date	string or Date - the initial date to display
         * @param  onSelect  function - the function to call when a date is selected
         * @param  settings  object - update the dialog date picker instance's settings (anonymous object)
         * @param  pos int[2] - coordinates for the dialog's position within the screen or
         *					event - with x/y coordinates or
         *					leave empty for default (screen centre)
         * @return the manager object
         */
        _dialogDatepicker: function(input, date, onSelect, settings, pos) {
            var id, browserWidth, browserHeight, scrollX, scrollY,
                inst = this._dialogInst; // internal instance

            if (!inst) {
                this.uuid += 1;
                id = "dp" + this.uuid;
                this._dialogInput = $("<input type='text' id='" + id +
                    "' style='position: absolute; top: -100px; width: 0px;'/>");
                this._dialogInput.on("keydown", this._doKeyDown);
                $("body").append(this._dialogInput);
                inst = this._dialogInst = this._newInst(this._dialogInput, false);
                inst.settings = {};
                $.data(this._dialogInput[0], "datepicker", inst);
            }
            datepicker_extendRemove(inst.settings, settings || {});
            date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
            this._dialogInput.val(date);

            this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
            if (!this._pos) {
                browserWidth = document.documentElement.clientWidth;
                browserHeight = document.documentElement.clientHeight;
                scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
                scrollY = document.documentElement.scrollTop || document.body.scrollTop;
                this._pos = // should use actual width/height below
                    [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
            }

            // Move input on screen for focus, but hidden behind dialog
            this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
            inst.settings.onSelect = onSelect;
            this._inDialog = true;
            this.dpDiv.addClass(this._dialogClass);
            this._showDatepicker(this._dialogInput[0]);
            if ($.blockUI) {
                $.blockUI(this.dpDiv);
            }
            $.data(this._dialogInput[0], "datepicker", inst);
            return this;
        },

        /* Detach a datepicker from its control.
         * @param  target	element - the target input field or division or span
         */
        _destroyDatepicker: function(target) {
            var nodeName,
                $target = $(target),
                inst = $.data(target, "datepicker");

            if (!$target.hasClass(this.markerClassName)) {
                return;
            }

            nodeName = target.nodeName.toLowerCase();
            $.removeData(target, "datepicker");
            if (nodeName === "input") {
                inst.append.remove();
                inst.trigger.remove();
                $target.removeClass(this.markerClassName).
                off("focus", this._showDatepicker).
                off("keydown", this._doKeyDown).
                off("keypress", this._doKeyPress).
                off("keyup", this._doKeyUp);
            } else if (nodeName === "div" || nodeName === "span") {
                $target.removeClass(this.markerClassName).empty();
            }

            if (datepicker_instActive === inst) {
                datepicker_instActive = null;
            }
        },

        /* Enable the date picker to a jQuery selection.
         * @param  target	element - the target input field or division or span
         */
        _enableDatepicker: function(target) {
            var nodeName, inline,
                $target = $(target),
                inst = $.data(target, "datepicker");

            if (!$target.hasClass(this.markerClassName)) {
                return;
            }

            nodeName = target.nodeName.toLowerCase();
            if (nodeName === "input") {
                target.disabled = false;
                inst.trigger.filter("button").
                each(function() { this.disabled = false; }).end().
                filter("img").css({ opacity: "1.0", cursor: "" });
            } else if (nodeName === "div" || nodeName === "span") {
                inline = $target.children("." + this._inlineClass);
                inline.children().removeClass("ui-state-disabled");
                inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
                prop("disabled", false);
            }
            this._disabledInputs = $.map(this._disabledInputs,
                function(value) { return (value === target ? null : value); }); // delete entry
        },

        /* Disable the date picker to a jQuery selection.
         * @param  target	element - the target input field or division or span
         */
        _disableDatepicker: function(target) {
            var nodeName, inline,
                $target = $(target),
                inst = $.data(target, "datepicker");

            if (!$target.hasClass(this.markerClassName)) {
                return;
            }

            nodeName = target.nodeName.toLowerCase();
            if (nodeName === "input") {
                target.disabled = true;
                inst.trigger.filter("button").
                each(function() { this.disabled = true; }).end().
                filter("img").css({ opacity: "0.5", cursor: "default" });
            } else if (nodeName === "div" || nodeName === "span") {
                inline = $target.children("." + this._inlineClass);
                inline.children().addClass("ui-state-disabled");
                inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
                prop("disabled", true);
            }
            this._disabledInputs = $.map(this._disabledInputs,
                function(value) { return (value === target ? null : value); }); // delete entry
            this._disabledInputs[this._disabledInputs.length] = target;
        },

        /* Is the first field in a jQuery collection disabled as a datepicker?
         * @param  target	element - the target input field or division or span
         * @return boolean - true if disabled, false if enabled
         */
        _isDisabledDatepicker: function(target) {
            if (!target) {
                return false;
            }
            for (var i = 0; i < this._disabledInputs.length; i++) {
                if (this._disabledInputs[i] === target) {
                    return true;
                }
            }
            return false;
        },

        /* Retrieve the instance data for the target control.
         * @param  target  element - the target input field or division or span
         * @return  object - the associated instance data
         * @throws  error if a jQuery problem getting data
         */
        _getInst: function(target) {
            try {
                return $.data(target, "datepicker");
            } catch (err) {
                throw "Missing instance data for this datepicker";
            }
        },

        /* Update or retrieve the settings for a date picker attached to an input field or division.
         * @param  target  element - the target input field or division or span
         * @param  name	object - the new settings to update or
         *				string - the name of the setting to change or retrieve,
         *				when retrieving also "all" for all instance settings or
         *				"defaults" for all global defaults
         * @param  value   any - the new value for the setting
         *				(omit if above is an object or to retrieve a value)
         */
        _optionDatepicker: function(target, name, value) {
            var settings, date, minDate, maxDate,
                inst = this._getInst(target);

            if (arguments.length === 2 && typeof name === "string") {
                return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
                    (inst ? (name === "all" ? $.extend({}, inst.settings) :
                        this._get(inst, name)) : null));
            }

            settings = name || {};
            if (typeof name === "string") {
                settings = {};
                settings[name] = value;
            }

            if (inst) {
                if (this._curInst === inst) {
                    this._hideDatepicker();
                }

                date = this._getDateDatepicker(target, true);
                minDate = this._getMinMaxDate(inst, "min");
                maxDate = this._getMinMaxDate(inst, "max");
                datepicker_extendRemove(inst.settings, settings);

                // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
                if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
                    inst.settings.minDate = this._formatDate(inst, minDate);
                }
                if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
                    inst.settings.maxDate = this._formatDate(inst, maxDate);
                }
                if ("disabled" in settings) {
                    if (settings.disabled) {
                        this._disableDatepicker(target);
                    } else {
                        this._enableDatepicker(target);
                    }
                }
                this._attachments($(target), inst);
                this._autoSize(inst);
                this._setDate(inst, date);
                this._updateAlternate(inst);
                this._updateDatepicker(inst);
            }
        },

        // Change method deprecated
        _changeDatepicker: function(target, name, value) {
            this._optionDatepicker(target, name, value);
        },

        /* Redraw the date picker attached to an input field or division.
         * @param  target  element - the target input field or division or span
         */
        _refreshDatepicker: function(target) {
            var inst = this._getInst(target);
            if (inst) {
                this._updateDatepicker(inst);
            }
        },

        /* Set the dates for a jQuery selection.
         * @param  target element - the target input field or division or span
         * @param  date	Date - the new date
         */
        _setDateDatepicker: function(target, date) {
            var inst = this._getInst(target);
            if (inst) {
                this._setDate(inst, date);
                this._updateDatepicker(inst);
                this._updateAlternate(inst);
            }
        },

        /* Get the date(s) for the first entry in a jQuery selection.
         * @param  target element - the target input field or division or span
         * @param  noDefault boolean - true if no default date is to be used
         * @return Date - the current date
         */
        _getDateDatepicker: function(target, noDefault) {
            var inst = this._getInst(target);
            if (inst && !inst.inline) {
                this._setDateFromField(inst, noDefault);
            }
            return (inst ? this._getDate(inst) : null);
        },

        /* Handle keystrokes. */
        _doKeyDown: function(event) {
            var onSelect, dateStr, sel,
                inst = $.datepicker._getInst(event.target),
                handled = true,
                isRTL = inst.dpDiv.is(".ui-datepicker-rtl");

            inst._keyEvent = true;
            if ($.datepicker._datepickerShowing) {
                switch (event.keyCode) {
                    case 9:
                        $.datepicker._hideDatepicker();
                        handled = false;
                        break; // hide on tab out
                    case 13:
                        sel = $("td." + $.datepicker._dayOverClass + ":not(." +
                            $.datepicker._currentClass + ")", inst.dpDiv);
                        if (sel[0]) {
                            $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
                        }

                        onSelect = $.datepicker._get(inst, "onSelect");
                        if (onSelect) {
                            dateStr = $.datepicker._formatDate(inst);

                            // Trigger custom callback
                            onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
                        } else {
                            $.datepicker._hideDatepicker();
                        }

                        return false; // don't submit the form
                    case 27:
                        $.datepicker._hideDatepicker();
                        break; // hide on escape
                    case 33:
                        $.datepicker._adjustDate(event.target, (event.ctrlKey ?
                            -$.datepicker._get(inst, "stepBigMonths") :
                            -$.datepicker._get(inst, "stepMonths")), "M");
                        break; // previous month/year on page up/+ ctrl
                    case 34:
                        $.datepicker._adjustDate(event.target, (event.ctrlKey ?
                            +$.datepicker._get(inst, "stepBigMonths") :
                            +$.datepicker._get(inst, "stepMonths")), "M");
                        break; // next month/year on page down/+ ctrl
                    case 35:
                        if (event.ctrlKey || event.metaKey) {
                            $.datepicker._clearDate(event.target);
                        }
                        handled = event.ctrlKey || event.metaKey;
                        break; // clear on ctrl or command +end
                    case 36:
                        if (event.ctrlKey || event.metaKey) {
                            $.datepicker._gotoToday(event.target);
                        }
                        handled = event.ctrlKey || event.metaKey;
                        break; // current on ctrl or command +home
                    case 37:
                        if (event.ctrlKey || event.metaKey) {
                            $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
                        }
                        handled = event.ctrlKey || event.metaKey;

                        // -1 day on ctrl or command +left
                        if (event.originalEvent.altKey) {
                            $.datepicker._adjustDate(event.target, (event.ctrlKey ?
                                -$.datepicker._get(inst, "stepBigMonths") :
                                -$.datepicker._get(inst, "stepMonths")), "M");
                        }

                        // next month/year on alt +left on Mac
                        break;
                    case 38:
                        if (event.ctrlKey || event.metaKey) {
                            $.datepicker._adjustDate(event.target, -7, "D");
                        }
                        handled = event.ctrlKey || event.metaKey;
                        break; // -1 week on ctrl or command +up
                    case 39:
                        if (event.ctrlKey || event.metaKey) {
                            $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
                        }
                        handled = event.ctrlKey || event.metaKey;

                        // +1 day on ctrl or command +right
                        if (event.originalEvent.altKey) {
                            $.datepicker._adjustDate(event.target, (event.ctrlKey ?
                                +$.datepicker._get(inst, "stepBigMonths") :
                                +$.datepicker._get(inst, "stepMonths")), "M");
                        }

                        // next month/year on alt +right
                        break;
                    case 40:
                        if (event.ctrlKey || event.metaKey) {
                            $.datepicker._adjustDate(event.target, +7, "D");
                        }
                        handled = event.ctrlKey || event.metaKey;
                        break; // +1 week on ctrl or command +down
                    default:
                        handled = false;
                }
            } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
                $.datepicker._showDatepicker(this);
            } else {
                handled = false;
            }

            if (handled) {
                event.preventDefault();
                event.stopPropagation();
            }
        },

        /* Filter entered characters - based on date format. */
        _doKeyPress: function(event) {
            var chars, chr,
                inst = $.datepicker._getInst(event.target);

            if ($.datepicker._get(inst, "constrainInput")) {
                chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
                chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
                return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
            }
        },

        /* Synchronise manual entry and field/alternate field. */
        _doKeyUp: function(event) {
            var date,
                inst = $.datepicker._getInst(event.target);

            if (inst.input.val() !== inst.lastVal) {
                try {
                    date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
                        (inst.input ? inst.input.val() : null),
                        $.datepicker._getFormatConfig(inst));

                    if (date) { // only if valid
                        $.datepicker._setDateFromField(inst);
                        $.datepicker._updateAlternate(inst);
                        $.datepicker._updateDatepicker(inst);
                    }
                } catch (err) {}
            }
            return true;
        },

        /* Pop-up the date picker for a given input field.
         * If false returned from beforeShow event handler do not show.
         * @param  input  element - the input field attached to the date picker or
         *					event - if triggered by focus
         */
        _showDatepicker: function(input) {
            input = input.target || input;
            if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
                input = $("input", input.parentNode)[0];
            }

            if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
                return;
            }

            var inst, beforeShow, beforeShowSettings, isFixed,
                offset, showAnim, duration;

            inst = $.datepicker._getInst(input);
            if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
                $.datepicker._curInst.dpDiv.stop(true, true);
                if (inst && $.datepicker._datepickerShowing) {
                    $.datepicker._hideDatepicker($.datepicker._curInst.input[0]);
                }
            }

            beforeShow = $.datepicker._get(inst, "beforeShow");
            beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
            if (beforeShowSettings === false) {
                return;
            }
            datepicker_extendRemove(inst.settings, beforeShowSettings);

            inst.lastVal = null;
            $.datepicker._lastInput = input;
            $.datepicker._setDateFromField(inst);

            if ($.datepicker._inDialog) { // hide cursor
                input.value = "";
            }
            if (!$.datepicker._pos) { // position below input
                $.datepicker._pos = $.datepicker._findPos(input);
                $.datepicker._pos[1] += input.offsetHeight; // add the height
            }

            isFixed = false;
            $(input).parents().each(function() {
                isFixed |= $(this).css("position") === "fixed";
                return !isFixed;
            });

            offset = { left: $.datepicker._pos[0], top: $.datepicker._pos[1] };
            $.datepicker._pos = null;

            //to avoid flashes on Firefox
            inst.dpDiv.empty();

            // determine sizing offscreen
            inst.dpDiv.css({ position: "absolute", display: "block", top: "-1000px" });
            $.datepicker._updateDatepicker(inst);

            // fix width for dynamic number of date pickers
            // and adjust position before showing
            offset = $.datepicker._checkOffset(inst, offset, isFixed);
            inst.dpDiv.css({
                position: ($.datepicker._inDialog && $.blockUI ?
                    "static" : (isFixed ? "fixed" : "absolute")),
                display: "none",
                left: offset.left + "px",
                top: offset.top + "px"
            });

            if (!inst.inline) {
                showAnim = $.datepicker._get(inst, "showAnim");
                duration = $.datepicker._get(inst, "duration");
                inst.dpDiv.css("z-index", datepicker_getZindex($(input)) + 1);
                $.datepicker._datepickerShowing = true;

                if ($.effects && $.effects.effect[showAnim]) {
                    inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
                } else {
                    inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
                }

                if ($.datepicker._shouldFocusInput(inst)) {
                    inst.input.trigger("focus");
                }

                $.datepicker._curInst = inst;
            }
        },

        /* Generate the date picker content. */
        _updateDatepicker: function(inst) {
            this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
            datepicker_instActive = inst; // for delegate hover events
            inst.dpDiv.empty().append(this._generateHTML(inst));
            this._attachHandlers(inst);

            var origyearshtml,
                numMonths = this._getNumberOfMonths(inst),
                cols = numMonths[1],
                width = 17,
                activeCell = inst.dpDiv.find("." + this._dayOverClass + " a");

            if (activeCell.length > 0) {
                datepicker_handleMouseover.apply(activeCell.get(0));
            }

            inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
            if (cols > 1) {
                inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
            }
            inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
                "Class"]("ui-datepicker-multi");
            inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
                "Class"]("ui-datepicker-rtl");

            if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput(inst)) {
                inst.input.trigger("focus");
            }

            // Deffered render of the years select (to avoid flashes on Firefox)
            if (inst.yearshtml) {
                origyearshtml = inst.yearshtml;
                setTimeout(function() {

                    //assure that inst.yearshtml didn't change.
                    if (origyearshtml === inst.yearshtml && inst.yearshtml) {
                        inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
                    }
                    origyearshtml = inst.yearshtml = null;
                }, 0);
            }
        },

        // #6694 - don't focus the input if it's already focused
        // this breaks the change event in IE
        // Support: IE and jQuery <1.9
        _shouldFocusInput: function(inst) {
            return inst.input && inst.input.is(":visible") && !inst.input.is(":disabled") && !inst.input.is(":focus");
        },

        /* Check positioning to remain on screen. */
        _checkOffset: function(inst, offset, isFixed) {
            var dpWidth = inst.dpDiv.outerWidth(),
                dpHeight = inst.dpDiv.outerHeight(),
                inputWidth = inst.input ? inst.input.outerWidth() : 0,
                inputHeight = inst.input ? inst.input.outerHeight() : 0,
                viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
                viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());

            offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
            offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
            offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

            // Now check if datepicker is showing outside window viewport - move to a better place if so.
            offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
                Math.abs(offset.left + dpWidth - viewWidth) : 0);
            offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
                Math.abs(dpHeight + inputHeight) : 0);

            return offset;
        },

        /* Find an object's position on the screen. */
        _findPos: function(obj) {
            var position,
                inst = this._getInst(obj),
                isRTL = this._get(inst, "isRTL");

            while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
                obj = obj[isRTL ? "previousSibling" : "nextSibling"];
            }

            position = $(obj).offset();
            return [position.left, position.top];
        },

        /* Hide the date picker from view.
         * @param  input  element - the input field attached to the date picker
         */
        _hideDatepicker: function(input) {
            var showAnim, duration, postProcess, onClose,
                inst = this._curInst;

            if (!inst || (input && inst !== $.data(input, "datepicker"))) {
                return;
            }

            if (this._datepickerShowing) {
                showAnim = this._get(inst, "showAnim");
                duration = this._get(inst, "duration");
                postProcess = function() {
                    $.datepicker._tidyDialog(inst);
                };

                // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
                if ($.effects && ($.effects.effect[showAnim] || $.effects[showAnim])) {
                    inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
                } else {
                    inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
                        (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
                }

                if (!showAnim) {
                    postProcess();
                }
                this._datepickerShowing = false;

                onClose = this._get(inst, "onClose");
                if (onClose) {
                    onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
                }

                this._lastInput = null;
                if (this._inDialog) {
                    this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
                    if ($.blockUI) {
                        $.unblockUI();
                        $("body").append(this.dpDiv);
                    }
                }
                this._inDialog = false;
            }
        },

        /* Tidy up after a dialog display. */
        _tidyDialog: function(inst) {
            inst.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar");
        },

        /* Close date picker if clicked elsewhere. */
        _checkExternalClick: function(event) {
            if (!$.datepicker._curInst) {
                return;
            }

            var $target = $(event.target),
                inst = $.datepicker._getInst($target[0]);

            if ((($target[0].id !== $.datepicker._mainDivId &&
                    $target.parents("#" + $.datepicker._mainDivId).length === 0 &&
                    !$target.hasClass($.datepicker.markerClassName) &&
                    !$target.closest("." + $.datepicker._triggerClass).length &&
                    $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))) ||
                ($target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst)) {
                $.datepicker._hideDatepicker();
            }
        },

        /* Adjust one of the date sub-fields. */
        _adjustDate: function(id, offset, period) {
            var target = $(id),
                inst = this._getInst(target[0]);

            if (this._isDisabledDatepicker(target[0])) {
                return;
            }
            this._adjustInstDate(inst, offset +
                (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
                period);
            this._updateDatepicker(inst);
        },

        /* Action for current link. */
        _gotoToday: function(id) {
            var date,
                target = $(id),
                inst = this._getInst(target[0]);

            if (this._get(inst, "gotoCurrent") && inst.currentDay) {
                inst.selectedDay = inst.currentDay;
                inst.drawMonth = inst.selectedMonth = inst.currentMonth;
                inst.drawYear = inst.selectedYear = inst.currentYear;
            } else {
                date = new Date();
                inst.selectedDay = date.getDate();
                inst.drawMonth = inst.selectedMonth = date.getMonth();
                inst.drawYear = inst.selectedYear = date.getFullYear();
            }
            this._notifyChange(inst);
            this._adjustDate(target);
        },

        /* Action for selecting a new month/year. */
        _selectMonthYear: function(id, select, period) {
            var target = $(id),
                inst = this._getInst(target[0]);

            inst["selected" + (period === "M" ? "Month" : "Year")] =
                inst["draw" + (period === "M" ? "Month" : "Year")] =
                parseInt(select.options[select.selectedIndex].value, 10);

            this._notifyChange(inst);
            this._adjustDate(target);
        },

        /* Action for selecting a day. */
        _selectDay: function(id, month, year, td) {
            var inst,
                target = $(id);

            if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
                return;
            }

            inst = this._getInst(target[0]);
            inst.selectedDay = inst.currentDay = $("a", td).html();
            inst.selectedMonth = inst.currentMonth = month;
            inst.selectedYear = inst.currentYear = year;
            this._selectDate(id, this._formatDate(inst,
                inst.currentDay, inst.currentMonth, inst.currentYear));
        },

        /* Erase the input field and hide the date picker. */
        _clearDate: function(id) {
            var target = $(id);
            this._selectDate(target, "");
        },

        /* Update the input field with the selected date. */
        _selectDate: function(id, dateStr) {
            var onSelect,
                target = $(id),
                inst = this._getInst(target[0]);

            dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
            if (inst.input) {
                inst.input.val(dateStr);
            }
            this._updateAlternate(inst);

            onSelect = this._get(inst, "onSelect");
            if (onSelect) {
                onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
            } else if (inst.input) {
                inst.input.trigger("change"); // fire the change event
            }

            if (inst.inline) {
                this._updateDatepicker(inst);
            } else {
                this._hideDatepicker();
                this._lastInput = inst.input[0];
                if (typeof(inst.input[0]) !== "object") {
                    inst.input.trigger("focus"); // restore focus
                }
                this._lastInput = null;
            }
        },

        /* Update any alternate field to synchronise with the main field. */
        _updateAlternate: function(inst) {
            var altFormat, date, dateStr,
                altField = this._get(inst, "altField");

            if (altField) { // update alternate field too
                altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
                date = this._getDate(inst);
                dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
                $(altField).val(dateStr);
            }
        },

        /* Set as beforeShowDay function to prevent selection of weekends.
         * @param  date  Date - the date to customise
         * @return [boolean, string] - is this date selectable?, what is its CSS class?
         */
        noWeekends: function(date) {
            var day = date.getDay();
            return [(day > 0 && day < 6), ""];
        },

        /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
         * @param  date  Date - the date to get the week for
         * @return  number - the number of the week within the year that contains this date
         */
        iso8601Week: function(date) {
            var time,
                checkDate = new Date(date.getTime());

            // Find Thursday of this week starting on Monday
            checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));

            time = checkDate.getTime();
            checkDate.setMonth(0); // Compare with Jan 1
            checkDate.setDate(1);
            return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
        },

        /* Parse a string value into a date object.
         * See formatDate below for the possible formats.
         *
         * @param  format string - the expected format of the date
         * @param  value string - the date in the above format
         * @param  settings Object - attributes include:
         *					shortYearCutoff  number - the cutoff year for determining the century (optional)
         *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
         *					dayNames		string[7] - names of the days from Sunday (optional)
         *					monthNamesShort string[12] - abbreviated names of the months (optional)
         *					monthNames		string[12] - names of the months (optional)
         * @return  Date - the extracted date value or null if value is blank
         */
        parseDate: function(format, value, settings) {
            if (format == null || value == null) {
                throw "Invalid arguments";
            }

            value = (typeof value === "object" ? value.toString() : value + "");
            if (value === "") {
                return null;
            }

            var iFormat, dim, extra,
                iValue = 0,
                shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
                shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
                    new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
                dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
                dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
                monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
                monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
                year = -1,
                month = -1,
                day = -1,
                doy = -1,
                literal = false,
                date,

                // Check whether a format character is doubled
                lookAhead = function(match) {
                    var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
                    if (matches) {
                        iFormat++;
                    }
                    return matches;
                },

                // Extract a number from the string value
                getNumber = function(match) {
                    var isDoubled = lookAhead(match),
                        size = (match === "@" ? 14 : (match === "!" ? 20 :
                            (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
                        minSize = (match === "y" ? size : 1),
                        digits = new RegExp("^\\d{" + minSize + "," + size + "}"),
                        num = value.substring(iValue).match(digits);
                    if (!num) {
                        throw "Missing number at position " + iValue;
                    }
                    iValue += num[0].length;
                    return parseInt(num[0], 10);
                },

                // Extract a name from the string value and convert to an index
                getName = function(match, shortNames, longNames) {
                    var index = -1,
                        names = $.map(lookAhead(match) ? longNames : shortNames, function(v, k) {
                            return [
                                [k, v]
                            ];
                        }).sort(function(a, b) {
                            return -(a[1].length - b[1].length);
                        });

                    $.each(names, function(i, pair) {
                        var name = pair[1];
                        if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
                            index = pair[0];
                            iValue += name.length;
                            return false;
                        }
                    });
                    if (index !== -1) {
                        return index + 1;
                    } else {
                        throw "Unknown name at position " + iValue;
                    }
                },

                // Confirm that a literal character matches the string value
                checkLiteral = function() {
                    if (value.charAt(iValue) !== format.charAt(iFormat)) {
                        throw "Unexpected literal at position " + iValue;
                    }
                    iValue++;
                };

            for (iFormat = 0; iFormat < format.length; iFormat++) {
                if (literal) {
                    if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
                        literal = false;
                    } else {
                        checkLiteral();
                    }
                } else {
                    switch (format.charAt(iFormat)) {
                        case "d":
                            day = getNumber("d");
                            break;
                        case "D":
                            getName("D", dayNamesShort, dayNames);
                            break;
                        case "o":
                            doy = getNumber("o");
                            break;
                        case "m":
                            month = getNumber("m");
                            break;
                        case "M":
                            month = getName("M", monthNamesShort, monthNames);
                            break;
                        case "y":
                            year = getNumber("y");
                            break;
                        case "@":
                            date = new Date(getNumber("@"));
                            year = date.getFullYear();
                            month = date.getMonth() + 1;
                            day = date.getDate();
                            break;
                        case "!":
                            date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
                            year = date.getFullYear();
                            month = date.getMonth() + 1;
                            day = date.getDate();
                            break;
                        case "'":
                            if (lookAhead("'")) {
                                checkLiteral();
                            } else {
                                literal = true;
                            }
                            break;
                        default:
                            checkLiteral();
                    }
                }
            }

            if (iValue < value.length) {
                extra = value.substr(iValue);
                if (!/^\s+/.test(extra)) {
                    throw "Extra/unparsed characters found in date: " + extra;
                }
            }

            if (year === -1) {
                year = new Date().getFullYear();
            } else if (year < 100) {
                year += new Date().getFullYear() - new Date().getFullYear() % 100 +
                    (year <= shortYearCutoff ? 0 : -100);
            }

            if (doy > -1) {
                month = 1;
                day = doy;
                do {
                    dim = this._getDaysInMonth(year, month - 1);
                    if (day <= dim) {
                        break;
                    }
                    month++;
                    day -= dim;
                } while (true);
            }

            date = this._daylightSavingAdjust(new Date(year, month - 1, day));
            if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
                throw "Invalid date"; // E.g. 31/02/00
            }
            return date;
        },

        /* Standard date formats. */
        ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
        COOKIE: "D, dd M yy",
        ISO_8601: "yy-mm-dd",
        RFC_822: "D, d M y",
        RFC_850: "DD, dd-M-y",
        RFC_1036: "D, d M y",
        RFC_1123: "D, d M yy",
        RFC_2822: "D, d M yy",
        RSS: "D, d M y", // RFC 822
        TICKS: "!",
        TIMESTAMP: "@",
        W3C: "yy-mm-dd", // ISO 8601

        _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
            Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),

        /* Format a date object into a string value.
         * The format can be combinations of the following:
         * d  - day of month (no leading zero)
         * dd - day of month (two digit)
         * o  - day of year (no leading zeros)
         * oo - day of year (three digit)
         * D  - day name short
         * DD - day name long
         * m  - month of year (no leading zero)
         * mm - month of year (two digit)
         * M  - month name short
         * MM - month name long
         * y  - year (two digit)
         * yy - year (four digit)
         * @ - Unix timestamp (ms since 01/01/1970)
         * ! - Windows ticks (100ns since 01/01/0001)
         * "..." - literal text
         * '' - single quote
         *
         * @param  format string - the desired format of the date
         * @param  date Date - the date value to format
         * @param  settings Object - attributes include:
         *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
         *					dayNames		string[7] - names of the days from Sunday (optional)
         *					monthNamesShort string[12] - abbreviated names of the months (optional)
         *					monthNames		string[12] - names of the months (optional)
         * @return  string - the date in the above format
         */
        formatDate: function(format, date, settings) {
            if (!date) {
                return "";
            }

            var iFormat,
                dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
                dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
                monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
                monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,

                // Check whether a format character is doubled
                lookAhead = function(match) {
                    var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
                    if (matches) {
                        iFormat++;
                    }
                    return matches;
                },

                // Format a number, with leading zero if necessary
                formatNumber = function(match, value, len) {
                    var num = "" + value;
                    if (lookAhead(match)) {
                        while (num.length < len) {
                            num = "0" + num;
                        }
                    }
                    return num;
                },

                // Format a name, short or long as requested
                formatName = function(match, value, shortNames, longNames) {
                    return (lookAhead(match) ? longNames[value] : shortNames[value]);
                },
                output = "",
                literal = false;

            if (date) {
                for (iFormat = 0; iFormat < format.length; iFormat++) {
                    if (literal) {
                        if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
                            literal = false;
                        } else {
                            output += format.charAt(iFormat);
                        }
                    } else {
                        switch (format.charAt(iFormat)) {
                            case "d":
                                output += formatNumber("d", date.getDate(), 2);
                                break;
                            case "D":
                                output += formatName("D", date.getDay(), dayNamesShort, dayNames);
                                break;
                            case "o":
                                output += formatNumber("o",
                                    Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
                                break;
                            case "m":
                                output += formatNumber("m", date.getMonth() + 1, 2);
                                break;
                            case "M":
                                output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
                                break;
                            case "y":
                                output += (lookAhead("y") ? date.getFullYear() :
                                    (date.getFullYear() % 100 < 10 ? "0" : "") + date.getFullYear() % 100);
                                break;
                            case "@":
                                output += date.getTime();
                                break;
                            case "!":
                                output += date.getTime() * 10000 + this._ticksTo1970;
                                break;
                            case "'":
                                if (lookAhead("'")) {
                                    output += "'";
                                } else {
                                    literal = true;
                                }
                                break;
                            default:
                                output += format.charAt(iFormat);
                        }
                    }
                }
            }
            return output;
        },

        /* Extract all possible characters from the date format. */
        _possibleChars: function(format) {
            var iFormat,
                chars = "",
                literal = false,

                // Check whether a format character is doubled
                lookAhead = function(match) {
                    var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
                    if (matches) {
                        iFormat++;
                    }
                    return matches;
                };

            for (iFormat = 0; iFormat < format.length; iFormat++) {
                if (literal) {
                    if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
                        literal = false;
                    } else {
                        chars += format.charAt(iFormat);
                    }
                } else {
                    switch (format.charAt(iFormat)) {
                        case "d":
                        case "m":
                        case "y":
                        case "@":
                            chars += "0123456789";
                            break;
                        case "D":
                        case "M":
                            return null; // Accept anything
                        case "'":
                            if (lookAhead("'")) {
                                chars += "'";
                            } else {
                                literal = true;
                            }
                            break;
                        default:
                            chars += format.charAt(iFormat);
                    }
                }
            }
            return chars;
        },

        /* Get a setting value, defaulting if necessary. */
        _get: function(inst, name) {
            return inst.settings[name] !== undefined ?
                inst.settings[name] : this._defaults[name];
        },

        /* Parse existing date and initialise date picker. */
        _setDateFromField: function(inst, noDefault) {
            if (inst.input.val() === inst.lastVal) {
                return;
            }

            var dateFormat = this._get(inst, "dateFormat"),
                dates = inst.lastVal = inst.input ? inst.input.val() : null,
                defaultDate = this._getDefaultDate(inst),
                date = defaultDate,
                settings = this._getFormatConfig(inst);

            try {
                date = this.parseDate(dateFormat, dates, settings) || defaultDate;
            } catch (event) {
                dates = (noDefault ? "" : dates);
            }
            inst.selectedDay = date.getDate();
            inst.drawMonth = inst.selectedMonth = date.getMonth();
            inst.drawYear = inst.selectedYear = date.getFullYear();
            inst.currentDay = (dates ? date.getDate() : 0);
            inst.currentMonth = (dates ? date.getMonth() : 0);
            inst.currentYear = (dates ? date.getFullYear() : 0);
            this._adjustInstDate(inst);
        },

        /* Retrieve the default date shown on opening. */
        _getDefaultDate: function(inst) {
            return this._restrictMinMax(inst,
                this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
        },

        /* A date may be specified as an exact value or a relative one. */
        _determineDate: function(inst, date, defaultDate) {
            var offsetNumeric = function(offset) {
                    var date = new Date();
                    date.setDate(date.getDate() + offset);
                    return date;
                },
                offsetString = function(offset) {
                    try {
                        return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
                            offset, $.datepicker._getFormatConfig(inst));
                    } catch (e) {

                        // Ignore
                    }

                    var date = (offset.toLowerCase().match(/^c/) ?
                            $.datepicker._getDate(inst) : null) || new Date(),
                        year = date.getFullYear(),
                        month = date.getMonth(),
                        day = date.getDate(),
                        pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
                        matches = pattern.exec(offset);

                    while (matches) {
                        switch (matches[2] || "d") {
                            case "d":
                            case "D":
                                day += parseInt(matches[1], 10);
                                break;
                            case "w":
                            case "W":
                                day += parseInt(matches[1], 10) * 7;
                                break;
                            case "m":
                            case "M":
                                month += parseInt(matches[1], 10);
                                day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
                                break;
                            case "y":
                            case "Y":
                                year += parseInt(matches[1], 10);
                                day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
                                break;
                        }
                        matches = pattern.exec(offset);
                    }
                    return new Date(year, month, day);
                },
                newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
                    (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));

            newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
            if (newDate) {
                newDate.setHours(0);
                newDate.setMinutes(0);
                newDate.setSeconds(0);
                newDate.setMilliseconds(0);
            }
            return this._daylightSavingAdjust(newDate);
        },

        /* Handle switch to/from daylight saving.
         * Hours may be non-zero on daylight saving cut-over:
         * > 12 when midnight changeover, but then cannot generate
         * midnight datetime, so jump to 1AM, otherwise reset.
         * @param  date  (Date) the date to check
         * @return  (Date) the corrected date
         */
        _daylightSavingAdjust: function(date) {
            if (!date) {
                return null;
            }
            date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
            return date;
        },

        /* Set the date(s) directly. */
        _setDate: function(inst, date, noChange) {
            var clear = !date,
                origMonth = inst.selectedMonth,
                origYear = inst.selectedYear,
                newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));

            inst.selectedDay = inst.currentDay = newDate.getDate();
            inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
            inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
            if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
                this._notifyChange(inst);
            }
            this._adjustInstDate(inst);
            if (inst.input) {
                inst.input.val(clear ? "" : this._formatDate(inst));
            }
        },

        /* Retrieve the date(s) directly. */
        _getDate: function(inst) {
            var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
                this._daylightSavingAdjust(new Date(
                    inst.currentYear, inst.currentMonth, inst.currentDay)));
            return startDate;
        },

        /* Attach the onxxx handlers.  These are declared statically so
         * they work with static code transformers like Caja.
         */
        _attachHandlers: function(inst) {
            var stepMonths = this._get(inst, "stepMonths"),
                id = "#" + inst.id.replace(/\\\\/g, "\\");
            inst.dpDiv.find("[data-handler]").map(function() {
                var handler = {
                    prev: function() {
                        $.datepicker._adjustDate(id, -stepMonths, "M");
                    },
                    next: function() {
                        $.datepicker._adjustDate(id, +stepMonths, "M");
                    },
                    hide: function() {
                        $.datepicker._hideDatepicker();
                    },
                    today: function() {
                        $.datepicker._gotoToday(id);
                    },
                    selectDay: function() {
                        $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
                        return false;
                    },
                    selectMonth: function() {
                        $.datepicker._selectMonthYear(id, this, "M");
                        return false;
                    },
                    selectYear: function() {
                        $.datepicker._selectMonthYear(id, this, "Y");
                        return false;
                    }
                };
                $(this).on(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
            });
        },

        /* Generate the HTML for the current state of the date picker. */
        _generateHTML: function(inst) {
            var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
                controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
                monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
                selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
                cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
                printDate, dRow, tbody, daySettings, otherMonth, unselectable,
                tempDate = new Date(),
                today = this._daylightSavingAdjust(
                    new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
                isRTL = this._get(inst, "isRTL"),
                showButtonPanel = this._get(inst, "showButtonPanel"),
                hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
                navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
                numMonths = this._getNumberOfMonths(inst),
                showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
                stepMonths = this._get(inst, "stepMonths"),
                isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
                currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
                    new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
                minDate = this._getMinMaxDate(inst, "min"),
                maxDate = this._getMinMaxDate(inst, "max"),
                drawMonth = inst.drawMonth - showCurrentAtPos,
                drawYear = inst.drawYear;

            if (drawMonth < 0) {
                drawMonth += 12;
                drawYear--;
            }
            if (maxDate) {
                maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
                    maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
                maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
                while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
                    drawMonth--;
                    if (drawMonth < 0) {
                        drawMonth = 11;
                        drawYear--;
                    }
                }
            }
            inst.drawMonth = drawMonth;
            inst.drawYear = drawYear;

            prevText = this._get(inst, "prevText");
            prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
                this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
                this._getFormatConfig(inst)));

            prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
                "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
                " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + (isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
                (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + (isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));

            nextText = this._get(inst, "nextText");
            nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
                this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
                this._getFormatConfig(inst)));

            next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
                "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
                " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + (isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
                (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + (isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));

            currentText = this._get(inst, "currentText");
            gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
            currentText = (!navigationAsDateFormat ? currentText :
                this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));

            controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
                this._get(inst, "closeText") + "</button>" : "");

            buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
                (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
                    ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";

            firstDay = parseInt(this._get(inst, "firstDay"), 10);
            firstDay = (isNaN(firstDay) ? 0 : firstDay);

            showWeek = this._get(inst, "showWeek");
            dayNames = this._get(inst, "dayNames");
            dayNamesMin = this._get(inst, "dayNamesMin");
            monthNames = this._get(inst, "monthNames");
            monthNamesShort = this._get(inst, "monthNamesShort");
            beforeShowDay = this._get(inst, "beforeShowDay");
            showOtherMonths = this._get(inst, "showOtherMonths");
            selectOtherMonths = this._get(inst, "selectOtherMonths");
            defaultDate = this._getDefaultDate(inst);
            html = "";

            for (row = 0; row < numMonths[0]; row++) {
                group = "";
                this.maxRows = 4;
                for (col = 0; col < numMonths[1]; col++) {
                    selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
                    cornerClass = " ui-corner-all";
                    calender = "";
                    if (isMultiMonth) {
                        calender += "<div class='ui-datepicker-group";
                        if (numMonths[1] > 1) {
                            switch (col) {
                                case 0:
                                    calender += " ui-datepicker-group-first";
                                    cornerClass = " ui-corner-" + (isRTL ? "right" : "left");
                                    break;
                                case numMonths[1] - 1:
                                    calender += " ui-datepicker-group-last";
                                    cornerClass = " ui-corner-" + (isRTL ? "left" : "right");
                                    break;
                                default:
                                    calender += " ui-datepicker-group-middle";
                                    cornerClass = "";
                                    break;
                            }
                        }
                        calender += "'>";
                    }
                    calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
                        (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
                        (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
                        this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
                            row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
                        "</div><table class='ui-datepicker-calendar'><thead>" +
                        "<tr>";
                    thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
                    for (dow = 0; dow < 7; dow++) { // days of the week
                        day = (dow + firstDay) % 7;
                        thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
                            "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
                    }
                    calender += thead + "</tr></thead><tbody>";
                    daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
                    if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
                        inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
                    }
                    leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
                    curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
                    numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
                    this.maxRows = numRows;
                    printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
                    for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
                        calender += "<tr>";
                        tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
                            this._get(inst, "calculateWeek")(printDate) + "</td>");
                        for (dow = 0; dow < 7; dow++) { // create date picker days
                            daySettings = (beforeShowDay ?
                                beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
                            otherMonth = (printDate.getMonth() !== drawMonth);
                            unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
                                (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
                            tbody += "<td class='" +
                                ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
                                (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
                                ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
                                    (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?

                                    // or defaultDate is current printedDate and defaultDate is selectedDate
                                    " " + this._dayOverClass : "") + // highlight selected day
                                (unselectable ? " " + this._unselectableClass + " ui-state-disabled" : "") + // highlight unselectable days
                                (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
                                    (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
                                    (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
                                ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title
                                (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
                                (otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months
                                    (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
                                        (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
                                        (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
                                        (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
                                        "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
                            printDate.setDate(printDate.getDate() + 1);
                            printDate = this._daylightSavingAdjust(printDate);
                        }
                        calender += tbody + "</tr>";
                    }
                    drawMonth++;
                    if (drawMonth > 11) {
                        drawMonth = 0;
                        drawYear++;
                    }
                    calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
                        ((numMonths[0] > 0 && col === numMonths[1] - 1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
                    group += calender;
                }
                html += group;
            }
            html += buttonPanel;
            inst._keyEvent = false;
            return html;
        },

        /* Generate the month and year header. */
        _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
            secondary, monthNames, monthNamesShort) {

            var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
                changeMonth = this._get(inst, "changeMonth"),
                changeYear = this._get(inst, "changeYear"),
                showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
                html = "<div class='ui-datepicker-title'>",
                monthHtml = "";

            // Month selection
            if (secondary || !changeMonth) {
                monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
            } else {
                inMinYear = (minDate && minDate.getFullYear() === drawYear);
                inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
                monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
                for (month = 0; month < 12; month++) {
                    if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
                        monthHtml += "<option value='" + month + "'" +
                            (month === drawMonth ? " selected='selected'" : "") +
                            ">" + monthNamesShort[month] + "</option>";
                    }
                }
                monthHtml += "</select>";
            }

            if (!showMonthAfterYear) {
                html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "");
            }

            // Year selection
            if (!inst.yearshtml) {
                inst.yearshtml = "";
                if (secondary || !changeYear) {
                    html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
                } else {

                    // determine range of years to display
                    years = this._get(inst, "yearRange").split(":");
                    thisYear = new Date().getFullYear();
                    determineYear = function(value) {
                        var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
                            (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
                                parseInt(value, 10)));
                        return (isNaN(year) ? thisYear : year);
                    };
                    year = determineYear(years[0]);
                    endYear = Math.max(year, determineYear(years[1] || ""));
                    year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
                    endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
                    inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
                    for (; year <= endYear; year++) {
                        inst.yearshtml += "<option value='" + year + "'" +
                            (year === drawYear ? " selected='selected'" : "") +
                            ">" + year + "</option>";
                    }
                    inst.yearshtml += "</select>";

                    html += inst.yearshtml;
                    inst.yearshtml = null;
                }
            }

            html += this._get(inst, "yearSuffix");
            if (showMonthAfterYear) {
                html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml;
            }
            html += "</div>"; // Close datepicker_header
            return html;
        },

        /* Adjust one of the date sub-fields. */
        _adjustInstDate: function(inst, offset, period) {
            var year = inst.selectedYear + (period === "Y" ? offset : 0),
                month = inst.selectedMonth + (period === "M" ? offset : 0),
                day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
                date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));

            inst.selectedDay = date.getDate();
            inst.drawMonth = inst.selectedMonth = date.getMonth();
            inst.drawYear = inst.selectedYear = date.getFullYear();
            if (period === "M" || period === "Y") {
                this._notifyChange(inst);
            }
        },

        /* Ensure a date is within any min/max bounds. */
        _restrictMinMax: function(inst, date) {
            var minDate = this._getMinMaxDate(inst, "min"),
                maxDate = this._getMinMaxDate(inst, "max"),
                newDate = (minDate && date < minDate ? minDate : date);
            return (maxDate && newDate > maxDate ? maxDate : newDate);
        },

        /* Notify change of month/year. */
        _notifyChange: function(inst) {
            var onChange = this._get(inst, "onChangeMonthYear");
            if (onChange) {
                onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]);
            }
        },

        /* Determine the number of months to show. */
        _getNumberOfMonths: function(inst) {
            var numMonths = this._get(inst, "numberOfMonths");
            return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
        },

        /* Determine the current maximum date - ensure no time components are set. */
        _getMinMaxDate: function(inst, minMax) {
            return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
        },

        /* Find the number of days in a given month. */
        _getDaysInMonth: function(year, month) {
            return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
        },

        /* Find the day of the week of the first of a month. */
        _getFirstDayOfMonth: function(year, month) {
            return new Date(year, month, 1).getDay();
        },

        /* Determines if we should allow a "next/prev" month display change. */
        _canAdjustMonth: function(inst, offset, curYear, curMonth) {
            var numMonths = this._getNumberOfMonths(inst),
                date = this._daylightSavingAdjust(new Date(curYear,
                    curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));

            if (offset < 0) {
                date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
            }
            return this._isInRange(inst, date);
        },

        /* Is the given date in the accepted range? */
        _isInRange: function(inst, date) {
            var yearSplit, currentYear,
                minDate = this._getMinMaxDate(inst, "min"),
                maxDate = this._getMinMaxDate(inst, "max"),
                minYear = null,
                maxYear = null,
                years = this._get(inst, "yearRange");
            if (years) {
                yearSplit = years.split(":");
                currentYear = new Date().getFullYear();
                minYear = parseInt(yearSplit[0], 10);
                maxYear = parseInt(yearSplit[1], 10);
                if (yearSplit[0].match(/[+\-].*/)) {
                    minYear += currentYear;
                }
                if (yearSplit[1].match(/[+\-].*/)) {
                    maxYear += currentYear;
                }
            }

            return ((!minDate || date.getTime() >= minDate.getTime()) &&
                (!maxDate || date.getTime() <= maxDate.getTime()) &&
                (!minYear || date.getFullYear() >= minYear) &&
                (!maxYear || date.getFullYear() <= maxYear));
        },

        /* Provide the configuration settings for formatting/parsing. */
        _getFormatConfig: function(inst) {
            var shortYearCutoff = this._get(inst, "shortYearCutoff");
            shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
                new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
            return {
                shortYearCutoff: shortYearCutoff,
                dayNamesShort: this._get(inst, "dayNamesShort"),
                dayNames: this._get(inst, "dayNames"),
                monthNamesShort: this._get(inst, "monthNamesShort"),
                monthNames: this._get(inst, "monthNames")
            };
        },

        /* Format the given date for display. */
        _formatDate: function(inst, day, month, year) {
            if (!day) {
                inst.currentDay = inst.selectedDay;
                inst.currentMonth = inst.selectedMonth;
                inst.currentYear = inst.selectedYear;
            }
            var date = (day ? (typeof day === "object" ? day :
                    this._daylightSavingAdjust(new Date(year, month, day))) :
                this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
            return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
        }
    });

    /*
     * Bind hover events for datepicker elements.
     * Done via delegate so the binding only occurs once in the lifetime of the parent div.
     * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
     */
    function datepicker_bindHover(dpDiv) {
        var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
        return dpDiv.on("mouseout", selector, function() {
                $(this).removeClass("ui-state-hover");
                if (this.className.indexOf("ui-datepicker-prev") !== -1) {
                    $(this).removeClass("ui-datepicker-prev-hover");
                }
                if (this.className.indexOf("ui-datepicker-next") !== -1) {
                    $(this).removeClass("ui-datepicker-next-hover");
                }
            })
            .on("mouseover", selector, datepicker_handleMouseover);
    }

    function datepicker_handleMouseover() {
        if (!$.datepicker._isDisabledDatepicker(datepicker_instActive.inline ? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) {
            $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
            $(this).addClass("ui-state-hover");
            if (this.className.indexOf("ui-datepicker-prev") !== -1) {
                $(this).addClass("ui-datepicker-prev-hover");
            }
            if (this.className.indexOf("ui-datepicker-next") !== -1) {
                $(this).addClass("ui-datepicker-next-hover");
            }
        }
    }

    /* jQuery extend now ignores nulls! */
    function datepicker_extendRemove(target, props) {
        $.extend(target, props);
        for (var name in props) {
            if (props[name] == null) {
                target[name] = props[name];
            }
        }
        return target;
    }

    /* Invoke the datepicker functionality.
       @param  options  string - a command, optionally followed by additional parameters or
    					Object - settings for attaching new datepicker functionality
       @return  jQuery object */
    $.fn.datepicker = function(options) {

        /* Verify an empty collection wasn't passed - Fixes #6976 */
        if (!this.length) {
            return this;
        }

        /* Initialise the date picker. */
        if (!$.datepicker.initialized) {
            $(document).on("mousedown", $.datepicker._checkExternalClick);
            $.datepicker.initialized = true;
        }

        /* Append datepicker main container to body if not exist. */
        if ($("#" + $.datepicker._mainDivId).length === 0) {
            $("body").append($.datepicker.dpDiv);
        }

        var otherArgs = Array.prototype.slice.call(arguments, 1);
        if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
            return $.datepicker["_" + options + "Datepicker"].
            apply($.datepicker, [this[0]].concat(otherArgs));
        }
        if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
            return $.datepicker["_" + options + "Datepicker"].
            apply($.datepicker, [this[0]].concat(otherArgs));
        }
        return this.each(function() {
            typeof options === "string" ?
                $.datepicker["_" + options + "Datepicker"].
            apply($.datepicker, [this].concat(otherArgs)):
                $.datepicker._attachDatepicker(this, options);
        });
    };

    $.datepicker = new Datepicker(); // singleton instance
    $.datepicker.initialized = false;
    $.datepicker.uuid = new Date().getTime();
    $.datepicker.version = "1.12.1";

    var widgetsDatepicker = $.datepicker;


    /*!
     * jQuery UI Dialog 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Dialog
    //>>group: Widgets
    //>>description: Displays customizable dialog windows.
    //>>docs: http://api.jqueryui.com/dialog/
    //>>demos: http://jqueryui.com/dialog/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/dialog.css
    //>>css.theme: ../../themes/base/theme.css



    $.widget("ui.dialog", {
        version: "1.12.1",
        options: {
            appendTo: "body",
            autoOpen: true,
            buttons: [],
            classes: {
                "ui-dialog": "ui-corner-all",
                "ui-dialog-titlebar": "ui-corner-all"
            },
            closeOnEscape: true,
            closeText: "Close",
            draggable: true,
            hide: null,
            height: "auto",
            maxHeight: null,
            maxWidth: null,
            minHeight: 150,
            minWidth: 150,
            modal: false,
            position: {
                my: "center",
                at: "center",
                of: window,
                collision: "fit",

                // Ensure the titlebar is always visible
                using: function(pos) {
                    var topOffset = $(this).css(pos).offset().top;
                    if (topOffset < 0) {
                        $(this).css("top", pos.top - topOffset);
                    }
                }
            },
            resizable: true,
            show: null,
            title: null,
            width: 300,

            // Callbacks
            beforeClose: null,
            close: null,
            drag: null,
            dragStart: null,
            dragStop: null,
            focus: null,
            open: null,
            resize: null,
            resizeStart: null,
            resizeStop: null
        },

        sizeRelatedOptions: {
            buttons: true,
            height: true,
            maxHeight: true,
            maxWidth: true,
            minHeight: true,
            minWidth: true,
            width: true
        },

        resizableRelatedOptions: {
            maxHeight: true,
            maxWidth: true,
            minHeight: true,
            minWidth: true
        },

        _create: function() {
            this.originalCss = {
                display: this.element[0].style.display,
                width: this.element[0].style.width,
                minHeight: this.element[0].style.minHeight,
                maxHeight: this.element[0].style.maxHeight,
                height: this.element[0].style.height
            };
            this.originalPosition = {
                parent: this.element.parent(),
                index: this.element.parent().children().index(this.element)
            };
            this.originalTitle = this.element.attr("title");
            if (this.options.title == null && this.originalTitle != null) {
                this.options.title = this.originalTitle;
            }

            // Dialogs can't be disabled
            if (this.options.disabled) {
                this.options.disabled = false;
            }

            this._createWrapper();

            this.element
                .show()
                .removeAttr("title")
                .appendTo(this.uiDialog);

            this._addClass("ui-dialog-content", "ui-widget-content");

            this._createTitlebar();
            this._createButtonPane();

            if (this.options.draggable && $.fn.draggable) {
                this._makeDraggable();
            }
            if (this.options.resizable && $.fn.resizable) {
                this._makeResizable();
            }

            this._isOpen = false;

            this._trackFocus();
        },

        _init: function() {
            if (this.options.autoOpen) {
                this.open();
            }
        },

        _appendTo: function() {
            var element = this.options.appendTo;
            if (element && (element.jquery || element.nodeType)) {
                return $(element);
            }
            return this.document.find(element || "body").eq(0);
        },

        _destroy: function() {
            var next,
                originalPosition = this.originalPosition;

            this._untrackInstance();
            this._destroyOverlay();

            this.element
                .removeUniqueId()
                .css(this.originalCss)

            // Without detaching first, the following becomes really slow
            .detach();

            this.uiDialog.remove();

            if (this.originalTitle) {
                this.element.attr("title", this.originalTitle);
            }

            next = originalPosition.parent.children().eq(originalPosition.index);

            // Don't try to place the dialog next to itself (#8613)
            if (next.length && next[0] !== this.element[0]) {
                next.before(this.element);
            } else {
                originalPosition.parent.append(this.element);
            }
        },

        widget: function() {
            return this.uiDialog;
        },

        disable: $.noop,
        enable: $.noop,

        close: function(event) {
            var that = this;

            if (!this._isOpen || this._trigger("beforeClose", event) === false) {
                return;
            }

            this._isOpen = false;
            this._focusedElement = null;
            this._destroyOverlay();
            this._untrackInstance();

            if (!this.opener.filter(":focusable").trigger("focus").length) {

                // Hiding a focused element doesn't trigger blur in WebKit
                // so in case we have nothing to focus on, explicitly blur the active element
                // https://bugs.webkit.org/show_bug.cgi?id=47182
                $.ui.safeBlur($.ui.safeActiveElement(this.document[0]));
            }

            this._hide(this.uiDialog, this.options.hide, function() {
                that._trigger("close", event);
            });
        },

        isOpen: function() {
            return this._isOpen;
        },

        moveToTop: function() {
            this._moveToTop();
        },

        _moveToTop: function(event, silent) {
            var moved = false,
                zIndices = this.uiDialog.siblings(".ui-front:visible").map(function() {
                    return +$(this).css("z-index");
                }).get(),
                zIndexMax = Math.max.apply(null, zIndices);

            if (zIndexMax >= +this.uiDialog.css("z-index")) {
                this.uiDialog.css("z-index", zIndexMax + 1);
                moved = true;
            }

            if (moved && !silent) {
                this._trigger("focus", event);
            }
            return moved;
        },

        open: function() {
            var that = this;
            if (this._isOpen) {
                if (this._moveToTop()) {
                    this._focusTabbable();
                }
                return;
            }

            this._isOpen = true;
            this.opener = $($.ui.safeActiveElement(this.document[0]));

            this._size();
            this._position();
            this._createOverlay();
            this._moveToTop(null, true);

            // Ensure the overlay is moved to the top with the dialog, but only when
            // opening. The overlay shouldn't move after the dialog is open so that
            // modeless dialogs opened after the modal dialog stack properly.
            if (this.overlay) {
                this.overlay.css("z-index", this.uiDialog.css("z-index") - 1);
            }

            this._show(this.uiDialog, this.options.show, function() {
                that._focusTabbable();
                that._trigger("focus");
            });

            // Track the dialog immediately upon openening in case a focus event
            // somehow occurs outside of the dialog before an element inside the
            // dialog is focused (#10152)
            this._makeFocusTarget();

            this._trigger("open");
        },

        _focusTabbable: function() {

            // Set focus to the first match:
            // 1. An element that was focused previously
            // 2. First element inside the dialog matching [autofocus]
            // 3. Tabbable element inside the content element
            // 4. Tabbable element inside the buttonpane
            // 5. The close button
            // 6. The dialog itself
            var hasFocus = this._focusedElement;
            if (!hasFocus) {
                hasFocus = this.element.find("[autofocus]");
            }
            if (!hasFocus.length) {
                hasFocus = this.element.find(":tabbable");
            }
            if (!hasFocus.length) {
                hasFocus = this.uiDialogButtonPane.find(":tabbable");
            }
            if (!hasFocus.length) {
                hasFocus = this.uiDialogTitlebarClose.filter(":tabbable");
            }
            if (!hasFocus.length) {
                hasFocus = this.uiDialog;
            }
            hasFocus.eq(0).trigger("focus");
        },

        _keepFocus: function(event) {
            function checkFocus() {
                var activeElement = $.ui.safeActiveElement(this.document[0]),
                    isActive = this.uiDialog[0] === activeElement ||
                    $.contains(this.uiDialog[0], activeElement);
                if (!isActive) {
                    this._focusTabbable();
                }
            }
            event.preventDefault();
            checkFocus.call(this);

            // support: IE
            // IE <= 8 doesn't prevent moving focus even with event.preventDefault()
            // so we check again later
            this._delay(checkFocus);
        },

        _createWrapper: function() {
            this.uiDialog = $("<div>")
                .hide()
                .attr({

                    // Setting tabIndex makes the div focusable
                    tabIndex: -1,
                    role: "dialog"
                })
                .appendTo(this._appendTo());

            this._addClass(this.uiDialog, "ui-dialog", "ui-widget ui-widget-content ui-front");
            this._on(this.uiDialog, {
                keydown: function(event) {
                    if (this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
                        event.keyCode === $.ui.keyCode.ESCAPE) {
                        event.preventDefault();
                        this.close(event);
                        return;
                    }

                    // Prevent tabbing out of dialogs
                    if (event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented()) {
                        return;
                    }
                    var tabbables = this.uiDialog.find(":tabbable"),
                        first = tabbables.filter(":first"),
                        last = tabbables.filter(":last");

                    if ((event.target === last[0] || event.target === this.uiDialog[0]) &&
                        !event.shiftKey) {
                        this._delay(function() {
                            first.trigger("focus");
                        });
                        event.preventDefault();
                    } else if ((event.target === first[0] ||
                            event.target === this.uiDialog[0]) && event.shiftKey) {
                        this._delay(function() {
                            last.trigger("focus");
                        });
                        event.preventDefault();
                    }
                },
                mousedown: function(event) {
                    if (this._moveToTop(event)) {
                        this._focusTabbable();
                    }
                }
            });

            // We assume that any existing aria-describedby attribute means
            // that the dialog content is marked up properly
            // otherwise we brute force the content as the description
            if (!this.element.find("[aria-describedby]").length) {
                this.uiDialog.attr({
                    "aria-describedby": this.element.uniqueId().attr("id")
                });
            }
        },

        _createTitlebar: function() {
            var uiDialogTitle;

            this.uiDialogTitlebar = $("<div>");
            this._addClass(this.uiDialogTitlebar,
                "ui-dialog-titlebar", "ui-widget-header ui-helper-clearfix");
            this._on(this.uiDialogTitlebar, {
                mousedown: function(event) {

                    // Don't prevent click on close button (#8838)
                    // Focusing a dialog that is partially scrolled out of view
                    // causes the browser to scroll it into view, preventing the click event
                    if (!$(event.target).closest(".ui-dialog-titlebar-close")) {

                        // Dialog isn't getting focus when dragging (#8063)
                        this.uiDialog.trigger("focus");
                    }
                }
            });

            // Support: IE
            // Use type="button" to prevent enter keypresses in textboxes from closing the
            // dialog in IE (#9312)
            this.uiDialogTitlebarClose = $("<button type='button'></button>")
                .button({
                    label: $("<a>").text(this.options.closeText).html(),
                    icon: "ui-icon-closethick",
                    showLabel: false
                })
                .appendTo(this.uiDialogTitlebar);

            this._addClass(this.uiDialogTitlebarClose, "ui-dialog-titlebar-close");
            this._on(this.uiDialogTitlebarClose, {
                click: function(event) {
                    event.preventDefault();
                    this.close(event);
                }
            });

            uiDialogTitle = $("<span>").uniqueId().prependTo(this.uiDialogTitlebar);
            this._addClass(uiDialogTitle, "ui-dialog-title");
            this._title(uiDialogTitle);

            this.uiDialogTitlebar.prependTo(this.uiDialog);

            this.uiDialog.attr({
                "aria-labelledby": uiDialogTitle.attr("id")
            });
        },

        _title: function(title) {
            if (this.options.title) {
                title.text(this.options.title);
            } else {
                title.html("&#160;");
            }
        },

        _createButtonPane: function() {
            this.uiDialogButtonPane = $("<div>");
            this._addClass(this.uiDialogButtonPane, "ui-dialog-buttonpane",
                "ui-widget-content ui-helper-clearfix");

            this.uiButtonSet = $("<div>")
                .appendTo(this.uiDialogButtonPane);
            this._addClass(this.uiButtonSet, "ui-dialog-buttonset");

            this._createButtons();
        },

        _createButtons: function() {
            var that = this,
                buttons = this.options.buttons;

            // If we already have a button pane, remove it
            this.uiDialogButtonPane.remove();
            this.uiButtonSet.empty();

            if ($.isEmptyObject(buttons) || ($.isArray(buttons) && !buttons.length)) {
                this._removeClass(this.uiDialog, "ui-dialog-buttons");
                return;
            }

            $.each(buttons, function(name, props) {
                var click, buttonOptions;
                props = $.isFunction(props) ? { click: props, text: name } :
                    props;

                // Default to a non-submitting button
                props = $.extend({ type: "button" }, props);

                // Change the context for the click callback to be the main element
                click = props.click;
                buttonOptions = {
                    icon: props.icon,
                    iconPosition: props.iconPosition,
                    showLabel: props.showLabel,

                    // Deprecated options
                    icons: props.icons,
                    text: props.text
                };

                delete props.click;
                delete props.icon;
                delete props.iconPosition;
                delete props.showLabel;

                // Deprecated options
                delete props.icons;
                if (typeof props.text === "boolean") {
                    delete props.text;
                }

                $("<button></button>", props)
                    .button(buttonOptions)
                    .appendTo(that.uiButtonSet)
                    .on("click", function() {
                        click.apply(that.element[0], arguments);
                    });
            });
            this._addClass(this.uiDialog, "ui-dialog-buttons");
            this.uiDialogButtonPane.appendTo(this.uiDialog);
        },

        _makeDraggable: function() {
            var that = this,
                options = this.options;

            function filteredUi(ui) {
                return {
                    position: ui.position,
                    offset: ui.offset
                };
            }

            this.uiDialog.draggable({
                cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
                handle: ".ui-dialog-titlebar",
                containment: "document",
                start: function(event, ui) {
                    that._addClass($(this), "ui-dialog-dragging");
                    that._blockFrames();
                    that._trigger("dragStart", event, filteredUi(ui));
                },
                drag: function(event, ui) {
                    that._trigger("drag", event, filteredUi(ui));
                },
                stop: function(event, ui) {
                    var left = ui.offset.left - that.document.scrollLeft(),
                        top = ui.offset.top - that.document.scrollTop();

                    options.position = {
                        my: "left top",
                        at: "left" + (left >= 0 ? "+" : "") + left + " " +
                            "top" + (top >= 0 ? "+" : "") + top,
                        of: that.window
                    };
                    that._removeClass($(this), "ui-dialog-dragging");
                    that._unblockFrames();
                    that._trigger("dragStop", event, filteredUi(ui));
                }
            });
        },

        _makeResizable: function() {
            var that = this,
                options = this.options,
                handles = options.resizable,

                // .ui-resizable has position: relative defined in the stylesheet
                // but dialogs have to use absolute or fixed positioning
                position = this.uiDialog.css("position"),
                resizeHandles = typeof handles === "string" ?
                handles :
                "n,e,s,w,se,sw,ne,nw";

            function filteredUi(ui) {
                return {
                    originalPosition: ui.originalPosition,
                    originalSize: ui.originalSize,
                    position: ui.position,
                    size: ui.size
                };
            }

            this.uiDialog.resizable({
                    cancel: ".ui-dialog-content",
                    containment: "document",
                    alsoResize: this.element,
                    maxWidth: options.maxWidth,
                    maxHeight: options.maxHeight,
                    minWidth: options.minWidth,
                    minHeight: this._minHeight(),
                    handles: resizeHandles,
                    start: function(event, ui) {
                        that._addClass($(this), "ui-dialog-resizing");
                        that._blockFrames();
                        that._trigger("resizeStart", event, filteredUi(ui));
                    },
                    resize: function(event, ui) {
                        that._trigger("resize", event, filteredUi(ui));
                    },
                    stop: function(event, ui) {
                        var offset = that.uiDialog.offset(),
                            left = offset.left - that.document.scrollLeft(),
                            top = offset.top - that.document.scrollTop();

                        options.height = that.uiDialog.height();
                        options.width = that.uiDialog.width();
                        options.position = {
                            my: "left top",
                            at: "left" + (left >= 0 ? "+" : "") + left + " " +
                                "top" + (top >= 0 ? "+" : "") + top,
                            of: that.window
                        };
                        that._removeClass($(this), "ui-dialog-resizing");
                        that._unblockFrames();
                        that._trigger("resizeStop", event, filteredUi(ui));
                    }
                })
                .css("position", position);
        },

        _trackFocus: function() {
            this._on(this.widget(), {
                focusin: function(event) {
                    this._makeFocusTarget();
                    this._focusedElement = $(event.target);
                }
            });
        },

        _makeFocusTarget: function() {
            this._untrackInstance();
            this._trackingInstances().unshift(this);
        },

        _untrackInstance: function() {
            var instances = this._trackingInstances(),
                exists = $.inArray(this, instances);
            if (exists !== -1) {
                instances.splice(exists, 1);
            }
        },

        _trackingInstances: function() {
            var instances = this.document.data("ui-dialog-instances");
            if (!instances) {
                instances = [];
                this.document.data("ui-dialog-instances", instances);
            }
            return instances;
        },

        _minHeight: function() {
            var options = this.options;

            return options.height === "auto" ?
                options.minHeight :
                Math.min(options.minHeight, options.height);
        },

        _position: function() {

            // Need to show the dialog to get the actual offset in the position plugin
            var isVisible = this.uiDialog.is(":visible");
            if (!isVisible) {
                this.uiDialog.show();
            }
            this.uiDialog.position(this.options.position);
            if (!isVisible) {
                this.uiDialog.hide();
            }
        },

        _setOptions: function(options) {
            var that = this,
                resize = false,
                resizableOptions = {};

            $.each(options, function(key, value) {
                that._setOption(key, value);

                if (key in that.sizeRelatedOptions) {
                    resize = true;
                }
                if (key in that.resizableRelatedOptions) {
                    resizableOptions[key] = value;
                }
            });

            if (resize) {
                this._size();
                this._position();
            }
            if (this.uiDialog.is(":data(ui-resizable)")) {
                this.uiDialog.resizable("option", resizableOptions);
            }
        },

        _setOption: function(key, value) {
            var isDraggable, isResizable,
                uiDialog = this.uiDialog;

            if (key === "disabled") {
                return;
            }

            this._super(key, value);

            if (key === "appendTo") {
                this.uiDialog.appendTo(this._appendTo());
            }

            if (key === "buttons") {
                this._createButtons();
            }

            if (key === "closeText") {
                this.uiDialogTitlebarClose.button({

                    // Ensure that we always pass a string
                    label: $("<a>").text("" + this.options.closeText).html()
                });
            }

            if (key === "draggable") {
                isDraggable = uiDialog.is(":data(ui-draggable)");
                if (isDraggable && !value) {
                    uiDialog.draggable("destroy");
                }

                if (!isDraggable && value) {
                    this._makeDraggable();
                }
            }

            if (key === "position") {
                this._position();
            }

            if (key === "resizable") {

                // currently resizable, becoming non-resizable
                isResizable = uiDialog.is(":data(ui-resizable)");
                if (isResizable && !value) {
                    uiDialog.resizable("destroy");
                }

                // Currently resizable, changing handles
                if (isResizable && typeof value === "string") {
                    uiDialog.resizable("option", "handles", value);
                }

                // Currently non-resizable, becoming resizable
                if (!isResizable && value !== false) {
                    this._makeResizable();
                }
            }

            if (key === "title") {
                this._title(this.uiDialogTitlebar.find(".ui-dialog-title"));
            }
        },

        _size: function() {

            // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
            // divs will both have width and height set, so we need to reset them
            var nonContentHeight, minContentHeight, maxContentHeight,
                options = this.options;

            // Reset content sizing
            this.element.show().css({
                width: "auto",
                minHeight: 0,
                maxHeight: "none",
                height: 0
            });

            if (options.minWidth > options.width) {
                options.width = options.minWidth;
            }

            // Reset wrapper sizing
            // determine the height of all the non-content elements
            nonContentHeight = this.uiDialog.css({
                    height: "auto",
                    width: options.width
                })
                .outerHeight();
            minContentHeight = Math.max(0, options.minHeight - nonContentHeight);
            maxContentHeight = typeof options.maxHeight === "number" ?
                Math.max(0, options.maxHeight - nonContentHeight) :
                "none";

            if (options.height === "auto") {
                this.element.css({
                    minHeight: minContentHeight,
                    maxHeight: maxContentHeight,
                    height: "auto"
                });
            } else {
                this.element.height(Math.max(0, options.height - nonContentHeight));
            }

            if (this.uiDialog.is(":data(ui-resizable)")) {
                this.uiDialog.resizable("option", "minHeight", this._minHeight());
            }
        },

        _blockFrames: function() {
            this.iframeBlocks = this.document.find("iframe").map(function() {
                var iframe = $(this);

                return $("<div>")
                    .css({
                        position: "absolute",
                        width: iframe.outerWidth(),
                        height: iframe.outerHeight()
                    })
                    .appendTo(iframe.parent())
                    .offset(iframe.offset())[0];
            });
        },

        _unblockFrames: function() {
            if (this.iframeBlocks) {
                this.iframeBlocks.remove();
                delete this.iframeBlocks;
            }
        },

        _allowInteraction: function(event) {
            if ($(event.target).closest(".ui-dialog").length) {
                return true;
            }

            // TODO: Remove hack when datepicker implements
            // the .ui-front logic (#8989)
            return !!$(event.target).closest(".ui-datepicker").length;
        },

        _createOverlay: function() {
            if (!this.options.modal) {
                return;
            }

            // We use a delay in case the overlay is created from an
            // event that we're going to be cancelling (#2804)
            var isOpening = true;
            this._delay(function() {
                isOpening = false;
            });

            if (!this.document.data("ui-dialog-overlays")) {

                // Prevent use of anchors and inputs
                // Using _on() for an event handler shared across many instances is
                // safe because the dialogs stack and must be closed in reverse order
                this._on(this.document, {
                    focusin: function(event) {
                        if (isOpening) {
                            return;
                        }

                        if (!this._allowInteraction(event)) {
                            event.preventDefault();
                            this._trackingInstances()[0]._focusTabbable();
                        }
                    }
                });
            }

            this.overlay = $("<div>")
                .appendTo(this._appendTo());

            this._addClass(this.overlay, null, "ui-widget-overlay ui-front");
            this._on(this.overlay, {
                mousedown: "_keepFocus"
            });
            this.document.data("ui-dialog-overlays",
                (this.document.data("ui-dialog-overlays") || 0) + 1);
        },

        _destroyOverlay: function() {
            if (!this.options.modal) {
                return;
            }

            if (this.overlay) {
                var overlays = this.document.data("ui-dialog-overlays") - 1;

                if (!overlays) {
                    this._off(this.document, "focusin");
                    this.document.removeData("ui-dialog-overlays");
                } else {
                    this.document.data("ui-dialog-overlays", overlays);
                }

                this.overlay.remove();
                this.overlay = null;
            }
        }
    });

    // DEPRECATED
    // TODO: switch return back to widget declaration at top of file when this is removed
    if ($.uiBackCompat !== false) {

        // Backcompat for dialogClass option
        $.widget("ui.dialog", $.ui.dialog, {
            options: {
                dialogClass: ""
            },
            _createWrapper: function() {
                this._super();
                this.uiDialog.addClass(this.options.dialogClass);
            },
            _setOption: function(key, value) {
                if (key === "dialogClass") {
                    this.uiDialog
                        .removeClass(this.options.dialogClass)
                        .addClass(value);
                }
                this._superApply(arguments);
            }
        });
    }

    var widgetsDialog = $.ui.dialog;


    /*!
     * jQuery UI Progressbar 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Progressbar
    //>>group: Widgets
    // jscs:disable maximumLineLength
    //>>description: Displays a status indicator for loading state, standard percentage, and other progress indicators.
    // jscs:enable maximumLineLength
    //>>docs: http://api.jqueryui.com/progressbar/
    //>>demos: http://jqueryui.com/progressbar/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/progressbar.css
    //>>css.theme: ../../themes/base/theme.css



    var widgetsProgressbar = $.widget("ui.progressbar", {
        version: "1.12.1",
        options: {
            classes: {
                "ui-progressbar": "ui-corner-all",
                "ui-progressbar-value": "ui-corner-left",
                "ui-progressbar-complete": "ui-corner-right"
            },
            max: 100,
            value: 0,

            change: null,
            complete: null
        },

        min: 0,

        _create: function() {

            // Constrain initial value
            this.oldValue = this.options.value = this._constrainedValue();

            this.element.attr({

                // Only set static values; aria-valuenow and aria-valuemax are
                // set inside _refreshValue()
                role: "progressbar",
                "aria-valuemin": this.min
            });
            this._addClass("ui-progressbar", "ui-widget ui-widget-content");

            this.valueDiv = $("<div>").appendTo(this.element);
            this._addClass(this.valueDiv, "ui-progressbar-value", "ui-widget-header");
            this._refreshValue();
        },

        _destroy: function() {
            this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow");

            this.valueDiv.remove();
        },

        value: function(newValue) {
            if (newValue === undefined) {
                return this.options.value;
            }

            this.options.value = this._constrainedValue(newValue);
            this._refreshValue();
        },

        _constrainedValue: function(newValue) {
            if (newValue === undefined) {
                newValue = this.options.value;
            }

            this.indeterminate = newValue === false;

            // Sanitize value
            if (typeof newValue !== "number") {
                newValue = 0;
            }

            return this.indeterminate ? false :
                Math.min(this.options.max, Math.max(this.min, newValue));
        },

        _setOptions: function(options) {

            // Ensure "value" option is set after other values (like max)
            var value = options.value;
            delete options.value;

            this._super(options);

            this.options.value = this._constrainedValue(value);
            this._refreshValue();
        },

        _setOption: function(key, value) {
            if (key === "max") {

                // Don't allow a max less than min
                value = Math.max(this.min, value);
            }
            this._super(key, value);
        },

        _setOptionDisabled: function(value) {
            this._super(value);

            this.element.attr("aria-disabled", value);
            this._toggleClass(null, "ui-state-disabled", !!value);
        },

        _percentage: function() {
            return this.indeterminate ?
                100 :
                100 * (this.options.value - this.min) / (this.options.max - this.min);
        },

        _refreshValue: function() {
            var value = this.options.value,
                percentage = this._percentage();

            this.valueDiv
                .toggle(this.indeterminate || value > this.min)
                .width(percentage.toFixed(0) + "%");

            this
                ._toggleClass(this.valueDiv, "ui-progressbar-complete", null,
                    value === this.options.max)
                ._toggleClass("ui-progressbar-indeterminate", null, this.indeterminate);

            if (this.indeterminate) {
                this.element.removeAttr("aria-valuenow");
                if (!this.overlayDiv) {
                    this.overlayDiv = $("<div>").appendTo(this.valueDiv);
                    this._addClass(this.overlayDiv, "ui-progressbar-overlay");
                }
            } else {
                this.element.attr({
                    "aria-valuemax": this.options.max,
                    "aria-valuenow": value
                });
                if (this.overlayDiv) {
                    this.overlayDiv.remove();
                    this.overlayDiv = null;
                }
            }

            if (this.oldValue !== value) {
                this.oldValue = value;
                this._trigger("change");
            }
            if (value === this.options.max) {
                this._trigger("complete");
            }
        }
    });


    /*!
     * jQuery UI Selectmenu 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Selectmenu
    //>>group: Widgets
    // jscs:disable maximumLineLength
    //>>description: Duplicates and extends the functionality of a native HTML select element, allowing it to be customizable in behavior and appearance far beyond the limitations of a native select.
    // jscs:enable maximumLineLength
    //>>docs: http://api.jqueryui.com/selectmenu/
    //>>demos: http://jqueryui.com/selectmenu/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/selectmenu.css, ../../themes/base/button.css
    //>>css.theme: ../../themes/base/theme.css



    var widgetsSelectmenu = $.widget("ui.selectmenu", [$.ui.formResetMixin, {
        version: "1.12.1",
        defaultElement: "<select>",
        options: {
            appendTo: null,
            classes: {
                "ui-selectmenu-button-open": "ui-corner-top",
                "ui-selectmenu-button-closed": "ui-corner-all"
            },
            disabled: null,
            icons: {
                button: "ui-icon-triangle-1-s"
            },
            position: {
                my: "left top",
                at: "left bottom",
                collision: "none"
            },
            width: false,

            // Callbacks
            change: null,
            close: null,
            focus: null,
            open: null,
            select: null
        },

        _create: function() {
            var selectmenuId = this.element.uniqueId().attr("id");
            this.ids = {
                element: selectmenuId,
                button: selectmenuId + "-button",
                menu: selectmenuId + "-menu"
            };

            this._drawButton();
            this._drawMenu();
            this._bindFormResetHandler();

            this._rendered = false;
            this.menuItems = $();
        },

        _drawButton: function() {
            var icon,
                that = this,
                item = this._parseOption(
                    this.element.find("option:selected"),
                    this.element[0].selectedIndex
                );

            // Associate existing label with the new button
            this.labels = this.element.labels().attr("for", this.ids.button);
            this._on(this.labels, {
                click: function(event) {
                    this.button.focus();
                    event.preventDefault();
                }
            });

            // Hide original select element
            this.element.hide();

            // Create button
            this.button = $("<span>", {
                    tabindex: this.options.disabled ? -1 : 0,
                    id: this.ids.button,
                    role: "combobox",
                    "aria-expanded": "false",
                    "aria-autocomplete": "list",
                    "aria-owns": this.ids.menu,
                    "aria-haspopup": "true",
                    title: this.element.attr("title")
                })
                .insertAfter(this.element);

            this._addClass(this.button, "ui-selectmenu-button ui-selectmenu-button-closed",
                "ui-button ui-widget");

            icon = $("<span>").appendTo(this.button);
            this._addClass(icon, "ui-selectmenu-icon", "ui-icon " + this.options.icons.button);
            this.buttonItem = this._renderButtonItem(item)
                .appendTo(this.button);

            if (this.options.width !== false) {
                this._resizeButton();
            }

            this._on(this.button, this._buttonEvents);
            this.button.one("focusin", function() {

                // Delay rendering the menu items until the button receives focus.
                // The menu may have already been rendered via a programmatic open.
                if (!that._rendered) {
                    that._refreshMenu();
                }
            });
        },

        _drawMenu: function() {
            var that = this;

            // Create menu
            this.menu = $("<ul>", {
                "aria-hidden": "true",
                "aria-labelledby": this.ids.button,
                id: this.ids.menu
            });

            // Wrap menu
            this.menuWrap = $("<div>").append(this.menu);
            this._addClass(this.menuWrap, "ui-selectmenu-menu", "ui-front");
            this.menuWrap.appendTo(this._appendTo());

            // Initialize menu widget
            this.menuInstance = this.menu
                .menu({
                    classes: {
                        "ui-menu": "ui-corner-bottom"
                    },
                    role: "listbox",
                    select: function(event, ui) {
                        event.preventDefault();

                        // Support: IE8
                        // If the item was selected via a click, the text selection
                        // will be destroyed in IE
                        that._setSelection();

                        that._select(ui.item.data("ui-selectmenu-item"), event);
                    },
                    focus: function(event, ui) {
                        var item = ui.item.data("ui-selectmenu-item");

                        // Prevent inital focus from firing and check if its a newly focused item
                        if (that.focusIndex != null && item.index !== that.focusIndex) {
                            that._trigger("focus", event, { item: item });
                            if (!that.isOpen) {
                                that._select(item, event);
                            }
                        }
                        that.focusIndex = item.index;

                        that.button.attr("aria-activedescendant",
                            that.menuItems.eq(item.index).attr("id"));
                    }
                })
                .menu("instance");

            // Don't close the menu on mouseleave
            this.menuInstance._off(this.menu, "mouseleave");

            // Cancel the menu's collapseAll on document click
            this.menuInstance._closeOnDocumentClick = function() {
                return false;
            };

            // Selects often contain empty items, but never contain dividers
            this.menuInstance._isDivider = function() {
                return false;
            };
        },

        refresh: function() {
            this._refreshMenu();
            this.buttonItem.replaceWith(
                this.buttonItem = this._renderButtonItem(

                    // Fall back to an empty object in case there are no options
                    this._getSelectedItem().data("ui-selectmenu-item") || {}
                )
            );
            if (this.options.width === null) {
                this._resizeButton();
            }
        },

        _refreshMenu: function() {
            var item,
                options = this.element.find("option");

            this.menu.empty();

            this._parseOptions(options);
            this._renderMenu(this.menu, this.items);

            this.menuInstance.refresh();
            this.menuItems = this.menu.find("li")
                .not(".ui-selectmenu-optgroup")
                .find(".ui-menu-item-wrapper");

            this._rendered = true;

            if (!options.length) {
                return;
            }

            item = this._getSelectedItem();

            // Update the menu to have the correct item focused
            this.menuInstance.focus(null, item);
            this._setAria(item.data("ui-selectmenu-item"));

            // Set disabled state
            this._setOption("disabled", this.element.prop("disabled"));
        },

        open: function(event) {
            if (this.options.disabled) {
                return;
            }

            // If this is the first time the menu is being opened, render the items
            if (!this._rendered) {
                this._refreshMenu();
            } else {

                // Menu clears focus on close, reset focus to selected item
                this._removeClass(this.menu.find(".ui-state-active"), null, "ui-state-active");
                this.menuInstance.focus(null, this._getSelectedItem());
            }

            // If there are no options, don't open the menu
            if (!this.menuItems.length) {
                return;
            }

            this.isOpen = true;
            this._toggleAttr();
            this._resizeMenu();
            this._position();

            this._on(this.document, this._documentClick);

            this._trigger("open", event);
        },

        _position: function() {
            this.menuWrap.position($.extend({ of: this.button }, this.options.position));
        },

        close: function(event) {
            if (!this.isOpen) {
                return;
            }

            this.isOpen = false;
            this._toggleAttr();

            this.range = null;
            this._off(this.document);

            this._trigger("close", event);
        },

        widget: function() {
            return this.button;
        },

        menuWidget: function() {
            return this.menu;
        },

        _renderButtonItem: function(item) {
            var buttonItem = $("<span>");

            this._setText(buttonItem, item.label);
            this._addClass(buttonItem, "ui-selectmenu-text");

            return buttonItem;
        },

        _renderMenu: function(ul, items) {
            var that = this,
                currentOptgroup = "";

            $.each(items, function(index, item) {
                var li;

                if (item.optgroup !== currentOptgroup) {
                    li = $("<li>", {
                        text: item.optgroup
                    });
                    that._addClass(li, "ui-selectmenu-optgroup", "ui-menu-divider" +
                        (item.element.parent("optgroup").prop("disabled") ?
                            " ui-state-disabled" :
                            ""));

                    li.appendTo(ul);

                    currentOptgroup = item.optgroup;
                }

                that._renderItemData(ul, item);
            });
        },

        _renderItemData: function(ul, item) {
            return this._renderItem(ul, item).data("ui-selectmenu-item", item);
        },

        _renderItem: function(ul, item) {
            var li = $("<li>"),
                wrapper = $("<div>", {
                    title: item.element.attr("title")
                });

            if (item.disabled) {
                this._addClass(li, null, "ui-state-disabled");
            }
            this._setText(wrapper, item.label);

            return li.append(wrapper).appendTo(ul);
        },

        _setText: function(element, value) {
            if (value) {
                element.text(value);
            } else {
                element.html("&#160;");
            }
        },

        _move: function(direction, event) {
            var item, next,
                filter = ".ui-menu-item";

            if (this.isOpen) {
                item = this.menuItems.eq(this.focusIndex).parent("li");
            } else {
                item = this.menuItems.eq(this.element[0].selectedIndex).parent("li");
                filter += ":not(.ui-state-disabled)";
            }

            if (direction === "first" || direction === "last") {
                next = item[direction === "first" ? "prevAll" : "nextAll"](filter).eq(-1);
            } else {
                next = item[direction + "All"](filter).eq(0);
            }

            if (next.length) {
                this.menuInstance.focus(event, next);
            }
        },

        _getSelectedItem: function() {
            return this.menuItems.eq(this.element[0].selectedIndex).parent("li");
        },

        _toggle: function(event) {
            this[this.isOpen ? "close" : "open"](event);
        },

        _setSelection: function() {
            var selection;

            if (!this.range) {
                return;
            }

            if (window.getSelection) {
                selection = window.getSelection();
                selection.removeAllRanges();
                selection.addRange(this.range);

                // Support: IE8
            } else {
                this.range.select();
            }

            // Support: IE
            // Setting the text selection kills the button focus in IE, but
            // restoring the focus doesn't kill the selection.
            this.button.focus();
        },

        _documentClick: {
            mousedown: function(event) {
                if (!this.isOpen) {
                    return;
                }

                if (!$(event.target).closest(".ui-selectmenu-menu, #" +
                        $.ui.escapeSelector(this.ids.button)).length) {
                    this.close(event);
                }
            }
        },

        _buttonEvents: {

            // Prevent text selection from being reset when interacting with the selectmenu (#10144)
            mousedown: function() {
                var selection;

                if (window.getSelection) {
                    selection = window.getSelection();
                    if (selection.rangeCount) {
                        this.range = selection.getRangeAt(0);
                    }

                    // Support: IE8
                } else {
                    this.range = document.selection.createRange();
                }
            },

            click: function(event) {
                this._setSelection();
                this._toggle(event);
            },

            keydown: function(event) {
                var preventDefault = true;
                switch (event.keyCode) {
                    case $.ui.keyCode.TAB:
                    case $.ui.keyCode.ESCAPE:
                        this.close(event);
                        preventDefault = false;
                        break;
                    case $.ui.keyCode.ENTER:
                        if (this.isOpen) {
                            this._selectFocusedItem(event);
                        }
                        break;
                    case $.ui.keyCode.UP:
                        if (event.altKey) {
                            this._toggle(event);
                        } else {
                            this._move("prev", event);
                        }
                        break;
                    case $.ui.keyCode.DOWN:
                        if (event.altKey) {
                            this._toggle(event);
                        } else {
                            this._move("next", event);
                        }
                        break;
                    case $.ui.keyCode.SPACE:
                        if (this.isOpen) {
                            this._selectFocusedItem(event);
                        } else {
                            this._toggle(event);
                        }
                        break;
                    case $.ui.keyCode.LEFT:
                        this._move("prev", event);
                        break;
                    case $.ui.keyCode.RIGHT:
                        this._move("next", event);
                        break;
                    case $.ui.keyCode.HOME:
                    case $.ui.keyCode.PAGE_UP:
                        this._move("first", event);
                        break;
                    case $.ui.keyCode.END:
                    case $.ui.keyCode.PAGE_DOWN:
                        this._move("last", event);
                        break;
                    default:
                        this.menu.trigger(event);
                        preventDefault = false;
                }

                if (preventDefault) {
                    event.preventDefault();
                }
            }
        },

        _selectFocusedItem: function(event) {
            var item = this.menuItems.eq(this.focusIndex).parent("li");
            if (!item.hasClass("ui-state-disabled")) {
                this._select(item.data("ui-selectmenu-item"), event);
            }
        },

        _select: function(item, event) {
            var oldIndex = this.element[0].selectedIndex;

            // Change native select element
            this.element[0].selectedIndex = item.index;
            this.buttonItem.replaceWith(this.buttonItem = this._renderButtonItem(item));
            this._setAria(item);
            this._trigger("select", event, { item: item });

            if (item.index !== oldIndex) {
                this._trigger("change", event, { item: item });
            }

            this.close(event);
        },

        _setAria: function(item) {
            var id = this.menuItems.eq(item.index).attr("id");

            this.button.attr({
                "aria-labelledby": id,
                "aria-activedescendant": id
            });
            this.menu.attr("aria-activedescendant", id);
        },

        _setOption: function(key, value) {
            if (key === "icons") {
                var icon = this.button.find("span.ui-icon");
                this._removeClass(icon, null, this.options.icons.button)
                    ._addClass(icon, null, value.button);
            }

            this._super(key, value);

            if (key === "appendTo") {
                this.menuWrap.appendTo(this._appendTo());
            }

            if (key === "width") {
                this._resizeButton();
            }
        },

        _setOptionDisabled: function(value) {
            this._super(value);

            this.menuInstance.option("disabled", value);
            this.button.attr("aria-disabled", value);
            this._toggleClass(this.button, null, "ui-state-disabled", value);

            this.element.prop("disabled", value);
            if (value) {
                this.button.attr("tabindex", -1);
                this.close();
            } else {
                this.button.attr("tabindex", 0);
            }
        },

        _appendTo: function() {
            var element = this.options.appendTo;

            if (element) {
                element = element.jquery || element.nodeType ?
                    $(element) :
                    this.document.find(element).eq(0);
            }

            if (!element || !element[0]) {
                element = this.element.closest(".ui-front, dialog");
            }

            if (!element.length) {
                element = this.document[0].body;
            }

            return element;
        },

        _toggleAttr: function() {
            this.button.attr("aria-expanded", this.isOpen);

            // We can't use two _toggleClass() calls here, because we need to make sure
            // we always remove classes first and add them second, otherwise if both classes have the
            // same theme class, it will be removed after we add it.
            this._removeClass(this.button, "ui-selectmenu-button-" +
                    (this.isOpen ? "closed" : "open"))
                ._addClass(this.button, "ui-selectmenu-button-" +
                    (this.isOpen ? "open" : "closed"))
                ._toggleClass(this.menuWrap, "ui-selectmenu-open", null, this.isOpen);

            this.menu.attr("aria-hidden", !this.isOpen);
        },

        _resizeButton: function() {
            var width = this.options.width;

            // For `width: false`, just remove inline style and stop
            if (width === false) {
                this.button.css("width", "");
                return;
            }

            // For `width: null`, match the width of the original element
            if (width === null) {
                width = this.element.show().outerWidth();
                this.element.hide();
            }

            this.button.outerWidth(width);
        },

        _resizeMenu: function() {
            this.menu.outerWidth(Math.max(
                this.button.outerWidth(),

                // Support: IE10
                // IE10 wraps long text (possibly a rounding bug)
                // so we add 1px to avoid the wrapping
                this.menu.width("").outerWidth() + 1
            ));
        },

        _getCreateOptions: function() {
            var options = this._super();

            options.disabled = this.element.prop("disabled");

            return options;
        },

        _parseOptions: function(options) {
            var that = this,
                data = [];
            options.each(function(index, item) {
                data.push(that._parseOption($(item), index));
            });
            this.items = data;
        },

        _parseOption: function(option, index) {
            var optgroup = option.parent("optgroup");

            return {
                element: option,
                index: index,
                value: option.val(),
                label: option.text(),
                optgroup: optgroup.attr("label") || "",
                disabled: optgroup.prop("disabled") || option.prop("disabled")
            };
        },

        _destroy: function() {
            this._unbindFormResetHandler();
            this.menuWrap.remove();
            this.button.remove();
            this.element.show();
            this.element.removeUniqueId();
            this.labels.attr("for", this.ids.element);
        }
    }]);


    /*!
     * jQuery UI Spinner 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Spinner
    //>>group: Widgets
    //>>description: Displays buttons to easily input numbers via the keyboard or mouse.
    //>>docs: http://api.jqueryui.com/spinner/
    //>>demos: http://jqueryui.com/spinner/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/spinner.css
    //>>css.theme: ../../themes/base/theme.css



    function spinnerModifer(fn) {
        return function() {
            var previous = this.element.val();
            fn.apply(this, arguments);
            this._refresh();
            if (previous !== this.element.val()) {
                this._trigger("change");
            }
        };
    }

    $.widget("ui.spinner", {
        version: "1.12.1",
        defaultElement: "<input>",
        widgetEventPrefix: "spin",
        options: {
            classes: {
                "ui-spinner": "ui-corner-all",
                "ui-spinner-down": "ui-corner-br",
                "ui-spinner-up": "ui-corner-tr"
            },
            culture: null,
            icons: {
                down: "ui-icon-triangle-1-s",
                up: "ui-icon-triangle-1-n"
            },
            incremental: true,
            max: null,
            min: null,
            numberFormat: null,
            page: 10,
            step: 1,

            change: null,
            spin: null,
            start: null,
            stop: null
        },

        _create: function() {

            // handle string values that need to be parsed
            this._setOption("max", this.options.max);
            this._setOption("min", this.options.min);
            this._setOption("step", this.options.step);

            // Only format if there is a value, prevents the field from being marked
            // as invalid in Firefox, see #9573.
            if (this.value() !== "") {

                // Format the value, but don't constrain.
                this._value(this.element.val(), true);
            }

            this._draw();
            this._on(this._events);
            this._refresh();

            // Turning off autocomplete prevents the browser from remembering the
            // value when navigating through history, so we re-enable autocomplete
            // if the page is unloaded before the widget is destroyed. #7790
            this._on(this.window, {
                beforeunload: function() {
                    this.element.removeAttr("autocomplete");
                }
            });
        },

        _getCreateOptions: function() {
            var options = this._super();
            var element = this.element;

            $.each(["min", "max", "step"], function(i, option) {
                var value = element.attr(option);
                if (value != null && value.length) {
                    options[option] = value;
                }
            });

            return options;
        },

        _events: {
            keydown: function(event) {
                if (this._start(event) && this._keydown(event)) {
                    event.preventDefault();
                }
            },
            keyup: "_stop",
            focus: function() {
                this.previous = this.element.val();
            },
            blur: function(event) {
                if (this.cancelBlur) {
                    delete this.cancelBlur;
                    return;
                }

                this._stop();
                this._refresh();
                if (this.previous !== this.element.val()) {
                    this._trigger("change", event);
                }
            },
            mousewheel: function(event, delta) {
                if (!delta) {
                    return;
                }
                if (!this.spinning && !this._start(event)) {
                    return false;
                }

                this._spin((delta > 0 ? 1 : -1) * this.options.step, event);
                clearTimeout(this.mousewheelTimer);
                this.mousewheelTimer = this._delay(function() {
                    if (this.spinning) {
                        this._stop(event);
                    }
                }, 100);
                event.preventDefault();
            },
            "mousedown .ui-spinner-button": function(event) {
                var previous;

                // We never want the buttons to have focus; whenever the user is
                // interacting with the spinner, the focus should be on the input.
                // If the input is focused then this.previous is properly set from
                // when the input first received focus. If the input is not focused
                // then we need to set this.previous based on the value before spinning.
                previous = this.element[0] === $.ui.safeActiveElement(this.document[0]) ?
                    this.previous : this.element.val();

                function checkFocus() {
                    var isActive = this.element[0] === $.ui.safeActiveElement(this.document[0]);
                    if (!isActive) {
                        this.element.trigger("focus");
                        this.previous = previous;

                        // support: IE
                        // IE sets focus asynchronously, so we need to check if focus
                        // moved off of the input because the user clicked on the button.
                        this._delay(function() {
                            this.previous = previous;
                        });
                    }
                }

                // Ensure focus is on (or stays on) the text field
                event.preventDefault();
                checkFocus.call(this);

                // Support: IE
                // IE doesn't prevent moving focus even with event.preventDefault()
                // so we set a flag to know when we should ignore the blur event
                // and check (again) if focus moved off of the input.
                this.cancelBlur = true;
                this._delay(function() {
                    delete this.cancelBlur;
                    checkFocus.call(this);
                });

                if (this._start(event) === false) {
                    return;
                }

                this._repeat(null, $(event.currentTarget)
                    .hasClass("ui-spinner-up") ? 1 : -1, event);
            },
            "mouseup .ui-spinner-button": "_stop",
            "mouseenter .ui-spinner-button": function(event) {

                // button will add ui-state-active if mouse was down while mouseleave and kept down
                if (!$(event.currentTarget).hasClass("ui-state-active")) {
                    return;
                }

                if (this._start(event) === false) {
                    return false;
                }
                this._repeat(null, $(event.currentTarget)
                    .hasClass("ui-spinner-up") ? 1 : -1, event);
            },

            // TODO: do we really want to consider this a stop?
            // shouldn't we just stop the repeater and wait until mouseup before
            // we trigger the stop event?
            "mouseleave .ui-spinner-button": "_stop"
        },

        // Support mobile enhanced option and make backcompat more sane
        _enhance: function() {
            this.uiSpinner = this.element
                .attr("autocomplete", "off")
                .wrap("<span>")
                .parent()

            // Add buttons
            .append(
                "<a></a><a></a>"
            );
        },

        _draw: function() {
            this._enhance();

            this._addClass(this.uiSpinner, "ui-spinner", "ui-widget ui-widget-content");
            this._addClass("ui-spinner-input");

            this.element.attr("role", "spinbutton");

            // Button bindings
            this.buttons = this.uiSpinner.children("a")
                .attr("tabIndex", -1)
                .attr("aria-hidden", true)
                .button({
                    classes: {
                        "ui-button": ""
                    }
                });

            // TODO: Right now button does not support classes this is already updated in button PR
            this._removeClass(this.buttons, "ui-corner-all");

            this._addClass(this.buttons.first(), "ui-spinner-button ui-spinner-up");
            this._addClass(this.buttons.last(), "ui-spinner-button ui-spinner-down");
            this.buttons.first().button({
                "icon": this.options.icons.up,
                "showLabel": false
            });
            this.buttons.last().button({
                "icon": this.options.icons.down,
                "showLabel": false
            });

            // IE 6 doesn't understand height: 50% for the buttons
            // unless the wrapper has an explicit height
            if (this.buttons.height() > Math.ceil(this.uiSpinner.height() * 0.5) &&
                this.uiSpinner.height() > 0) {
                this.uiSpinner.height(this.uiSpinner.height());
            }
        },

        _keydown: function(event) {
            var options = this.options,
                keyCode = $.ui.keyCode;

            switch (event.keyCode) {
                case keyCode.UP:
                    this._repeat(null, 1, event);
                    return true;
                case keyCode.DOWN:
                    this._repeat(null, -1, event);
                    return true;
                case keyCode.PAGE_UP:
                    this._repeat(null, options.page, event);
                    return true;
                case keyCode.PAGE_DOWN:
                    this._repeat(null, -options.page, event);
                    return true;
            }

            return false;
        },

        _start: function(event) {
            if (!this.spinning && this._trigger("start", event) === false) {
                return false;
            }

            if (!this.counter) {
                this.counter = 1;
            }
            this.spinning = true;
            return true;
        },

        _repeat: function(i, steps, event) {
            i = i || 500;

            clearTimeout(this.timer);
            this.timer = this._delay(function() {
                this._repeat(40, steps, event);
            }, i);

            this._spin(steps * this.options.step, event);
        },

        _spin: function(step, event) {
            var value = this.value() || 0;

            if (!this.counter) {
                this.counter = 1;
            }

            value = this._adjustValue(value + step * this._increment(this.counter));

            if (!this.spinning || this._trigger("spin", event, { value: value }) !== false) {
                this._value(value);
                this.counter++;
            }
        },

        _increment: function(i) {
            var incremental = this.options.incremental;

            if (incremental) {
                return $.isFunction(incremental) ?
                    incremental(i) :
                    Math.floor(i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1);
            }

            return 1;
        },

        _precision: function() {
            var precision = this._precisionOf(this.options.step);
            if (this.options.min !== null) {
                precision = Math.max(precision, this._precisionOf(this.options.min));
            }
            return precision;
        },

        _precisionOf: function(num) {
            var str = num.toString(),
                decimal = str.indexOf(".");
            return decimal === -1 ? 0 : str.length - decimal - 1;
        },

        _adjustValue: function(value) {
            var base, aboveMin,
                options = this.options;

            // Make sure we're at a valid step
            // - find out where we are relative to the base (min or 0)
            base = options.min !== null ? options.min : 0;
            aboveMin = value - base;

            // - round to the nearest step
            aboveMin = Math.round(aboveMin / options.step) * options.step;

            // - rounding is based on 0, so adjust back to our base
            value = base + aboveMin;

            // Fix precision from bad JS floating point math
            value = parseFloat(value.toFixed(this._precision()));

            // Clamp the value
            if (options.max !== null && value > options.max) {
                return options.max;
            }
            if (options.min !== null && value < options.min) {
                return options.min;
            }

            return value;
        },

        _stop: function(event) {
            if (!this.spinning) {
                return;
            }

            clearTimeout(this.timer);
            clearTimeout(this.mousewheelTimer);
            this.counter = 0;
            this.spinning = false;
            this._trigger("stop", event);
        },

        _setOption: function(key, value) {
            var prevValue, first, last;

            if (key === "culture" || key === "numberFormat") {
                prevValue = this._parse(this.element.val());
                this.options[key] = value;
                this.element.val(this._format(prevValue));
                return;
            }

            if (key === "max" || key === "min" || key === "step") {
                if (typeof value === "string") {
                    value = this._parse(value);
                }
            }
            if (key === "icons") {
                first = this.buttons.first().find(".ui-icon");
                this._removeClass(first, null, this.options.icons.up);
                this._addClass(first, null, value.up);
                last = this.buttons.last().find(".ui-icon");
                this._removeClass(last, null, this.options.icons.down);
                this._addClass(last, null, value.down);
            }

            this._super(key, value);
        },

        _setOptionDisabled: function(value) {
            this._super(value);

            this._toggleClass(this.uiSpinner, null, "ui-state-disabled", !!value);
            this.element.prop("disabled", !!value);
            this.buttons.button(value ? "disable" : "enable");
        },

        _setOptions: spinnerModifer(function(options) {
            this._super(options);
        }),

        _parse: function(val) {
            if (typeof val === "string" && val !== "") {
                val = window.Globalize && this.options.numberFormat ?
                    Globalize.parseFloat(val, 10, this.options.culture) : +val;
            }
            return val === "" || isNaN(val) ? null : val;
        },

        _format: function(value) {
            if (value === "") {
                return "";
            }
            return window.Globalize && this.options.numberFormat ?
                Globalize.format(value, this.options.numberFormat, this.options.culture) :
                value;
        },

        _refresh: function() {
            this.element.attr({
                "aria-valuemin": this.options.min,
                "aria-valuemax": this.options.max,

                // TODO: what should we do with values that can't be parsed?
                "aria-valuenow": this._parse(this.element.val())
            });
        },

        isValid: function() {
            var value = this.value();

            // Null is invalid
            if (value === null) {
                return false;
            }

            // If value gets adjusted, it's invalid
            return value === this._adjustValue(value);
        },

        // Update the value without triggering change
        _value: function(value, allowAny) {
            var parsed;
            if (value !== "") {
                parsed = this._parse(value);
                if (parsed !== null) {
                    if (!allowAny) {
                        parsed = this._adjustValue(parsed);
                    }
                    value = this._format(parsed);
                }
            }
            this.element.val(value);
            this._refresh();
        },

        _destroy: function() {
            this.element
                .prop("disabled", false)
                .removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow");

            this.uiSpinner.replaceWith(this.element);
        },

        stepUp: spinnerModifer(function(steps) {
            this._stepUp(steps);
        }),
        _stepUp: function(steps) {
            if (this._start()) {
                this._spin((steps || 1) * this.options.step);
                this._stop();
            }
        },

        stepDown: spinnerModifer(function(steps) {
            this._stepDown(steps);
        }),
        _stepDown: function(steps) {
            if (this._start()) {
                this._spin((steps || 1) * -this.options.step);
                this._stop();
            }
        },

        pageUp: spinnerModifer(function(pages) {
            this._stepUp((pages || 1) * this.options.page);
        }),

        pageDown: spinnerModifer(function(pages) {
            this._stepDown((pages || 1) * this.options.page);
        }),

        value: function(newVal) {
            if (!arguments.length) {
                return this._parse(this.element.val());
            }
            spinnerModifer(this._value).call(this, newVal);
        },

        widget: function() {
            return this.uiSpinner;
        }
    });

    // DEPRECATED
    // TODO: switch return back to widget declaration at top of file when this is removed
    if ($.uiBackCompat !== false) {

        // Backcompat for spinner html extension points
        $.widget("ui.spinner", $.ui.spinner, {
            _enhance: function() {
                this.uiSpinner = this.element
                    .attr("autocomplete", "off")
                    .wrap(this._uiSpinnerHtml())
                    .parent()

                // Add buttons
                .append(this._buttonHtml());
            },
            _uiSpinnerHtml: function() {
                return "<span>";
            },

            _buttonHtml: function() {
                return "<a></a><a></a>";
            }
        });
    }

    var widgetsSpinner = $.ui.spinner;


    /*!
     * jQuery UI Tabs 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Tabs
    //>>group: Widgets
    //>>description: Transforms a set of container elements into a tab structure.
    //>>docs: http://api.jqueryui.com/tabs/
    //>>demos: http://jqueryui.com/tabs/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/tabs.css
    //>>css.theme: ../../themes/base/theme.css



    $.widget("ui.tabs", {
        version: "1.12.1",
        delay: 300,
        options: {
            active: null,
            classes: {
                "ui-tabs": "ui-corner-all",
                "ui-tabs-nav": "ui-corner-all",
                "ui-tabs-panel": "ui-corner-bottom",
                "ui-tabs-tab": "ui-corner-top"
            },
            collapsible: false,
            event: "click",
            heightStyle: "content",
            hide: null,
            show: null,

            // Callbacks
            activate: null,
            beforeActivate: null,
            beforeLoad: null,
            load: null
        },

        _isLocal: (function() {
            var rhash = /#.*$/;

            return function(anchor) {
                var anchorUrl, locationUrl;

                anchorUrl = anchor.href.replace(rhash, "");
                locationUrl = location.href.replace(rhash, "");

                // Decoding may throw an error if the URL isn't UTF-8 (#9518)
                try {
                    anchorUrl = decodeURIComponent(anchorUrl);
                } catch (error) {}
                try {
                    locationUrl = decodeURIComponent(locationUrl);
                } catch (error) {}

                return anchor.hash.length > 1 && anchorUrl === locationUrl;
            };
        })(),

        _create: function() {
            var that = this,
                options = this.options;

            this.running = false;

            this._addClass("ui-tabs", "ui-widget ui-widget-content");
            this._toggleClass("ui-tabs-collapsible", null, options.collapsible);

            this._processTabs();
            options.active = this._initialActive();

            // Take disabling tabs via class attribute from HTML
            // into account and update option properly.
            if ($.isArray(options.disabled)) {
                options.disabled = $.unique(options.disabled.concat(
                    $.map(this.tabs.filter(".ui-state-disabled"), function(li) {
                        return that.tabs.index(li);
                    })
                )).sort();
            }

            // Check for length avoids error when initializing empty list
            if (this.options.active !== false && this.anchors.length) {
                this.active = this._findActive(options.active);
            } else {
                this.active = $();
            }

            this._refresh();

            if (this.active.length) {
                this.load(options.active);
            }
        },

        _initialActive: function() {
            var active = this.options.active,
                collapsible = this.options.collapsible,
                locationHash = location.hash.substring(1);

            if (active === null) {

                // check the fragment identifier in the URL
                if (locationHash) {
                    this.tabs.each(function(i, tab) {
                        if ($(tab).attr("aria-controls") === locationHash) {
                            active = i;
                            return false;
                        }
                    });
                }

                // Check for a tab marked active via a class
                if (active === null) {
                    active = this.tabs.index(this.tabs.filter(".ui-tabs-active"));
                }

                // No active tab, set to false
                if (active === null || active === -1) {
                    active = this.tabs.length ? 0 : false;
                }
            }

            // Handle numbers: negative, out of range
            if (active !== false) {
                active = this.tabs.index(this.tabs.eq(active));
                if (active === -1) {
                    active = collapsible ? false : 0;
                }
            }

            // Don't allow collapsible: false and active: false
            if (!collapsible && active === false && this.anchors.length) {
                active = 0;
            }

            return active;
        },

        _getCreateEventData: function() {
            return {
                tab: this.active,
                panel: !this.active.length ? $() : this._getPanelForTab(this.active)
            };
        },

        _tabKeydown: function(event) {
            var focusedTab = $($.ui.safeActiveElement(this.document[0])).closest("li"),
                selectedIndex = this.tabs.index(focusedTab),
                goingForward = true;

            if (this._handlePageNav(event)) {
                return;
            }

            switch (event.keyCode) {
                case $.ui.keyCode.RIGHT:
                case $.ui.keyCode.DOWN:
                    selectedIndex++;
                    break;
                case $.ui.keyCode.UP:
                case $.ui.keyCode.LEFT:
                    goingForward = false;
                    selectedIndex--;
                    break;
                case $.ui.keyCode.END:
                    selectedIndex = this.anchors.length - 1;
                    break;
                case $.ui.keyCode.HOME:
                    selectedIndex = 0;
                    break;
                case $.ui.keyCode.SPACE:

                    // Activate only, no collapsing
                    event.preventDefault();
                    clearTimeout(this.activating);
                    this._activate(selectedIndex);
                    return;
                case $.ui.keyCode.ENTER:

                    // Toggle (cancel delayed activation, allow collapsing)
                    event.preventDefault();
                    clearTimeout(this.activating);

                    // Determine if we should collapse or activate
                    this._activate(selectedIndex === this.options.active ? false : selectedIndex);
                    return;
                default:
                    return;
            }

            // Focus the appropriate tab, based on which key was pressed
            event.preventDefault();
            clearTimeout(this.activating);
            selectedIndex = this._focusNextTab(selectedIndex, goingForward);

            // Navigating with control/command key will prevent automatic activation
            if (!event.ctrlKey && !event.metaKey) {

                // Update aria-selected immediately so that AT think the tab is already selected.
                // Otherwise AT may confuse the user by stating that they need to activate the tab,
                // but the tab will already be activated by the time the announcement finishes.
                focusedTab.attr("aria-selected", "false");
                this.tabs.eq(selectedIndex).attr("aria-selected", "true");

                this.activating = this._delay(function() {
                    this.option("active", selectedIndex);
                }, this.delay);
            }
        },

        _panelKeydown: function(event) {
            if (this._handlePageNav(event)) {
                return;
            }

            // Ctrl+up moves focus to the current tab
            if (event.ctrlKey && event.keyCode === $.ui.keyCode.UP) {
                event.preventDefault();
                this.active.trigger("focus");
            }
        },

        // Alt+page up/down moves focus to the previous/next tab (and activates)
        _handlePageNav: function(event) {
            if (event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP) {
                this._activate(this._focusNextTab(this.options.active - 1, false));
                return true;
            }
            if (event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN) {
                this._activate(this._focusNextTab(this.options.active + 1, true));
                return true;
            }
        },

        _findNextTab: function(index, goingForward) {
            var lastTabIndex = this.tabs.length - 1;

            function constrain() {
                if (index > lastTabIndex) {
                    index = 0;
                }
                if (index < 0) {
                    index = lastTabIndex;
                }
                return index;
            }

            while ($.inArray(constrain(), this.options.disabled) !== -1) {
                index = goingForward ? index + 1 : index - 1;
            }

            return index;
        },

        _focusNextTab: function(index, goingForward) {
            index = this._findNextTab(index, goingForward);
            this.tabs.eq(index).trigger("focus");
            return index;
        },

        _setOption: function(key, value) {
            if (key === "active") {

                // _activate() will handle invalid values and update this.options
                this._activate(value);
                return;
            }

            this._super(key, value);

            if (key === "collapsible") {
                this._toggleClass("ui-tabs-collapsible", null, value);

                // Setting collapsible: false while collapsed; open first panel
                if (!value && this.options.active === false) {
                    this._activate(0);
                }
            }

            if (key === "event") {
                this._setupEvents(value);
            }

            if (key === "heightStyle") {
                this._setupHeightStyle(value);
            }
        },

        _sanitizeSelector: function(hash) {
            return hash ? hash.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&") : "";
        },

        refresh: function() {
            var options = this.options,
                lis = this.tablist.children(":has(a[href])");

            // Get disabled tabs from class attribute from HTML
            // this will get converted to a boolean if needed in _refresh()
            options.disabled = $.map(lis.filter(".ui-state-disabled"), function(tab) {
                return lis.index(tab);
            });

            this._processTabs();

            // Was collapsed or no tabs
            if (options.active === false || !this.anchors.length) {
                options.active = false;
                this.active = $();

                // was active, but active tab is gone
            } else if (this.active.length && !$.contains(this.tablist[0], this.active[0])) {

                // all remaining tabs are disabled
                if (this.tabs.length === options.disabled.length) {
                    options.active = false;
                    this.active = $();

                    // activate previous tab
                } else {
                    this._activate(this._findNextTab(Math.max(0, options.active - 1), false));
                }

                // was active, active tab still exists
            } else {

                // make sure active index is correct
                options.active = this.tabs.index(this.active);
            }

            this._refresh();
        },

        _refresh: function() {
            this._setOptionDisabled(this.options.disabled);
            this._setupEvents(this.options.event);
            this._setupHeightStyle(this.options.heightStyle);

            this.tabs.not(this.active).attr({
                "aria-selected": "false",
                "aria-expanded": "false",
                tabIndex: -1
            });
            this.panels.not(this._getPanelForTab(this.active))
                .hide()
                .attr({
                    "aria-hidden": "true"
                });

            // Make sure one tab is in the tab order
            if (!this.active.length) {
                this.tabs.eq(0).attr("tabIndex", 0);
            } else {
                this.active
                    .attr({
                        "aria-selected": "true",
                        "aria-expanded": "true",
                        tabIndex: 0
                    });
                this._addClass(this.active, "ui-tabs-active", "ui-state-active");
                this._getPanelForTab(this.active)
                    .show()
                    .attr({
                        "aria-hidden": "false"
                    });
            }
        },

        _processTabs: function() {
            var that = this,
                prevTabs = this.tabs,
                prevAnchors = this.anchors,
                prevPanels = this.panels;

            this.tablist = this._getList().attr("role", "tablist");
            this._addClass(this.tablist, "ui-tabs-nav",
                "ui-helper-reset ui-helper-clearfix ui-widget-header");

            // Prevent users from focusing disabled tabs via click
            this.tablist
                .on("mousedown" + this.eventNamespace, "> li", function(event) {
                    if ($(this).is(".ui-state-disabled")) {
                        event.preventDefault();
                    }
                })

            // Support: IE <9
            // Preventing the default action in mousedown doesn't prevent IE
            // from focusing the element, so if the anchor gets focused, blur.
            // We don't have to worry about focusing the previously focused
            // element since clicking on a non-focusable element should focus
            // the body anyway.
            .on("focus" + this.eventNamespace, ".ui-tabs-anchor", function() {
                if ($(this).closest("li").is(".ui-state-disabled")) {
                    this.blur();
                }
            });

            this.tabs = this.tablist.find("> li:has(a[href])")
                .attr({
                    role: "tab",
                    tabIndex: -1
                });
            this._addClass(this.tabs, "ui-tabs-tab", "ui-state-default");

            this.anchors = this.tabs.map(function() {
                    return $("a", this)[0];
                })
                .attr({
                    role: "presentation",
                    tabIndex: -1
                });
            this._addClass(this.anchors, "ui-tabs-anchor");

            this.panels = $();

            this.anchors.each(function(i, anchor) {
                var selector, panel, panelId,
                    anchorId = $(anchor).uniqueId().attr("id"),
                    tab = $(anchor).closest("li"),
                    originalAriaControls = tab.attr("aria-controls");

                // Inline tab
                if (that._isLocal(anchor)) {
                    selector = anchor.hash;
                    panelId = selector.substring(1);
                    panel = that.element.find(that._sanitizeSelector(selector));

                    // remote tab
                } else {

                    // If the tab doesn't already have aria-controls,
                    // generate an id by using a throw-away element
                    panelId = tab.attr("aria-controls") || $({}).uniqueId()[0].id;
                    selector = "#" + panelId;
                    panel = that.element.find(selector);
                    if (!panel.length) {
                        panel = that._createPanel(panelId);
                        panel.insertAfter(that.panels[i - 1] || that.tablist);
                    }
                    panel.attr("aria-live", "polite");
                }

                if (panel.length) {
                    that.panels = that.panels.add(panel);
                }
                if (originalAriaControls) {
                    tab.data("ui-tabs-aria-controls", originalAriaControls);
                }
                tab.attr({
                    "aria-controls": panelId,
                    "aria-labelledby": anchorId
                });
                panel.attr("aria-labelledby", anchorId);
            });

            this.panels.attr("role", "tabpanel");
            this._addClass(this.panels, "ui-tabs-panel", "ui-widget-content");

            // Avoid memory leaks (#10056)
            if (prevTabs) {
                this._off(prevTabs.not(this.tabs));
                this._off(prevAnchors.not(this.anchors));
                this._off(prevPanels.not(this.panels));
            }
        },

        // Allow overriding how to find the list for rare usage scenarios (#7715)
        _getList: function() {
            return this.tablist || this.element.find("ol, ul").eq(0);
        },

        _createPanel: function(id) {
            return $("<div>")
                .attr("id", id)
                .data("ui-tabs-destroy", true);
        },

        _setOptionDisabled: function(disabled) {
            var currentItem, li, i;

            if ($.isArray(disabled)) {
                if (!disabled.length) {
                    disabled = false;
                } else if (disabled.length === this.anchors.length) {
                    disabled = true;
                }
            }

            // Disable tabs
            for (i = 0;
                (li = this.tabs[i]); i++) {
                currentItem = $(li);
                if (disabled === true || $.inArray(i, disabled) !== -1) {
                    currentItem.attr("aria-disabled", "true");
                    this._addClass(currentItem, null, "ui-state-disabled");
                } else {
                    currentItem.removeAttr("aria-disabled");
                    this._removeClass(currentItem, null, "ui-state-disabled");
                }
            }

            this.options.disabled = disabled;

            this._toggleClass(this.widget(), this.widgetFullName + "-disabled", null,
                disabled === true);
        },

        _setupEvents: function(event) {
            var events = {};
            if (event) {
                $.each(event.split(" "), function(index, eventName) {
                    events[eventName] = "_eventHandler";
                });
            }

            this._off(this.anchors.add(this.tabs).add(this.panels));

            // Always prevent the default action, even when disabled
            this._on(true, this.anchors, {
                click: function(event) {
                    event.preventDefault();
                }
            });
            this._on(this.anchors, events);
            this._on(this.tabs, { keydown: "_tabKeydown" });
            this._on(this.panels, { keydown: "_panelKeydown" });

            this._focusable(this.tabs);
            this._hoverable(this.tabs);
        },

        _setupHeightStyle: function(heightStyle) {
            var maxHeight,
                parent = this.element.parent();

            if (heightStyle === "fill") {
                maxHeight = parent.height();
                maxHeight -= this.element.outerHeight() - this.element.height();

                this.element.siblings(":visible").each(function() {
                    var elem = $(this),
                        position = elem.css("position");

                    if (position === "absolute" || position === "fixed") {
                        return;
                    }
                    maxHeight -= elem.outerHeight(true);
                });

                this.element.children().not(this.panels).each(function() {
                    maxHeight -= $(this).outerHeight(true);
                });

                this.panels.each(function() {
                        $(this).height(Math.max(0, maxHeight -
                            $(this).innerHeight() + $(this).height()));
                    })
                    .css("overflow", "auto");
            } else if (heightStyle === "auto") {
                maxHeight = 0;
                this.panels.each(function() {
                    maxHeight = Math.max(maxHeight, $(this).height("").height());
                }).height(maxHeight);
            }
        },

        _eventHandler: function(event) {
            var options = this.options,
                active = this.active,
                anchor = $(event.currentTarget),
                tab = anchor.closest("li"),
                clickedIsActive = tab[0] === active[0],
                collapsing = clickedIsActive && options.collapsible,
                toShow = collapsing ? $() : this._getPanelForTab(tab),
                toHide = !active.length ? $() : this._getPanelForTab(active),
                eventData = {
                    oldTab: active,
                    oldPanel: toHide,
                    newTab: collapsing ? $() : tab,
                    newPanel: toShow
                };

            event.preventDefault();

            if (tab.hasClass("ui-state-disabled") ||

                // tab is already loading
                tab.hasClass("ui-tabs-loading") ||

                // can't switch durning an animation
                this.running ||

                // click on active header, but not collapsible
                (clickedIsActive && !options.collapsible) ||

                // allow canceling activation
                (this._trigger("beforeActivate", event, eventData) === false)) {
                return;
            }

            options.active = collapsing ? false : this.tabs.index(tab);

            this.active = clickedIsActive ? $() : tab;
            if (this.xhr) {
                this.xhr.abort();
            }

            if (!toHide.length && !toShow.length) {
                $.error("jQuery UI Tabs: Mismatching fragment identifier.");
            }

            if (toShow.length) {
                this.load(this.tabs.index(tab), event);
            }
            this._toggle(event, eventData);
        },

        // Handles show/hide for selecting tabs
        _toggle: function(event, eventData) {
            var that = this,
                toShow = eventData.newPanel,
                toHide = eventData.oldPanel;

            this.running = true;

            function complete() {
                that.running = false;
                that._trigger("activate", event, eventData);
            }

            function show() {
                that._addClass(eventData.newTab.closest("li"), "ui-tabs-active", "ui-state-active");

                if (toShow.length && that.options.show) {
                    that._show(toShow, that.options.show, complete);
                } else {
                    toShow.show();
                    complete();
                }
            }

            // Start out by hiding, then showing, then completing
            if (toHide.length && this.options.hide) {
                this._hide(toHide, this.options.hide, function() {
                    that._removeClass(eventData.oldTab.closest("li"),
                        "ui-tabs-active", "ui-state-active");
                    show();
                });
            } else {
                this._removeClass(eventData.oldTab.closest("li"),
                    "ui-tabs-active", "ui-state-active");
                toHide.hide();
                show();
            }

            toHide.attr("aria-hidden", "true");
            eventData.oldTab.attr({
                "aria-selected": "false",
                "aria-expanded": "false"
            });

            // If we're switching tabs, remove the old tab from the tab order.
            // If we're opening from collapsed state, remove the previous tab from the tab order.
            // If we're collapsing, then keep the collapsing tab in the tab order.
            if (toShow.length && toHide.length) {
                eventData.oldTab.attr("tabIndex", -1);
            } else if (toShow.length) {
                this.tabs.filter(function() {
                        return $(this).attr("tabIndex") === 0;
                    })
                    .attr("tabIndex", -1);
            }

            toShow.attr("aria-hidden", "false");
            eventData.newTab.attr({
                "aria-selected": "true",
                "aria-expanded": "true",
                tabIndex: 0
            });
        },

        _activate: function(index) {
            var anchor,
                active = this._findActive(index);

            // Trying to activate the already active panel
            if (active[0] === this.active[0]) {
                return;
            }

            // Trying to collapse, simulate a click on the current active header
            if (!active.length) {
                active = this.active;
            }

            anchor = active.find(".ui-tabs-anchor")[0];
            this._eventHandler({
                target: anchor,
                currentTarget: anchor,
                preventDefault: $.noop
            });
        },

        _findActive: function(index) {
            return index === false ? $() : this.tabs.eq(index);
        },

        _getIndex: function(index) {

            // meta-function to give users option to provide a href string instead of a numerical index.
            if (typeof index === "string") {
                index = this.anchors.index(this.anchors.filter("[href$='" +
                    $.ui.escapeSelector(index) + "']"));
            }

            return index;
        },

        _destroy: function() {
            if (this.xhr) {
                this.xhr.abort();
            }

            this.tablist
                .removeAttr("role")
                .off(this.eventNamespace);

            this.anchors
                .removeAttr("role tabIndex")
                .removeUniqueId();

            this.tabs.add(this.panels).each(function() {
                if ($.data(this, "ui-tabs-destroy")) {
                    $(this).remove();
                } else {
                    $(this).removeAttr("role tabIndex " +
                        "aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded");
                }
            });

            this.tabs.each(function() {
                var li = $(this),
                    prev = li.data("ui-tabs-aria-controls");
                if (prev) {
                    li
                        .attr("aria-controls", prev)
                        .removeData("ui-tabs-aria-controls");
                } else {
                    li.removeAttr("aria-controls");
                }
            });

            this.panels.show();

            if (this.options.heightStyle !== "content") {
                this.panels.css("height", "");
            }
        },

        enable: function(index) {
            var disabled = this.options.disabled;
            if (disabled === false) {
                return;
            }

            if (index === undefined) {
                disabled = false;
            } else {
                index = this._getIndex(index);
                if ($.isArray(disabled)) {
                    disabled = $.map(disabled, function(num) {
                        return num !== index ? num : null;
                    });
                } else {
                    disabled = $.map(this.tabs, function(li, num) {
                        return num !== index ? num : null;
                    });
                }
            }
            this._setOptionDisabled(disabled);
        },

        disable: function(index) {
            var disabled = this.options.disabled;
            if (disabled === true) {
                return;
            }

            if (index === undefined) {
                disabled = true;
            } else {
                index = this._getIndex(index);
                if ($.inArray(index, disabled) !== -1) {
                    return;
                }
                if ($.isArray(disabled)) {
                    disabled = $.merge([index], disabled).sort();
                } else {
                    disabled = [index];
                }
            }
            this._setOptionDisabled(disabled);
        },

        load: function(index, event) {
            index = this._getIndex(index);
            var that = this,
                tab = this.tabs.eq(index),
                anchor = tab.find(".ui-tabs-anchor"),
                panel = this._getPanelForTab(tab),
                eventData = {
                    tab: tab,
                    panel: panel
                },
                complete = function(jqXHR, status) {
                    if (status === "abort") {
                        that.panels.stop(false, true);
                    }

                    that._removeClass(tab, "ui-tabs-loading");
                    panel.removeAttr("aria-busy");

                    if (jqXHR === that.xhr) {
                        delete that.xhr;
                    }
                };

            // Not remote
            if (this._isLocal(anchor[0])) {
                return;
            }

            this.xhr = $.ajax(this._ajaxSettings(anchor, event, eventData));

            // Support: jQuery <1.8
            // jQuery <1.8 returns false if the request is canceled in beforeSend,
            // but as of 1.8, $.ajax() always returns a jqXHR object.
            if (this.xhr && this.xhr.statusText !== "canceled") {
                this._addClass(tab, "ui-tabs-loading");
                panel.attr("aria-busy", "true");

                this.xhr
                    .done(function(response, status, jqXHR) {

                        // support: jQuery <1.8
                        // http://bugs.jquery.com/ticket/11778
                        setTimeout(function() {
                            panel.html(response);
                            that._trigger("load", event, eventData);

                            complete(jqXHR, status);
                        }, 1);
                    })
                    .fail(function(jqXHR, status) {

                        // support: jQuery <1.8
                        // http://bugs.jquery.com/ticket/11778
                        setTimeout(function() {
                            complete(jqXHR, status);
                        }, 1);
                    });
            }
        },

        _ajaxSettings: function(anchor, event, eventData) {
            var that = this;
            return {

                // Support: IE <11 only
                // Strip any hash that exists to prevent errors with the Ajax request
                url: anchor.attr("href").replace(/#.*$/, ""),
                beforeSend: function(jqXHR, settings) {
                    return that._trigger("beforeLoad", event,
                        $.extend({ jqXHR: jqXHR, ajaxSettings: settings }, eventData));
                }
            };
        },

        _getPanelForTab: function(tab) {
            var id = $(tab).attr("aria-controls");
            return this.element.find(this._sanitizeSelector("#" + id));
        }
    });

    // DEPRECATED
    // TODO: Switch return back to widget declaration at top of file when this is removed
    if ($.uiBackCompat !== false) {

        // Backcompat for ui-tab class (now ui-tabs-tab)
        $.widget("ui.tabs", $.ui.tabs, {
            _processTabs: function() {
                this._superApply(arguments);
                this._addClass(this.tabs, "ui-tab");
            }
        });
    }

    var widgetsTabs = $.ui.tabs;


    /*!
     * jQuery UI Tooltip 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Tooltip
    //>>group: Widgets
    //>>description: Shows additional information for any element on hover or focus.
    //>>docs: http://api.jqueryui.com/tooltip/
    //>>demos: http://jqueryui.com/tooltip/
    //>>css.structure: ../../themes/base/core.css
    //>>css.structure: ../../themes/base/tooltip.css
    //>>css.theme: ../../themes/base/theme.css



    $.widget("ui.tooltip", {
        version: "1.12.1",
        options: {
            classes: {
                "ui-tooltip": "ui-corner-all ui-widget-shadow"
            },
            content: function() {

                // support: IE<9, Opera in jQuery <1.7
                // .text() can't accept undefined, so coerce to a string
                var title = $(this).attr("title") || "";

                // Escape title, since we're going from an attribute to raw HTML
                return $("<a>").text(title).html();
            },
            hide: true,

            // Disabled elements have inconsistent behavior across browsers (#8661)
            items: "[title]:not([disabled])",
            position: {
                my: "left top+15",
                at: "left bottom",
                collision: "flipfit flip"
            },
            show: true,
            track: false,

            // Callbacks
            close: null,
            open: null
        },

        _addDescribedBy: function(elem, id) {
            var describedby = (elem.attr("aria-describedby") || "").split(/\s+/);
            describedby.push(id);
            elem
                .data("ui-tooltip-id", id)
                .attr("aria-describedby", $.trim(describedby.join(" ")));
        },

        _removeDescribedBy: function(elem) {
            var id = elem.data("ui-tooltip-id"),
                describedby = (elem.attr("aria-describedby") || "").split(/\s+/),
                index = $.inArray(id, describedby);

            if (index !== -1) {
                describedby.splice(index, 1);
            }

            elem.removeData("ui-tooltip-id");
            describedby = $.trim(describedby.join(" "));
            if (describedby) {
                elem.attr("aria-describedby", describedby);
            } else {
                elem.removeAttr("aria-describedby");
            }
        },

        _create: function() {
            this._on({
                mouseover: "open",
                focusin: "open"
            });

            // IDs of generated tooltips, needed for destroy
            this.tooltips = {};

            // IDs of parent tooltips where we removed the title attribute
            this.parents = {};

            // Append the aria-live region so tooltips announce correctly
            this.liveRegion = $("<div>")
                .attr({
                    role: "log",
                    "aria-live": "assertive",
                    "aria-relevant": "additions"
                })
                .appendTo(this.document[0].body);
            this._addClass(this.liveRegion, null, "ui-helper-hidden-accessible");

            this.disabledTitles = $([]);
        },

        _setOption: function(key, value) {
            var that = this;

            this._super(key, value);

            if (key === "content") {
                $.each(this.tooltips, function(id, tooltipData) {
                    that._updateContent(tooltipData.element);
                });
            }
        },

        _setOptionDisabled: function(value) {
            this[value ? "_disable" : "_enable"]();
        },

        _disable: function() {
            var that = this;

            // Close open tooltips
            $.each(this.tooltips, function(id, tooltipData) {
                var event = $.Event("blur");
                event.target = event.currentTarget = tooltipData.element[0];
                that.close(event, true);
            });

            // Remove title attributes to prevent native tooltips
            this.disabledTitles = this.disabledTitles.add(
                this.element.find(this.options.items).addBack()
                .filter(function() {
                    var element = $(this);
                    if (element.is("[title]")) {
                        return element
                            .data("ui-tooltip-title", element.attr("title"))
                            .removeAttr("title");
                    }
                })
            );
        },

        _enable: function() {

            // restore title attributes
            this.disabledTitles.each(function() {
                var element = $(this);
                if (element.data("ui-tooltip-title")) {
                    element.attr("title", element.data("ui-tooltip-title"));
                }
            });
            this.disabledTitles = $([]);
        },

        open: function(event) {
            var that = this,
                target = $(event ? event.target : this.element)

            // we need closest here due to mouseover bubbling,
            // but always pointing at the same event target
            .closest(this.options.items);

            // No element to show a tooltip for or the tooltip is already open
            if (!target.length || target.data("ui-tooltip-id")) {
                return;
            }

            if (target.attr("title")) {
                target.data("ui-tooltip-title", target.attr("title"));
            }

            target.data("ui-tooltip-open", true);

            // Kill parent tooltips, custom or native, for hover
            if (event && event.type === "mouseover") {
                target.parents().each(function() {
                    var parent = $(this),
                        blurEvent;
                    if (parent.data("ui-tooltip-open")) {
                        blurEvent = $.Event("blur");
                        blurEvent.target = blurEvent.currentTarget = this;
                        that.close(blurEvent, true);
                    }
                    if (parent.attr("title")) {
                        parent.uniqueId();
                        that.parents[this.id] = {
                            element: this,
                            title: parent.attr("title")
                        };
                        parent.attr("title", "");
                    }
                });
            }

            this._registerCloseHandlers(event, target);
            this._updateContent(target, event);
        },

        _updateContent: function(target, event) {
            var content,
                contentOption = this.options.content,
                that = this,
                eventType = event ? event.type : null;

            if (typeof contentOption === "string" || contentOption.nodeType ||
                contentOption.jquery) {
                return this._open(event, target, contentOption);
            }

            content = contentOption.call(target[0], function(response) {

                // IE may instantly serve a cached response for ajax requests
                // delay this call to _open so the other call to _open runs first
                that._delay(function() {

                    // Ignore async response if tooltip was closed already
                    if (!target.data("ui-tooltip-open")) {
                        return;
                    }

                    // JQuery creates a special event for focusin when it doesn't
                    // exist natively. To improve performance, the native event
                    // object is reused and the type is changed. Therefore, we can't
                    // rely on the type being correct after the event finished
                    // bubbling, so we set it back to the previous value. (#8740)
                    if (event) {
                        event.type = eventType;
                    }
                    this._open(event, target, response);
                });
            });
            if (content) {
                this._open(event, target, content);
            }
        },

        _open: function(event, target, content) {
            var tooltipData, tooltip, delayedShow, a11yContent,
                positionOption = $.extend({}, this.options.position);

            if (!content) {
                return;
            }

            // Content can be updated multiple times. If the tooltip already
            // exists, then just update the content and bail.
            tooltipData = this._find(target);
            if (tooltipData) {
                tooltipData.tooltip.find(".ui-tooltip-content").html(content);
                return;
            }

            // If we have a title, clear it to prevent the native tooltip
            // we have to check first to avoid defining a title if none exists
            // (we don't want to cause an element to start matching [title])
            //
            // We use removeAttr only for key events, to allow IE to export the correct
            // accessible attributes. For mouse events, set to empty string to avoid
            // native tooltip showing up (happens only when removing inside mouseover).
            if (target.is("[title]")) {
                if (event && event.type === "mouseover") {
                    target.attr("title", "");
                } else {
                    target.removeAttr("title");
                }
            }

            tooltipData = this._tooltip(target);
            tooltip = tooltipData.tooltip;
            this._addDescribedBy(target, tooltip.attr("id"));
            tooltip.find(".ui-tooltip-content").html(content);

            // Support: Voiceover on OS X, JAWS on IE <= 9
            // JAWS announces deletions even when aria-relevant="additions"
            // Voiceover will sometimes re-read the entire log region's contents from the beginning
            this.liveRegion.children().hide();
            a11yContent = $("<div>").html(tooltip.find(".ui-tooltip-content").html());
            a11yContent.removeAttr("name").find("[name]").removeAttr("name");
            a11yContent.removeAttr("id").find("[id]").removeAttr("id");
            a11yContent.appendTo(this.liveRegion);

            function position(event) {
                positionOption.of = event;
                if (tooltip.is(":hidden")) {
                    return;
                }
                tooltip.position(positionOption);
            }
            if (this.options.track && event && /^mouse/.test(event.type)) {
                this._on(this.document, {
                    mousemove: position
                });

                // trigger once to override element-relative positioning
                position(event);
            } else {
                tooltip.position($.extend({
                    of: target
                }, this.options.position));
            }

            tooltip.hide();

            this._show(tooltip, this.options.show);

            // Handle tracking tooltips that are shown with a delay (#8644). As soon
            // as the tooltip is visible, position the tooltip using the most recent
            // event.
            // Adds the check to add the timers only when both delay and track options are set (#14682)
            if (this.options.track && this.options.show && this.options.show.delay) {
                delayedShow = this.delayedShow = setInterval(function() {
                    if (tooltip.is(":visible")) {
                        position(positionOption.of);
                        clearInterval(delayedShow);
                    }
                }, $.fx.interval);
            }

            this._trigger("open", event, { tooltip: tooltip });
        },

        _registerCloseHandlers: function(event, target) {
            var events = {
                keyup: function(event) {
                    if (event.keyCode === $.ui.keyCode.ESCAPE) {
                        var fakeEvent = $.Event(event);
                        fakeEvent.currentTarget = target[0];
                        this.close(fakeEvent, true);
                    }
                }
            };

            // Only bind remove handler for delegated targets. Non-delegated
            // tooltips will handle this in destroy.
            if (target[0] !== this.element[0]) {
                events.remove = function() {
                    this._removeTooltip(this._find(target).tooltip);
                };
            }

            if (!event || event.type === "mouseover") {
                events.mouseleave = "close";
            }
            if (!event || event.type === "focusin") {
                events.focusout = "close";
            }
            this._on(true, target, events);
        },

        close: function(event) {
            var tooltip,
                that = this,
                target = $(event ? event.currentTarget : this.element),
                tooltipData = this._find(target);

            // The tooltip may already be closed
            if (!tooltipData) {

                // We set ui-tooltip-open immediately upon open (in open()), but only set the
                // additional data once there's actually content to show (in _open()). So even if the
                // tooltip doesn't have full data, we always remove ui-tooltip-open in case we're in
                // the period between open() and _open().
                target.removeData("ui-tooltip-open");
                return;
            }

            tooltip = tooltipData.tooltip;

            // Disabling closes the tooltip, so we need to track when we're closing
            // to avoid an infinite loop in case the tooltip becomes disabled on close
            if (tooltipData.closing) {
                return;
            }

            // Clear the interval for delayed tracking tooltips
            clearInterval(this.delayedShow);

            // Only set title if we had one before (see comment in _open())
            // If the title attribute has changed since open(), don't restore
            if (target.data("ui-tooltip-title") && !target.attr("title")) {
                target.attr("title", target.data("ui-tooltip-title"));
            }

            this._removeDescribedBy(target);

            tooltipData.hiding = true;
            tooltip.stop(true);
            this._hide(tooltip, this.options.hide, function() {
                that._removeTooltip($(this));
            });

            target.removeData("ui-tooltip-open");
            this._off(target, "mouseleave focusout keyup");

            // Remove 'remove' binding only on delegated targets
            if (target[0] !== this.element[0]) {
                this._off(target, "remove");
            }
            this._off(this.document, "mousemove");

            if (event && event.type === "mouseleave") {
                $.each(this.parents, function(id, parent) {
                    $(parent.element).attr("title", parent.title);
                    delete that.parents[id];
                });
            }

            tooltipData.closing = true;
            this._trigger("close", event, { tooltip: tooltip });
            if (!tooltipData.hiding) {
                tooltipData.closing = false;
            }
        },

        _tooltip: function(element) {
            var tooltip = $("<div>").attr("role", "tooltip"),
                content = $("<div>").appendTo(tooltip),
                id = tooltip.uniqueId().attr("id");

            this._addClass(content, "ui-tooltip-content");
            this._addClass(tooltip, "ui-tooltip", "ui-widget ui-widget-content");

            tooltip.appendTo(this._appendTo(element));

            return this.tooltips[id] = {
                element: element,
                tooltip: tooltip
            };
        },

        _find: function(target) {
            var id = target.data("ui-tooltip-id");
            return id ? this.tooltips[id] : null;
        },

        _removeTooltip: function(tooltip) {
            tooltip.remove();
            delete this.tooltips[tooltip.attr("id")];
        },

        _appendTo: function(target) {
            var element = target.closest(".ui-front, dialog");

            if (!element.length) {
                element = this.document[0].body;
            }

            return element;
        },

        _destroy: function() {
            var that = this;

            // Close open tooltips
            $.each(this.tooltips, function(id, tooltipData) {

                // Delegate to close method to handle common cleanup
                var event = $.Event("blur"),
                    element = tooltipData.element;
                event.target = event.currentTarget = element[0];
                that.close(event, true);

                // Remove immediately; destroying an open tooltip doesn't use the
                // hide animation
                $("#" + id).remove();

                // Restore the title
                if (element.data("ui-tooltip-title")) {

                    // If the title attribute has changed since open(), don't restore
                    if (!element.attr("title")) {
                        element.attr("title", element.data("ui-tooltip-title"));
                    }
                    element.removeData("ui-tooltip-title");
                }
            });
            this.liveRegion.remove();
        }
    });

    // DEPRECATED
    // TODO: Switch return back to widget declaration at top of file when this is removed
    if ($.uiBackCompat !== false) {

        // Backcompat for tooltipClass option
        $.widget("ui.tooltip", $.ui.tooltip, {
            options: {
                tooltipClass: null
            },
            _tooltip: function() {
                var tooltipData = this._superApply(arguments);
                if (this.options.tooltipClass) {
                    tooltipData.tooltip.addClass(this.options.tooltipClass);
                }
                return tooltipData;
            }
        });
    }

    var widgetsTooltip = $.ui.tooltip;


    /*!
     * jQuery UI Effects 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Effects Core
    //>>group: Effects
    // jscs:disable maximumLineLength
    //>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects.
    // jscs:enable maximumLineLength
    //>>docs: http://api.jqueryui.com/category/effects-core/
    //>>demos: http://jqueryui.com/effect/



    var dataSpace = "ui-effects-",
        dataSpaceStyle = "ui-effects-style",
        dataSpaceAnimated = "ui-effects-animated",

        // Create a local jQuery because jQuery Color relies on it and the
        // global may not exist with AMD and a custom build (#10199)
        jQuery = $;

    $.effects = {
        effect: {}
    };

    /*!
     * jQuery Color Animations v2.1.2
     * https://github.com/jquery/jquery-color
     *
     * Copyright 2014 jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     *
     * Date: Wed Jan 16 08:47:09 2013 -0600
     */
    (function(jQuery, undefined) {

        var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor " +
            "borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",

            // Plusequals test for += 100 -= 100
            rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,

            // A set of RE's that can match strings and generate color tuples.
            stringParsers = [{
                re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
                parse: function(execResult) {
                    return [
                        execResult[1],
                        execResult[2],
                        execResult[3],
                        execResult[4]
                    ];
                }
            }, {
                re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
                parse: function(execResult) {
                    return [
                        execResult[1] * 2.55,
                        execResult[2] * 2.55,
                        execResult[3] * 2.55,
                        execResult[4]
                    ];
                }
            }, {

                // This regex ignores A-F because it's compared against an already lowercased string
                re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
                parse: function(execResult) {
                    return [
                        parseInt(execResult[1], 16),
                        parseInt(execResult[2], 16),
                        parseInt(execResult[3], 16)
                    ];
                }
            }, {

                // This regex ignores A-F because it's compared against an already lowercased string
                re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
                parse: function(execResult) {
                    return [
                        parseInt(execResult[1] + execResult[1], 16),
                        parseInt(execResult[2] + execResult[2], 16),
                        parseInt(execResult[3] + execResult[3], 16)
                    ];
                }
            }, {
                re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
                space: "hsla",
                parse: function(execResult) {
                    return [
                        execResult[1],
                        execResult[2] / 100,
                        execResult[3] / 100,
                        execResult[4]
                    ];
                }
            }],

            // JQuery.Color( )
            color = jQuery.Color = function(color, green, blue, alpha) {
                return new jQuery.Color.fn.parse(color, green, blue, alpha);
            },
            spaces = {
                rgba: {
                    props: {
                        red: {
                            idx: 0,
                            type: "byte"
                        },
                        green: {
                            idx: 1,
                            type: "byte"
                        },
                        blue: {
                            idx: 2,
                            type: "byte"
                        }
                    }
                },

                hsla: {
                    props: {
                        hue: {
                            idx: 0,
                            type: "degrees"
                        },
                        saturation: {
                            idx: 1,
                            type: "percent"
                        },
                        lightness: {
                            idx: 2,
                            type: "percent"
                        }
                    }
                }
            },
            propTypes = {
                "byte": {
                    floor: true,
                    max: 255
                },
                "percent": {
                    max: 1
                },
                "degrees": {
                    mod: 360,
                    floor: true
                }
            },
            support = color.support = {},

            // Element for support tests
            supportElem = jQuery("<p>")[0],

            // Colors = jQuery.Color.names
            colors,

            // Local aliases of functions called often
            each = jQuery.each;

        // Determine rgba support immediately
        supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
        support.rgba = supportElem.style.backgroundColor.indexOf("rgba") > -1;

        // Define cache name and alpha properties
        // for rgba and hsla spaces
        each(spaces, function(spaceName, space) {
            space.cache = "_" + spaceName;
            space.props.alpha = {
                idx: 3,
                type: "percent",
                def: 1
            };
        });

        function clamp(value, prop, allowEmpty) {
            var type = propTypes[prop.type] || {};

            if (value == null) {
                return (allowEmpty || !prop.def) ? null : prop.def;
            }

            // ~~ is an short way of doing floor for positive numbers
            value = type.floor ? ~~value : parseFloat(value);

            // IE will pass in empty strings as value for alpha,
            // which will hit this case
            if (isNaN(value)) {
                return prop.def;
            }

            if (type.mod) {

                // We add mod before modding to make sure that negatives values
                // get converted properly: -10 -> 350
                return (value + type.mod) % type.mod;
            }

            // For now all property types without mod have min and max
            return 0 > value ? 0 : type.max < value ? type.max : value;
        }

        function stringParse(string) {
            var inst = color(),
                rgba = inst._rgba = [];

            string = string.toLowerCase();

            each(stringParsers, function(i, parser) {
                var parsed,
                    match = parser.re.exec(string),
                    values = match && parser.parse(match),
                    spaceName = parser.space || "rgba";

                if (values) {
                    parsed = inst[spaceName](values);

                    // If this was an rgba parse the assignment might happen twice
                    // oh well....
                    inst[spaces[spaceName].cache] = parsed[spaces[spaceName].cache];
                    rgba = inst._rgba = parsed._rgba;

                    // Exit each( stringParsers ) here because we matched
                    return false;
                }
            });

            // Found a stringParser that handled it
            if (rgba.length) {

                // If this came from a parsed string, force "transparent" when alpha is 0
                // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
                if (rgba.join() === "0,0,0,0") {
                    jQuery.extend(rgba, colors.transparent);
                }
                return inst;
            }

            // Named colors
            return colors[string];
        }

        color.fn = jQuery.extend(color.prototype, {
            parse: function(red, green, blue, alpha) {
                if (red === undefined) {
                    this._rgba = [null, null, null, null];
                    return this;
                }
                if (red.jquery || red.nodeType) {
                    red = jQuery(red).css(green);
                    green = undefined;
                }

                var inst = this,
                    type = jQuery.type(red),
                    rgba = this._rgba = [];

                // More than 1 argument specified - assume ( red, green, blue, alpha )
                if (green !== undefined) {
                    red = [red, green, blue, alpha];
                    type = "array";
                }

                if (type === "string") {
                    return this.parse(stringParse(red) || colors._default);
                }

                if (type === "array") {
                    each(spaces.rgba.props, function(key, prop) {
                        rgba[prop.idx] = clamp(red[prop.idx], prop);
                    });
                    return this;
                }

                if (type === "object") {
                    if (red instanceof color) {
                        each(spaces, function(spaceName, space) {
                            if (red[space.cache]) {
                                inst[space.cache] = red[space.cache].slice();
                            }
                        });
                    } else {
                        each(spaces, function(spaceName, space) {
                            var cache = space.cache;
                            each(space.props, function(key, prop) {

                                // If the cache doesn't exist, and we know how to convert
                                if (!inst[cache] && space.to) {

                                    // If the value was null, we don't need to copy it
                                    // if the key was alpha, we don't need to copy it either
                                    if (key === "alpha" || red[key] == null) {
                                        return;
                                    }
                                    inst[cache] = space.to(inst._rgba);
                                }

                                // This is the only case where we allow nulls for ALL properties.
                                // call clamp with alwaysAllowEmpty
                                inst[cache][prop.idx] = clamp(red[key], prop, true);
                            });

                            // Everything defined but alpha?
                            if (inst[cache] &&
                                jQuery.inArray(null, inst[cache].slice(0, 3)) < 0) {

                                // Use the default of 1
                                inst[cache][3] = 1;
                                if (space.from) {
                                    inst._rgba = space.from(inst[cache]);
                                }
                            }
                        });
                    }
                    return this;
                }
            },
            is: function(compare) {
                var is = color(compare),
                    same = true,
                    inst = this;

                each(spaces, function(_, space) {
                    var localCache,
                        isCache = is[space.cache];
                    if (isCache) {
                        localCache = inst[space.cache] || space.to && space.to(inst._rgba) || [];
                        each(space.props, function(_, prop) {
                            if (isCache[prop.idx] != null) {
                                same = (isCache[prop.idx] === localCache[prop.idx]);
                                return same;
                            }
                        });
                    }
                    return same;
                });
                return same;
            },
            _space: function() {
                var used = [],
                    inst = this;
                each(spaces, function(spaceName, space) {
                    if (inst[space.cache]) {
                        used.push(spaceName);
                    }
                });
                return used.pop();
            },
            transition: function(other, distance) {
                var end = color(other),
                    spaceName = end._space(),
                    space = spaces[spaceName],
                    startColor = this.alpha() === 0 ? color("transparent") : this,
                    start = startColor[space.cache] || space.to(startColor._rgba),
                    result = start.slice();

                end = end[space.cache];
                each(space.props, function(key, prop) {
                    var index = prop.idx,
                        startValue = start[index],
                        endValue = end[index],
                        type = propTypes[prop.type] || {};

                    // If null, don't override start value
                    if (endValue === null) {
                        return;
                    }

                    // If null - use end
                    if (startValue === null) {
                        result[index] = endValue;
                    } else {
                        if (type.mod) {
                            if (endValue - startValue > type.mod / 2) {
                                startValue += type.mod;
                            } else if (startValue - endValue > type.mod / 2) {
                                startValue -= type.mod;
                            }
                        }
                        result[index] = clamp((endValue - startValue) * distance + startValue, prop);
                    }
                });
                return this[spaceName](result);
            },
            blend: function(opaque) {

                // If we are already opaque - return ourself
                if (this._rgba[3] === 1) {
                    return this;
                }

                var rgb = this._rgba.slice(),
                    a = rgb.pop(),
                    blend = color(opaque)._rgba;

                return color(jQuery.map(rgb, function(v, i) {
                    return (1 - a) * blend[i] + a * v;
                }));
            },
            toRgbaString: function() {
                var prefix = "rgba(",
                    rgba = jQuery.map(this._rgba, function(v, i) {
                        return v == null ? (i > 2 ? 1 : 0) : v;
                    });

                if (rgba[3] === 1) {
                    rgba.pop();
                    prefix = "rgb(";
                }

                return prefix + rgba.join() + ")";
            },
            toHslaString: function() {
                var prefix = "hsla(",
                    hsla = jQuery.map(this.hsla(), function(v, i) {
                        if (v == null) {
                            v = i > 2 ? 1 : 0;
                        }

                        // Catch 1 and 2
                        if (i && i < 3) {
                            v = Math.round(v * 100) + "%";
                        }
                        return v;
                    });

                if (hsla[3] === 1) {
                    hsla.pop();
                    prefix = "hsl(";
                }
                return prefix + hsla.join() + ")";
            },
            toHexString: function(includeAlpha) {
                var rgba = this._rgba.slice(),
                    alpha = rgba.pop();

                if (includeAlpha) {
                    rgba.push(~~(alpha * 255));
                }

                return "#" + jQuery.map(rgba, function(v) {

                    // Default to 0 when nulls exist
                    v = (v || 0).toString(16);
                    return v.length === 1 ? "0" + v : v;
                }).join("");
            },
            toString: function() {
                return this._rgba[3] === 0 ? "transparent" : this.toRgbaString();
            }
        });
        color.fn.parse.prototype = color.fn;

        // Hsla conversions adapted from:
        // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021

        function hue2rgb(p, q, h) {
            h = (h + 1) % 1;
            if (h * 6 < 1) {
                return p + (q - p) * h * 6;
            }
            if (h * 2 < 1) {
                return q;
            }
            if (h * 3 < 2) {
                return p + (q - p) * ((2 / 3) - h) * 6;
            }
            return p;
        }

        spaces.hsla.to = function(rgba) {
            if (rgba[0] == null || rgba[1] == null || rgba[2] == null) {
                return [null, null, null, rgba[3]];
            }
            var r = rgba[0] / 255,
                g = rgba[1] / 255,
                b = rgba[2] / 255,
                a = rgba[3],
                max = Math.max(r, g, b),
                min = Math.min(r, g, b),
                diff = max - min,
                add = max + min,
                l = add * 0.5,
                h, s;

            if (min === max) {
                h = 0;
            } else if (r === max) {
                h = (60 * (g - b) / diff) + 360;
            } else if (g === max) {
                h = (60 * (b - r) / diff) + 120;
            } else {
                h = (60 * (r - g) / diff) + 240;
            }

            // Chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
            // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
            if (diff === 0) {
                s = 0;
            } else if (l <= 0.5) {
                s = diff / add;
            } else {
                s = diff / (2 - add);
            }
            return [Math.round(h) % 360, s, l, a == null ? 1 : a];
        };

        spaces.hsla.from = function(hsla) {
            if (hsla[0] == null || hsla[1] == null || hsla[2] == null) {
                return [null, null, null, hsla[3]];
            }
            var h = hsla[0] / 360,
                s = hsla[1],
                l = hsla[2],
                a = hsla[3],
                q = l <= 0.5 ? l * (1 + s) : l + s - l * s,
                p = 2 * l - q;

            return [
                Math.round(hue2rgb(p, q, h + (1 / 3)) * 255),
                Math.round(hue2rgb(p, q, h) * 255),
                Math.round(hue2rgb(p, q, h - (1 / 3)) * 255),
                a
            ];
        };

        each(spaces, function(spaceName, space) {
            var props = space.props,
                cache = space.cache,
                to = space.to,
                from = space.from;

            // Makes rgba() and hsla()
            color.fn[spaceName] = function(value) {

                // Generate a cache for this space if it doesn't exist
                if (to && !this[cache]) {
                    this[cache] = to(this._rgba);
                }
                if (value === undefined) {
                    return this[cache].slice();
                }

                var ret,
                    type = jQuery.type(value),
                    arr = (type === "array" || type === "object") ? value : arguments,
                    local = this[cache].slice();

                each(props, function(key, prop) {
                    var val = arr[type === "object" ? key : prop.idx];
                    if (val == null) {
                        val = local[prop.idx];
                    }
                    local[prop.idx] = clamp(val, prop);
                });

                if (from) {
                    ret = color(from(local));
                    ret[cache] = local;
                    return ret;
                } else {
                    return color(local);
                }
            };

            // Makes red() green() blue() alpha() hue() saturation() lightness()
            each(props, function(key, prop) {

                // Alpha is included in more than one space
                if (color.fn[key]) {
                    return;
                }
                color.fn[key] = function(value) {
                    var vtype = jQuery.type(value),
                        fn = (key === "alpha" ? (this._hsla ? "hsla" : "rgba") : spaceName),
                        local = this[fn](),
                        cur = local[prop.idx],
                        match;

                    if (vtype === "undefined") {
                        return cur;
                    }

                    if (vtype === "function") {
                        value = value.call(this, cur);
                        vtype = jQuery.type(value);
                    }
                    if (value == null && prop.empty) {
                        return this;
                    }
                    if (vtype === "string") {
                        match = rplusequals.exec(value);
                        if (match) {
                            value = cur + parseFloat(match[2]) * (match[1] === "+" ? 1 : -1);
                        }
                    }
                    local[prop.idx] = value;
                    return this[fn](local);
                };
            });
        });

        // Add cssHook and .fx.step function for each named hook.
        // accept a space separated string of properties
        color.hook = function(hook) {
            var hooks = hook.split(" ");
            each(hooks, function(i, hook) {
                jQuery.cssHooks[hook] = {
                    set: function(elem, value) {
                        var parsed, curElem,
                            backgroundColor = "";

                        if (value !== "transparent" && (jQuery.type(value) !== "string" ||
                                (parsed = stringParse(value)))) {
                            value = color(parsed || value);
                            if (!support.rgba && value._rgba[3] !== 1) {
                                curElem = hook === "backgroundColor" ? elem.parentNode : elem;
                                while (
                                    (backgroundColor === "" || backgroundColor === "transparent") &&
                                    curElem && curElem.style
                                ) {
                                    try {
                                        backgroundColor = jQuery.css(curElem, "backgroundColor");
                                        curElem = curElem.parentNode;
                                    } catch (e) {}
                                }

                                value = value.blend(backgroundColor && backgroundColor !== "transparent" ?
                                    backgroundColor :
                                    "_default");
                            }

                            value = value.toRgbaString();
                        }
                        try {
                            elem.style[hook] = value;
                        } catch (e) {

                            // Wrapped to prevent IE from throwing errors on "invalid" values like
                            // 'auto' or 'inherit'
                        }
                    }
                };
                jQuery.fx.step[hook] = function(fx) {
                    if (!fx.colorInit) {
                        fx.start = color(fx.elem, hook);
                        fx.end = color(fx.end);
                        fx.colorInit = true;
                    }
                    jQuery.cssHooks[hook].set(fx.elem, fx.start.transition(fx.end, fx.pos));
                };
            });

        };

        color.hook(stepHooks);

        jQuery.cssHooks.borderColor = {
            expand: function(value) {
                var expanded = {};

                each(["Top", "Right", "Bottom", "Left"], function(i, part) {
                    expanded["border" + part + "Color"] = value;
                });
                return expanded;
            }
        };

        // Basic color names only.
        // Usage of any of the other color names requires adding yourself or including
        // jquery.color.svg-names.js.
        colors = jQuery.Color.names = {

            // 4.1. Basic color keywords
            aqua: "#00ffff",
            black: "#000000",
            blue: "#0000ff",
            fuchsia: "#ff00ff",
            gray: "#808080",
            green: "#008000",
            lime: "#00ff00",
            maroon: "#800000",
            navy: "#000080",
            olive: "#808000",
            purple: "#800080",
            red: "#ff0000",
            silver: "#c0c0c0",
            teal: "#008080",
            white: "#ffffff",
            yellow: "#ffff00",

            // 4.2.3. "transparent" color keyword
            transparent: [null, null, null, 0],

            _default: "#ffffff"
        };

    })(jQuery);

    /******************************************************************************/
    /****************************** CLASS ANIMATIONS ******************************/
    /******************************************************************************/
    (function() {

        var classAnimationActions = ["add", "remove", "toggle"],
            shorthandStyles = {
                border: 1,
                borderBottom: 1,
                borderColor: 1,
                borderLeft: 1,
                borderRight: 1,
                borderTop: 1,
                borderWidth: 1,
                margin: 1,
                padding: 1
            };

        $.each(
            ["borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle"],
            function(_, prop) {
                $.fx.step[prop] = function(fx) {
                    if (fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr) {
                        jQuery.style(fx.elem, prop, fx.end);
                        fx.setAttr = true;
                    }
                };
            }
        );

        function getElementStyles(elem) {
            var key, len,
                style = elem.ownerDocument.defaultView ?
                elem.ownerDocument.defaultView.getComputedStyle(elem, null) :
                elem.currentStyle,
                styles = {};

            if (style && style.length && style[0] && style[style[0]]) {
                len = style.length;
                while (len--) {
                    key = style[len];
                    if (typeof style[key] === "string") {
                        styles[$.camelCase(key)] = style[key];
                    }
                }

                // Support: Opera, IE <9
            } else {
                for (key in style) {
                    if (typeof style[key] === "string") {
                        styles[key] = style[key];
                    }
                }
            }

            return styles;
        }

        function styleDifference(oldStyle, newStyle) {
            var diff = {},
                name, value;

            for (name in newStyle) {
                value = newStyle[name];
                if (oldStyle[name] !== value) {
                    if (!shorthandStyles[name]) {
                        if ($.fx.step[name] || !isNaN(parseFloat(value))) {
                            diff[name] = value;
                        }
                    }
                }
            }

            return diff;
        }

        // Support: jQuery <1.8
        if (!$.fn.addBack) {
            $.fn.addBack = function(selector) {
                return this.add(selector == null ?
                    this.prevObject : this.prevObject.filter(selector)
                );
            };
        }

        $.effects.animateClass = function(value, duration, easing, callback) {
            var o = $.speed(duration, easing, callback);

            return this.queue(function() {
                var animated = $(this),
                    baseClass = animated.attr("class") || "",
                    applyClassChange,
                    allAnimations = o.children ? animated.find("*").addBack() : animated;

                // Map the animated objects to store the original styles.
                allAnimations = allAnimations.map(function() {
                    var el = $(this);
                    return {
                        el: el,
                        start: getElementStyles(this)
                    };
                });

                // Apply class change
                applyClassChange = function() {
                    $.each(classAnimationActions, function(i, action) {
                        if (value[action]) {
                            animated[action + "Class"](value[action]);
                        }
                    });
                };
                applyClassChange();

                // Map all animated objects again - calculate new styles and diff
                allAnimations = allAnimations.map(function() {
                    this.end = getElementStyles(this.el[0]);
                    this.diff = styleDifference(this.start, this.end);
                    return this;
                });

                // Apply original class
                animated.attr("class", baseClass);

                // Map all animated objects again - this time collecting a promise
                allAnimations = allAnimations.map(function() {
                    var styleInfo = this,
                        dfd = $.Deferred(),
                        opts = $.extend({}, o, {
                            queue: false,
                            complete: function() {
                                dfd.resolve(styleInfo);
                            }
                        });

                    this.el.animate(this.diff, opts);
                    return dfd.promise();
                });

                // Once all animations have completed:
                $.when.apply($, allAnimations.get()).done(function() {

                    // Set the final class
                    applyClassChange();

                    // For each animated element,
                    // clear all css properties that were animated
                    $.each(arguments, function() {
                        var el = this.el;
                        $.each(this.diff, function(key) {
                            el.css(key, "");
                        });
                    });

                    // This is guarnteed to be there if you use jQuery.speed()
                    // it also handles dequeuing the next anim...
                    o.complete.call(animated[0]);
                });
            });
        };

        $.fn.extend({
            addClass: (function(orig) {
                return function(classNames, speed, easing, callback) {
                    return speed ?
                        $.effects.animateClass.call(this, { add: classNames }, speed, easing, callback) :
                        orig.apply(this, arguments);
                };
            })($.fn.addClass),

            removeClass: (function(orig) {
                return function(classNames, speed, easing, callback) {
                    return arguments.length > 1 ?
                        $.effects.animateClass.call(this, { remove: classNames }, speed, easing, callback) :
                        orig.apply(this, arguments);
                };
            })($.fn.removeClass),

            toggleClass: (function(orig) {
                return function(classNames, force, speed, easing, callback) {
                    if (typeof force === "boolean" || force === undefined) {
                        if (!speed) {

                            // Without speed parameter
                            return orig.apply(this, arguments);
                        } else {
                            return $.effects.animateClass.call(this,
                                (force ? { add: classNames } : { remove: classNames }),
                                speed, easing, callback);
                        }
                    } else {

                        // Without force parameter
                        return $.effects.animateClass.call(this, { toggle: classNames }, force, speed, easing);
                    }
                };
            })($.fn.toggleClass),

            switchClass: function(remove, add, speed, easing, callback) {
                return $.effects.animateClass.call(this, {
                    add: add,
                    remove: remove
                }, speed, easing, callback);
            }
        });

    })();

    /******************************************************************************/
    /*********************************** EFFECTS **********************************/
    /******************************************************************************/

    (function() {

        if ($.expr && $.expr.filters && $.expr.filters.animated) {
            $.expr.filters.animated = (function(orig) {
                return function(elem) {
                    return !!$(elem).data(dataSpaceAnimated) || orig(elem);
                };
            })($.expr.filters.animated);
        }

        if ($.uiBackCompat !== false) {
            $.extend($.effects, {

                // Saves a set of properties in a data storage
                save: function(element, set) {
                    var i = 0,
                        length = set.length;
                    for (; i < length; i++) {
                        if (set[i] !== null) {
                            element.data(dataSpace + set[i], element[0].style[set[i]]);
                        }
                    }
                },

                // Restores a set of previously saved properties from a data storage
                restore: function(element, set) {
                    var val, i = 0,
                        length = set.length;
                    for (; i < length; i++) {
                        if (set[i] !== null) {
                            val = element.data(dataSpace + set[i]);
                            element.css(set[i], val);
                        }
                    }
                },

                setMode: function(el, mode) {
                    if (mode === "toggle") {
                        mode = el.is(":hidden") ? "show" : "hide";
                    }
                    return mode;
                },

                // Wraps the element around a wrapper that copies position properties
                createWrapper: function(element) {

                    // If the element is already wrapped, return it
                    if (element.parent().is(".ui-effects-wrapper")) {
                        return element.parent();
                    }

                    // Wrap the element
                    var props = {
                            width: element.outerWidth(true),
                            height: element.outerHeight(true),
                            "float": element.css("float")
                        },
                        wrapper = $("<div></div>")
                        .addClass("ui-effects-wrapper")
                        .css({
                            fontSize: "100%",
                            background: "transparent",
                            border: "none",
                            margin: 0,
                            padding: 0
                        }),

                        // Store the size in case width/height are defined in % - Fixes #5245
                        size = {
                            width: element.width(),
                            height: element.height()
                        },
                        active = document.activeElement;

                    // Support: Firefox
                    // Firefox incorrectly exposes anonymous content
                    // https://bugzilla.mozilla.org/show_bug.cgi?id=561664
                    try {
                        active.id;
                    } catch (e) {
                        active = document.body;
                    }

                    element.wrap(wrapper);

                    // Fixes #7595 - Elements lose focus when wrapped.
                    if (element[0] === active || $.contains(element[0], active)) {
                        $(active).trigger("focus");
                    }

                    // Hotfix for jQuery 1.4 since some change in wrap() seems to actually
                    // lose the reference to the wrapped element
                    wrapper = element.parent();

                    // Transfer positioning properties to the wrapper
                    if (element.css("position") === "static") {
                        wrapper.css({ position: "relative" });
                        element.css({ position: "relative" });
                    } else {
                        $.extend(props, {
                            position: element.css("position"),
                            zIndex: element.css("z-index")
                        });
                        $.each(["top", "left", "bottom", "right"], function(i, pos) {
                            props[pos] = element.css(pos);
                            if (isNaN(parseInt(props[pos], 10))) {
                                props[pos] = "auto";
                            }
                        });
                        element.css({
                            position: "relative",
                            top: 0,
                            left: 0,
                            right: "auto",
                            bottom: "auto"
                        });
                    }
                    element.css(size);

                    return wrapper.css(props).show();
                },

                removeWrapper: function(element) {
                    var active = document.activeElement;

                    if (element.parent().is(".ui-effects-wrapper")) {
                        element.parent().replaceWith(element);

                        // Fixes #7595 - Elements lose focus when wrapped.
                        if (element[0] === active || $.contains(element[0], active)) {
                            $(active).trigger("focus");
                        }
                    }

                    return element;
                }
            });
        }

        $.extend($.effects, {
            version: "1.12.1",

            define: function(name, mode, effect) {
                if (!effect) {
                    effect = mode;
                    mode = "effect";
                }

                $.effects.effect[name] = effect;
                $.effects.effect[name].mode = mode;

                return effect;
            },

            scaledDimensions: function(element, percent, direction) {
                if (percent === 0) {
                    return {
                        height: 0,
                        width: 0,
                        outerHeight: 0,
                        outerWidth: 0
                    };
                }

                var x = direction !== "horizontal" ? ((percent || 100) / 100) : 1,
                    y = direction !== "vertical" ? ((percent || 100) / 100) : 1;

                return {
                    height: element.height() * y,
                    width: element.width() * x,
                    outerHeight: element.outerHeight() * y,
                    outerWidth: element.outerWidth() * x
                };

            },

            clipToBox: function(animation) {
                return {
                    width: animation.clip.right - animation.clip.left,
                    height: animation.clip.bottom - animation.clip.top,
                    left: animation.clip.left,
                    top: animation.clip.top
                };
            },

            // Injects recently queued functions to be first in line (after "inprogress")
            unshift: function(element, queueLength, count) {
                var queue = element.queue();

                if (queueLength > 1) {
                    queue.splice.apply(queue, [1, 0].concat(queue.splice(queueLength, count)));
                }
                element.dequeue();
            },

            saveStyle: function(element) {
                element.data(dataSpaceStyle, element[0].style.cssText);
            },

            restoreStyle: function(element) {
                element[0].style.cssText = element.data(dataSpaceStyle) || "";
                element.removeData(dataSpaceStyle);
            },

            mode: function(element, mode) {
                var hidden = element.is(":hidden");

                if (mode === "toggle") {
                    mode = hidden ? "show" : "hide";
                }
                if (hidden ? mode === "hide" : mode === "show") {
                    mode = "none";
                }
                return mode;
            },

            // Translates a [top,left] array into a baseline value
            getBaseline: function(origin, original) {
                var y, x;

                switch (origin[0]) {
                    case "top":
                        y = 0;
                        break;
                    case "middle":
                        y = 0.5;
                        break;
                    case "bottom":
                        y = 1;
                        break;
                    default:
                        y = origin[0] / original.height;
                }

                switch (origin[1]) {
                    case "left":
                        x = 0;
                        break;
                    case "center":
                        x = 0.5;
                        break;
                    case "right":
                        x = 1;
                        break;
                    default:
                        x = origin[1] / original.width;
                }

                return {
                    x: x,
                    y: y
                };
            },

            // Creates a placeholder element so that the original element can be made absolute
            createPlaceholder: function(element) {
                var placeholder,
                    cssPosition = element.css("position"),
                    position = element.position();

                // Lock in margins first to account for form elements, which
                // will change margin if you explicitly set height
                // see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380
                // Support: Safari
                element.css({
                        marginTop: element.css("marginTop"),
                        marginBottom: element.css("marginBottom"),
                        marginLeft: element.css("marginLeft"),
                        marginRight: element.css("marginRight")
                    })
                    .outerWidth(element.outerWidth())
                    .outerHeight(element.outerHeight());

                if (/^(static|relative)/.test(cssPosition)) {
                    cssPosition = "absolute";

                    placeholder = $("<" + element[0].nodeName + ">").insertAfter(element).css({

                            // Convert inline to inline block to account for inline elements
                            // that turn to inline block based on content (like img)
                            display: /^(inline|ruby)/.test(element.css("display")) ?
                                "inline-block" : "block",
                            visibility: "hidden",

                            // Margins need to be set to account for margin collapse
                            marginTop: element.css("marginTop"),
                            marginBottom: element.css("marginBottom"),
                            marginLeft: element.css("marginLeft"),
                            marginRight: element.css("marginRight"),
                            "float": element.css("float")
                        })
                        .outerWidth(element.outerWidth())
                        .outerHeight(element.outerHeight())
                        .addClass("ui-effects-placeholder");

                    element.data(dataSpace + "placeholder", placeholder);
                }

                element.css({
                    position: cssPosition,
                    left: position.left,
                    top: position.top
                });

                return placeholder;
            },

            removePlaceholder: function(element) {
                var dataKey = dataSpace + "placeholder",
                    placeholder = element.data(dataKey);

                if (placeholder) {
                    placeholder.remove();
                    element.removeData(dataKey);
                }
            },

            // Removes a placeholder if it exists and restores
            // properties that were modified during placeholder creation
            cleanUp: function(element) {
                $.effects.restoreStyle(element);
                $.effects.removePlaceholder(element);
            },

            setTransition: function(element, list, factor, value) {
                value = value || {};
                $.each(list, function(i, x) {
                    var unit = element.cssUnit(x);
                    if (unit[0] > 0) {
                        value[x] = unit[0] * factor + unit[1];
                    }
                });
                return value;
            }
        });

        // Return an effect options object for the given parameters:
        function _normalizeArguments(effect, options, speed, callback) {

            // Allow passing all options as the first parameter
            if ($.isPlainObject(effect)) {
                options = effect;
                effect = effect.effect;
            }

            // Convert to an object
            effect = { effect: effect };

            // Catch (effect, null, ...)
            if (options == null) {
                options = {};
            }

            // Catch (effect, callback)
            if ($.isFunction(options)) {
                callback = options;
                speed = null;
                options = {};
            }

            // Catch (effect, speed, ?)
            if (typeof options === "number" || $.fx.speeds[options]) {
                callback = speed;
                speed = options;
                options = {};
            }

            // Catch (effect, options, callback)
            if ($.isFunction(speed)) {
                callback = speed;
                speed = null;
            }

            // Add options to effect
            if (options) {
                $.extend(effect, options);
            }

            speed = speed || options.duration;
            effect.duration = $.fx.off ? 0 :
                typeof speed === "number" ? speed :
                speed in $.fx.speeds ? $.fx.speeds[speed] :
                $.fx.speeds._default;

            effect.complete = callback || options.complete;

            return effect;
        }

        function standardAnimationOption(option) {

            // Valid standard speeds (nothing, number, named speed)
            if (!option || typeof option === "number" || $.fx.speeds[option]) {
                return true;
            }

            // Invalid strings - treat as "normal" speed
            if (typeof option === "string" && !$.effects.effect[option]) {
                return true;
            }

            // Complete callback
            if ($.isFunction(option)) {
                return true;
            }

            // Options hash (but not naming an effect)
            if (typeof option === "object" && !option.effect) {
                return true;
            }

            // Didn't match any standard API
            return false;
        }

        $.fn.extend({
            effect: function( /* effect, options, speed, callback */ ) {
                var args = _normalizeArguments.apply(this, arguments),
                    effectMethod = $.effects.effect[args.effect],
                    defaultMode = effectMethod.mode,
                    queue = args.queue,
                    queueName = queue || "fx",
                    complete = args.complete,
                    mode = args.mode,
                    modes = [],
                    prefilter = function(next) {
                        var el = $(this),
                            normalizedMode = $.effects.mode(el, mode) || defaultMode;

                        // Sentinel for duck-punching the :animated psuedo-selector
                        el.data(dataSpaceAnimated, true);

                        // Save effect mode for later use,
                        // we can't just call $.effects.mode again later,
                        // as the .show() below destroys the initial state
                        modes.push(normalizedMode);

                        // See $.uiBackCompat inside of run() for removal of defaultMode in 1.13
                        if (defaultMode && (normalizedMode === "show" ||
                                (normalizedMode === defaultMode && normalizedMode === "hide"))) {
                            el.show();
                        }

                        if (!defaultMode || normalizedMode !== "none") {
                            $.effects.saveStyle(el);
                        }

                        if ($.isFunction(next)) {
                            next();
                        }
                    };

                if ($.fx.off || !effectMethod) {

                    // Delegate to the original method (e.g., .show()) if possible
                    if (mode) {
                        return this[mode](args.duration, complete);
                    } else {
                        return this.each(function() {
                            if (complete) {
                                complete.call(this);
                            }
                        });
                    }
                }

                function run(next) {
                    var elem = $(this);

                    function cleanup() {
                        elem.removeData(dataSpaceAnimated);

                        $.effects.cleanUp(elem);

                        if (args.mode === "hide") {
                            elem.hide();
                        }

                        done();
                    }

                    function done() {
                        if ($.isFunction(complete)) {
                            complete.call(elem[0]);
                        }

                        if ($.isFunction(next)) {
                            next();
                        }
                    }

                    // Override mode option on a per element basis,
                    // as toggle can be either show or hide depending on element state
                    args.mode = modes.shift();

                    if ($.uiBackCompat !== false && !defaultMode) {
                        if (elem.is(":hidden") ? mode === "hide" : mode === "show") {

                            // Call the core method to track "olddisplay" properly
                            elem[mode]();
                            done();
                        } else {
                            effectMethod.call(elem[0], args, done);
                        }
                    } else {
                        if (args.mode === "none") {

                            // Call the core method to track "olddisplay" properly
                            elem[mode]();
                            done();
                        } else {
                            effectMethod.call(elem[0], args, cleanup);
                        }
                    }
                }

                // Run prefilter on all elements first to ensure that
                // any showing or hiding happens before placeholder creation,
                // which ensures that any layout changes are correctly captured.
                return queue === false ?
                    this.each(prefilter).each(run) :
                    this.queue(queueName, prefilter).queue(queueName, run);
            },

            show: (function(orig) {
                return function(option) {
                    if (standardAnimationOption(option)) {
                        return orig.apply(this, arguments);
                    } else {
                        var args = _normalizeArguments.apply(this, arguments);
                        args.mode = "show";
                        return this.effect.call(this, args);
                    }
                };
            })($.fn.show),

            hide: (function(orig) {
                return function(option) {
                    if (standardAnimationOption(option)) {
                        return orig.apply(this, arguments);
                    } else {
                        var args = _normalizeArguments.apply(this, arguments);
                        args.mode = "hide";
                        return this.effect.call(this, args);
                    }
                };
            })($.fn.hide),

            toggle: (function(orig) {
                return function(option) {
                    if (standardAnimationOption(option) || typeof option === "boolean") {
                        return orig.apply(this, arguments);
                    } else {
                        var args = _normalizeArguments.apply(this, arguments);
                        args.mode = "toggle";
                        return this.effect.call(this, args);
                    }
                };
            })($.fn.toggle),

            cssUnit: function(key) {
                var style = this.css(key),
                    val = [];

                $.each(["em", "px", "%", "pt"], function(i, unit) {
                    if (style.indexOf(unit) > 0) {
                        val = [parseFloat(style), unit];
                    }
                });
                return val;
            },

            cssClip: function(clipObj) {
                if (clipObj) {
                    return this.css("clip", "rect(" + clipObj.top + "px " + clipObj.right + "px " +
                        clipObj.bottom + "px " + clipObj.left + "px)");
                }
                return parseClip(this.css("clip"), this);
            },

            transfer: function(options, done) {
                var element = $(this),
                    target = $(options.to),
                    targetFixed = target.css("position") === "fixed",
                    body = $("body"),
                    fixTop = targetFixed ? body.scrollTop() : 0,
                    fixLeft = targetFixed ? body.scrollLeft() : 0,
                    endPosition = target.offset(),
                    animation = {
                        top: endPosition.top - fixTop,
                        left: endPosition.left - fixLeft,
                        height: target.innerHeight(),
                        width: target.innerWidth()
                    },
                    startPosition = element.offset(),
                    transfer = $("<div class='ui-effects-transfer'></div>")
                    .appendTo("body")
                    .addClass(options.className)
                    .css({
                        top: startPosition.top - fixTop,
                        left: startPosition.left - fixLeft,
                        height: element.innerHeight(),
                        width: element.innerWidth(),
                        position: targetFixed ? "fixed" : "absolute"
                    })
                    .animate(animation, options.duration, options.easing, function() {
                        transfer.remove();
                        if ($.isFunction(done)) {
                            done();
                        }
                    });
            }
        });

        function parseClip(str, element) {
            var outerWidth = element.outerWidth(),
                outerHeight = element.outerHeight(),
                clipRegex = /^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,
                values = clipRegex.exec(str) || ["", 0, outerWidth, outerHeight, 0];

            return {
                top: parseFloat(values[1]) || 0,
                right: values[2] === "auto" ? outerWidth : parseFloat(values[2]),
                bottom: values[3] === "auto" ? outerHeight : parseFloat(values[3]),
                left: parseFloat(values[4]) || 0
            };
        }

        $.fx.step.clip = function(fx) {
            if (!fx.clipInit) {
                fx.start = $(fx.elem).cssClip();
                if (typeof fx.end === "string") {
                    fx.end = parseClip(fx.end, fx.elem);
                }
                fx.clipInit = true;
            }

            $(fx.elem).cssClip({
                top: fx.pos * (fx.end.top - fx.start.top) + fx.start.top,
                right: fx.pos * (fx.end.right - fx.start.right) + fx.start.right,
                bottom: fx.pos * (fx.end.bottom - fx.start.bottom) + fx.start.bottom,
                left: fx.pos * (fx.end.left - fx.start.left) + fx.start.left
            });
        };

    })();

    /******************************************************************************/
    /*********************************** EASING ***********************************/
    /******************************************************************************/

    (function() {

        // Based on easing equations from Robert Penner (http://www.robertpenner.com/easing)

        var baseEasings = {};

        $.each(["Quad", "Cubic", "Quart", "Quint", "Expo"], function(i, name) {
            baseEasings[name] = function(p) {
                return Math.pow(p, i + 2);
            };
        });

        $.extend(baseEasings, {
            Sine: function(p) {
                return 1 - Math.cos(p * Math.PI / 2);
            },
            Circ: function(p) {
                return 1 - Math.sqrt(1 - p * p);
            },
            Elastic: function(p) {
                return p === 0 || p === 1 ? p :
                    -Math.pow(2, 8 * (p - 1)) * Math.sin(((p - 1) * 80 - 7.5) * Math.PI / 15);
            },
            Back: function(p) {
                return p * p * (3 * p - 2);
            },
            Bounce: function(p) {
                var pow2,
                    bounce = 4;

                while (p < ((pow2 = Math.pow(2, --bounce)) - 1) / 11) {}
                return 1 / Math.pow(4, 3 - bounce) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - p, 2);
            }
        });

        $.each(baseEasings, function(name, easeIn) {
            $.easing["easeIn" + name] = easeIn;
            $.easing["easeOut" + name] = function(p) {
                return 1 - easeIn(1 - p);
            };
            $.easing["easeInOut" + name] = function(p) {
                return p < 0.5 ?
                    easeIn(p * 2) / 2 :
                    1 - easeIn(p * -2 + 2) / 2;
            };
        });

    })();

    var effect = $.effects;


    /*!
     * jQuery UI Effects Blind 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Blind Effect
    //>>group: Effects
    //>>description: Blinds the element.
    //>>docs: http://api.jqueryui.com/blind-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectBlind = $.effects.define("blind", "hide", function(options, done) {
        var map = {
                up: ["bottom", "top"],
                vertical: ["bottom", "top"],
                down: ["top", "bottom"],
                left: ["right", "left"],
                horizontal: ["right", "left"],
                right: ["left", "right"]
            },
            element = $(this),
            direction = options.direction || "up",
            start = element.cssClip(),
            animate = { clip: $.extend({}, start) },
            placeholder = $.effects.createPlaceholder(element);

        animate.clip[map[direction][0]] = animate.clip[map[direction][1]];

        if (options.mode === "show") {
            element.cssClip(animate.clip);
            if (placeholder) {
                placeholder.css($.effects.clipToBox(animate));
            }

            animate.clip = start;
        }

        if (placeholder) {
            placeholder.animate($.effects.clipToBox(animate), options.duration, options.easing);
        }

        element.animate(animate, {
            queue: false,
            duration: options.duration,
            easing: options.easing,
            complete: done
        });
    });


    /*!
     * jQuery UI Effects Bounce 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Bounce Effect
    //>>group: Effects
    //>>description: Bounces an element horizontally or vertically n times.
    //>>docs: http://api.jqueryui.com/bounce-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectBounce = $.effects.define("bounce", function(options, done) {
        var upAnim, downAnim, refValue,
            element = $(this),

            // Defaults:
            mode = options.mode,
            hide = mode === "hide",
            show = mode === "show",
            direction = options.direction || "up",
            distance = options.distance,
            times = options.times || 5,

            // Number of internal animations
            anims = times * 2 + (show || hide ? 1 : 0),
            speed = options.duration / anims,
            easing = options.easing,

            // Utility:
            ref = (direction === "up" || direction === "down") ? "top" : "left",
            motion = (direction === "up" || direction === "left"),
            i = 0,

            queuelen = element.queue().length;

        $.effects.createPlaceholder(element);

        refValue = element.css(ref);

        // Default distance for the BIGGEST bounce is the outer Distance / 3
        if (!distance) {
            distance = element[ref === "top" ? "outerHeight" : "outerWidth"]() / 3;
        }

        if (show) {
            downAnim = { opacity: 1 };
            downAnim[ref] = refValue;

            // If we are showing, force opacity 0 and set the initial position
            // then do the "first" animation
            element
                .css("opacity", 0)
                .css(ref, motion ? -distance * 2 : distance * 2)
                .animate(downAnim, speed, easing);
        }

        // Start at the smallest distance if we are hiding
        if (hide) {
            distance = distance / Math.pow(2, times - 1);
        }

        downAnim = {};
        downAnim[ref] = refValue;

        // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
        for (; i < times; i++) {
            upAnim = {};
            upAnim[ref] = (motion ? "-=" : "+=") + distance;

            element
                .animate(upAnim, speed, easing)
                .animate(downAnim, speed, easing);

            distance = hide ? distance * 2 : distance / 2;
        }

        // Last Bounce when Hiding
        if (hide) {
            upAnim = { opacity: 0 };
            upAnim[ref] = (motion ? "-=" : "+=") + distance;

            element.animate(upAnim, speed, easing);
        }

        element.queue(done);

        $.effects.unshift(element, queuelen, anims + 1);
    });


    /*!
     * jQuery UI Effects Clip 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Clip Effect
    //>>group: Effects
    //>>description: Clips the element on and off like an old TV.
    //>>docs: http://api.jqueryui.com/clip-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectClip = $.effects.define("clip", "hide", function(options, done) {
        var start,
            animate = {},
            element = $(this),
            direction = options.direction || "vertical",
            both = direction === "both",
            horizontal = both || direction === "horizontal",
            vertical = both || direction === "vertical";

        start = element.cssClip();
        animate.clip = {
            top: vertical ? (start.bottom - start.top) / 2 : start.top,
            right: horizontal ? (start.right - start.left) / 2 : start.right,
            bottom: vertical ? (start.bottom - start.top) / 2 : start.bottom,
            left: horizontal ? (start.right - start.left) / 2 : start.left
        };

        $.effects.createPlaceholder(element);

        if (options.mode === "show") {
            element.cssClip(animate.clip);
            animate.clip = start;
        }

        element.animate(animate, {
            queue: false,
            duration: options.duration,
            easing: options.easing,
            complete: done
        });

    });


    /*!
     * jQuery UI Effects Drop 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Drop Effect
    //>>group: Effects
    //>>description: Moves an element in one direction and hides it at the same time.
    //>>docs: http://api.jqueryui.com/drop-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectDrop = $.effects.define("drop", "hide", function(options, done) {

        var distance,
            element = $(this),
            mode = options.mode,
            show = mode === "show",
            direction = options.direction || "left",
            ref = (direction === "up" || direction === "down") ? "top" : "left",
            motion = (direction === "up" || direction === "left") ? "-=" : "+=",
            oppositeMotion = (motion === "+=") ? "-=" : "+=",
            animation = {
                opacity: 0
            };

        $.effects.createPlaceholder(element);

        distance = options.distance ||
            element[ref === "top" ? "outerHeight" : "outerWidth"](true) / 2;

        animation[ref] = motion + distance;

        if (show) {
            element.css(animation);

            animation[ref] = oppositeMotion + distance;
            animation.opacity = 1;
        }

        // Animate
        element.animate(animation, {
            queue: false,
            duration: options.duration,
            easing: options.easing,
            complete: done
        });
    });


    /*!
     * jQuery UI Effects Explode 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Explode Effect
    //>>group: Effects
    // jscs:disable maximumLineLength
    //>>description: Explodes an element in all directions into n pieces. Implodes an element to its original wholeness.
    // jscs:enable maximumLineLength
    //>>docs: http://api.jqueryui.com/explode-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectExplode = $.effects.define("explode", "hide", function(options, done) {

        var i, j, left, top, mx, my,
            rows = options.pieces ? Math.round(Math.sqrt(options.pieces)) : 3,
            cells = rows,
            element = $(this),
            mode = options.mode,
            show = mode === "show",

            // Show and then visibility:hidden the element before calculating offset
            offset = element.show().css("visibility", "hidden").offset(),

            // Width and height of a piece
            width = Math.ceil(element.outerWidth() / cells),
            height = Math.ceil(element.outerHeight() / rows),
            pieces = [];

        // Children animate complete:
        function childComplete() {
            pieces.push(this);
            if (pieces.length === rows * cells) {
                animComplete();
            }
        }

        // Clone the element for each row and cell.
        for (i = 0; i < rows; i++) { // ===>
            top = offset.top + i * height;
            my = i - (rows - 1) / 2;

            for (j = 0; j < cells; j++) { // |||
                left = offset.left + j * width;
                mx = j - (cells - 1) / 2;

                // Create a clone of the now hidden main element that will be absolute positioned
                // within a wrapper div off the -left and -top equal to size of our pieces
                element
                    .clone()
                    .appendTo("body")
                    .wrap("<div></div>")
                    .css({
                        position: "absolute",
                        visibility: "visible",
                        left: -j * width,
                        top: -i * height
                    })

                // Select the wrapper - make it overflow: hidden and absolute positioned based on
                // where the original was located +left and +top equal to the size of pieces
                .parent()
                    .addClass("ui-effects-explode")
                    .css({
                        position: "absolute",
                        overflow: "hidden",
                        width: width,
                        height: height,
                        left: left + (show ? mx * width : 0),
                        top: top + (show ? my * height : 0),
                        opacity: show ? 0 : 1
                    })
                    .animate({
                        left: left + (show ? 0 : mx * width),
                        top: top + (show ? 0 : my * height),
                        opacity: show ? 1 : 0
                    }, options.duration || 500, options.easing, childComplete);
            }
        }

        function animComplete() {
            element.css({
                visibility: "visible"
            });
            $(pieces).remove();
            done();
        }
    });


    /*!
     * jQuery UI Effects Fade 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Fade Effect
    //>>group: Effects
    //>>description: Fades the element.
    //>>docs: http://api.jqueryui.com/fade-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectFade = $.effects.define("fade", "toggle", function(options, done) {
        var show = options.mode === "show";

        $(this)
            .css("opacity", show ? 0 : 1)
            .animate({
                opacity: show ? 1 : 0
            }, {
                queue: false,
                duration: options.duration,
                easing: options.easing,
                complete: done
            });
    });


    /*!
     * jQuery UI Effects Fold 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Fold Effect
    //>>group: Effects
    //>>description: Folds an element first horizontally and then vertically.
    //>>docs: http://api.jqueryui.com/fold-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectFold = $.effects.define("fold", "hide", function(options, done) {

        // Create element
        var element = $(this),
            mode = options.mode,
            show = mode === "show",
            hide = mode === "hide",
            size = options.size || 15,
            percent = /([0-9]+)%/.exec(size),
            horizFirst = !!options.horizFirst,
            ref = horizFirst ? ["right", "bottom"] : ["bottom", "right"],
            duration = options.duration / 2,

            placeholder = $.effects.createPlaceholder(element),

            start = element.cssClip(),
            animation1 = { clip: $.extend({}, start) },
            animation2 = { clip: $.extend({}, start) },

            distance = [start[ref[0]], start[ref[1]]],

            queuelen = element.queue().length;

        if (percent) {
            size = parseInt(percent[1], 10) / 100 * distance[hide ? 0 : 1];
        }
        animation1.clip[ref[0]] = size;
        animation2.clip[ref[0]] = size;
        animation2.clip[ref[1]] = 0;

        if (show) {
            element.cssClip(animation2.clip);
            if (placeholder) {
                placeholder.css($.effects.clipToBox(animation2));
            }

            animation2.clip = start;
        }

        // Animate
        element
            .queue(function(next) {
                if (placeholder) {
                    placeholder
                        .animate($.effects.clipToBox(animation1), duration, options.easing)
                        .animate($.effects.clipToBox(animation2), duration, options.easing);
                }

                next();
            })
            .animate(animation1, duration, options.easing)
            .animate(animation2, duration, options.easing)
            .queue(done);

        $.effects.unshift(element, queuelen, 4);
    });


    /*!
     * jQuery UI Effects Highlight 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Highlight Effect
    //>>group: Effects
    //>>description: Highlights the background of an element in a defined color for a custom duration.
    //>>docs: http://api.jqueryui.com/highlight-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectHighlight = $.effects.define("highlight", "show", function(options, done) {
        var element = $(this),
            animation = {
                backgroundColor: element.css("backgroundColor")
            };

        if (options.mode === "hide") {
            animation.opacity = 0;
        }

        $.effects.saveStyle(element);

        element
            .css({
                backgroundImage: "none",
                backgroundColor: options.color || "#ffff99"
            })
            .animate(animation, {
                queue: false,
                duration: options.duration,
                easing: options.easing,
                complete: done
            });
    });


    /*!
     * jQuery UI Effects Size 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Size Effect
    //>>group: Effects
    //>>description: Resize an element to a specified width and height.
    //>>docs: http://api.jqueryui.com/size-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectSize = $.effects.define("size", function(options, done) {

        // Create element
        var baseline, factor, temp,
            element = $(this),

            // Copy for children
            cProps = ["fontSize"],
            vProps = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"],
            hProps = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"],

            // Set options
            mode = options.mode,
            restore = mode !== "effect",
            scale = options.scale || "both",
            origin = options.origin || ["middle", "center"],
            position = element.css("position"),
            pos = element.position(),
            original = $.effects.scaledDimensions(element),
            from = options.from || original,
            to = options.to || $.effects.scaledDimensions(element, 0);

        $.effects.createPlaceholder(element);

        if (mode === "show") {
            temp = from;
            from = to;
            to = temp;
        }

        // Set scaling factor
        factor = {
            from: {
                y: from.height / original.height,
                x: from.width / original.width
            },
            to: {
                y: to.height / original.height,
                x: to.width / original.width
            }
        };

        // Scale the css box
        if (scale === "box" || scale === "both") {

            // Vertical props scaling
            if (factor.from.y !== factor.to.y) {
                from = $.effects.setTransition(element, vProps, factor.from.y, from);
                to = $.effects.setTransition(element, vProps, factor.to.y, to);
            }

            // Horizontal props scaling
            if (factor.from.x !== factor.to.x) {
                from = $.effects.setTransition(element, hProps, factor.from.x, from);
                to = $.effects.setTransition(element, hProps, factor.to.x, to);
            }
        }

        // Scale the content
        if (scale === "content" || scale === "both") {

            // Vertical props scaling
            if (factor.from.y !== factor.to.y) {
                from = $.effects.setTransition(element, cProps, factor.from.y, from);
                to = $.effects.setTransition(element, cProps, factor.to.y, to);
            }
        }

        // Adjust the position properties based on the provided origin points
        if (origin) {
            baseline = $.effects.getBaseline(origin, original);
            from.top = (original.outerHeight - from.outerHeight) * baseline.y + pos.top;
            from.left = (original.outerWidth - from.outerWidth) * baseline.x + pos.left;
            to.top = (original.outerHeight - to.outerHeight) * baseline.y + pos.top;
            to.left = (original.outerWidth - to.outerWidth) * baseline.x + pos.left;
        }
        element.css(from);

        // Animate the children if desired
        if (scale === "content" || scale === "both") {

            vProps = vProps.concat(["marginTop", "marginBottom"]).concat(cProps);
            hProps = hProps.concat(["marginLeft", "marginRight"]);

            // Only animate children with width attributes specified
            // TODO: is this right? should we include anything with css width specified as well
            element.find("*[width]").each(function() {
                var child = $(this),
                    childOriginal = $.effects.scaledDimensions(child),
                    childFrom = {
                        height: childOriginal.height * factor.from.y,
                        width: childOriginal.width * factor.from.x,
                        outerHeight: childOriginal.outerHeight * factor.from.y,
                        outerWidth: childOriginal.outerWidth * factor.from.x
                    },
                    childTo = {
                        height: childOriginal.height * factor.to.y,
                        width: childOriginal.width * factor.to.x,
                        outerHeight: childOriginal.height * factor.to.y,
                        outerWidth: childOriginal.width * factor.to.x
                    };

                // Vertical props scaling
                if (factor.from.y !== factor.to.y) {
                    childFrom = $.effects.setTransition(child, vProps, factor.from.y, childFrom);
                    childTo = $.effects.setTransition(child, vProps, factor.to.y, childTo);
                }

                // Horizontal props scaling
                if (factor.from.x !== factor.to.x) {
                    childFrom = $.effects.setTransition(child, hProps, factor.from.x, childFrom);
                    childTo = $.effects.setTransition(child, hProps, factor.to.x, childTo);
                }

                if (restore) {
                    $.effects.saveStyle(child);
                }

                // Animate children
                child.css(childFrom);
                child.animate(childTo, options.duration, options.easing, function() {

                    // Restore children
                    if (restore) {
                        $.effects.restoreStyle(child);
                    }
                });
            });
        }

        // Animate
        element.animate(to, {
            queue: false,
            duration: options.duration,
            easing: options.easing,
            complete: function() {

                var offset = element.offset();

                if (to.opacity === 0) {
                    element.css("opacity", from.opacity);
                }

                if (!restore) {
                    element
                        .css("position", position === "static" ? "relative" : position)
                        .offset(offset);

                    // Need to save style here so that automatic style restoration
                    // doesn't restore to the original styles from before the animation.
                    $.effects.saveStyle(element);
                }

                done();
            }
        });

    });


    /*!
     * jQuery UI Effects Scale 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Scale Effect
    //>>group: Effects
    //>>description: Grows or shrinks an element and its content.
    //>>docs: http://api.jqueryui.com/scale-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectScale = $.effects.define("scale", function(options, done) {

        // Create element
        var el = $(this),
            mode = options.mode,
            percent = parseInt(options.percent, 10) ||
            (parseInt(options.percent, 10) === 0 ? 0 : (mode !== "effect" ? 0 : 100)),

            newOptions = $.extend(true, {
                from: $.effects.scaledDimensions(el),
                to: $.effects.scaledDimensions(el, percent, options.direction || "both"),
                origin: options.origin || ["middle", "center"]
            }, options);

        // Fade option to support puff
        if (options.fade) {
            newOptions.from.opacity = 1;
            newOptions.to.opacity = 0;
        }

        $.effects.effect.size.call(this, newOptions, done);
    });


    /*!
     * jQuery UI Effects Puff 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Puff Effect
    //>>group: Effects
    //>>description: Creates a puff effect by scaling the element up and hiding it at the same time.
    //>>docs: http://api.jqueryui.com/puff-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectPuff = $.effects.define("puff", "hide", function(options, done) {
        var newOptions = $.extend(true, {}, options, {
            fade: true,
            percent: parseInt(options.percent, 10) || 150
        });

        $.effects.effect.scale.call(this, newOptions, done);
    });


    /*!
     * jQuery UI Effects Pulsate 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Pulsate Effect
    //>>group: Effects
    //>>description: Pulsates an element n times by changing the opacity to zero and back.
    //>>docs: http://api.jqueryui.com/pulsate-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectPulsate = $.effects.define("pulsate", "show", function(options, done) {
        var element = $(this),
            mode = options.mode,
            show = mode === "show",
            hide = mode === "hide",
            showhide = show || hide,

            // Showing or hiding leaves off the "last" animation
            anims = ((options.times || 5) * 2) + (showhide ? 1 : 0),
            duration = options.duration / anims,
            animateTo = 0,
            i = 1,
            queuelen = element.queue().length;

        if (show || !element.is(":visible")) {
            element.css("opacity", 0).show();
            animateTo = 1;
        }

        // Anims - 1 opacity "toggles"
        for (; i < anims; i++) {
            element.animate({ opacity: animateTo }, duration, options.easing);
            animateTo = 1 - animateTo;
        }

        element.animate({ opacity: animateTo }, duration, options.easing);

        element.queue(done);

        $.effects.unshift(element, queuelen, anims + 1);
    });


    /*!
     * jQuery UI Effects Shake 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Shake Effect
    //>>group: Effects
    //>>description: Shakes an element horizontally or vertically n times.
    //>>docs: http://api.jqueryui.com/shake-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectShake = $.effects.define("shake", function(options, done) {

        var i = 1,
            element = $(this),
            direction = options.direction || "left",
            distance = options.distance || 20,
            times = options.times || 3,
            anims = times * 2 + 1,
            speed = Math.round(options.duration / anims),
            ref = (direction === "up" || direction === "down") ? "top" : "left",
            positiveMotion = (direction === "up" || direction === "left"),
            animation = {},
            animation1 = {},
            animation2 = {},

            queuelen = element.queue().length;

        $.effects.createPlaceholder(element);

        // Animation
        animation[ref] = (positiveMotion ? "-=" : "+=") + distance;
        animation1[ref] = (positiveMotion ? "+=" : "-=") + distance * 2;
        animation2[ref] = (positiveMotion ? "-=" : "+=") + distance * 2;

        // Animate
        element.animate(animation, speed, options.easing);

        // Shakes
        for (; i < times; i++) {
            element
                .animate(animation1, speed, options.easing)
                .animate(animation2, speed, options.easing);
        }

        element
            .animate(animation1, speed, options.easing)
            .animate(animation, speed / 2, options.easing)
            .queue(done);

        $.effects.unshift(element, queuelen, anims + 1);
    });


    /*!
     * jQuery UI Effects Slide 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Slide Effect
    //>>group: Effects
    //>>description: Slides an element in and out of the viewport.
    //>>docs: http://api.jqueryui.com/slide-effect/
    //>>demos: http://jqueryui.com/effect/



    var effectsEffectSlide = $.effects.define("slide", "show", function(options, done) {
        var startClip, startRef,
            element = $(this),
            map = {
                up: ["bottom", "top"],
                down: ["top", "bottom"],
                left: ["right", "left"],
                right: ["left", "right"]
            },
            mode = options.mode,
            direction = options.direction || "left",
            ref = (direction === "up" || direction === "down") ? "top" : "left",
            positiveMotion = (direction === "up" || direction === "left"),
            distance = options.distance ||
            element[ref === "top" ? "outerHeight" : "outerWidth"](true),
            animation = {};

        $.effects.createPlaceholder(element);

        startClip = element.cssClip();
        startRef = element.position()[ref];

        // Define hide animation
        animation[ref] = (positiveMotion ? -1 : 1) * distance + startRef;
        animation.clip = element.cssClip();
        animation.clip[map[direction][1]] = animation.clip[map[direction][0]];

        // Reverse the animation if we're showing
        if (mode === "show") {
            element.cssClip(animation.clip);
            element.css(ref, animation[ref]);
            animation.clip = startClip;
            animation[ref] = startRef;
        }

        // Actually animate
        element.animate(animation, {
            queue: false,
            duration: options.duration,
            easing: options.easing,
            complete: done
        });
    });


    /*!
     * jQuery UI Effects Transfer 1.12.1
     * http://jqueryui.com
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license.
     * http://jquery.org/license
     */

    //>>label: Transfer Effect
    //>>group: Effects
    //>>description: Displays a transfer effect from one element to another.
    //>>docs: http://api.jqueryui.com/transfer-effect/
    //>>demos: http://jqueryui.com/effect/



    var effect;
    if ($.uiBackCompat !== false) {
        effect = $.effects.define("transfer", function(options, done) {
            $(this).transfer(options, done);
        });
    }
    var effectsEffectTransfer = effect;




}));
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/drop-pin.js?ver=4fca74de5e3fa981b9659807f09e9e55 
    var map;
    function lp_initialize_map() {
		if(jQuery('#lp-custom-latlong').length !=0 ){
			var clat;
			var clong;
			var myLatlng;
			
			clat = jQuery('body').data('defaultmaplat');
			clong = jQuery('body').data('defaultmaplot');
			if (jQuery("#latitude").length){
				if(document.getElementById("latitude").value!=''){
					clat = document.getElementById("latitude").value;
				}
			}
			if (jQuery("#longitude").length){
				if(document.getElementById("longitude").value!=''){
					clong = document.getElementById("longitude").value;
				}
			}

			if(clat && clong){
				myLatlng = new google.maps.LatLng(clat, clong);
			}
			else{
				myLatlng = new google.maps.LatLng(40.713956, -74.006653);
			}
			
			var myOptions = {
				zoom: 8,
				center: myLatlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			map = new google.maps.Map(document.getElementById("lp-custom-latlong"), myOptions);
			var marker = new google.maps.Marker({
				draggable: true,
				position: myLatlng,
				map: map,
				title: ""
			});
			google.maps.event.addListener(marker, 'dragend', function (event) {
				document.getElementById("latitude").value = event.latLng.lat();
				document.getElementById("longitude").value = event.latLng.lng();
			});
			
			// Create the DIV to hold the control and call the CenterControl()
			// constructor passing in this DIV.
			var centerControlDiv = document.createElement('div');
			var centerControl = new CenterControl(centerControlDiv, map, marker);

			centerControlDiv.index = 1;
			map.controls[google.maps.ControlPosition.TOP_RIGHT].push(centerControlDiv);
		}
    }
	google.maps.event.addDomListener(window, "load", lp_initialize_map());
	
	jQuery('#modal-doppin').on('shown.bs.modal', function () 
	{
		//google.maps.event.trigger(map, "resize");
		google.maps.event.addDomListener(window, "load", lp_initialize_map());
	});
	
	/* trigger click for custom lat and long toggle on submit page */
	jQuery(document).ready(function($){
		jQuery(".lp-coordinates a.googledroppin").on('click', function(){
			jQuery(".lp-coordinates a.googleAddressbtn").trigger('click');
		});
	})
	
	function CenterControl(controlDiv, map, marker) {
		
		var btitle = jQuery('#modal-doppin').data('lploctitlemap');

		// Set CSS for the control border.
		var controlUI = document.createElement('div');
		controlUI.style.backgroundColor = '#fff';
		controlUI.style.border = '2px solid #fff';
		controlUI.style.borderRadius = '3px';
		controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
		controlUI.style.cursor = 'pointer';
		controlUI.style.marginBottom = '22px';
		controlUI.style.textAlign = 'center';
		controlUI.title = btitle;
		controlDiv.appendChild(controlUI);

		// Set CSS for the control interior.
		var controlText = document.createElement('div');
		controlText.style.color = 'rgb(25,25,25)';
		controlText.style.fontSize = '13px';
		controlText.style.lineHeight = '20px';
		controlText.style.paddingLeft = '5px';
		controlText.style.paddingRight = '5px';
		controlText.innerHTML = btitle;
		controlUI.appendChild(controlText);

		// Setup the click event listeners: simply set the map to Chicago.
		controlUI.addEventListener('click', function() {
			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(function (position) {
					var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
					
					map.setCenter(pos);
					marker.setPosition(pos);
					document.getElementById("latitude").value = position.coords.latitude;
					document.getElementById("longitude").value = position.coords.longitude;
				})
			}
			
		});

	};
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/jquery.city-autocomplete.js?ver=4fca74de5e3fa981b9659807f09e9e55 
(function ($) {

    var lpregions = false;
    var lpattern = jQuery('#page').data('lpattern');
    if (lpattern === "with_region") {
        lpregions = true;
    }


    $.fn.cityAutocomplete = function (options) {
        var autocompleteService = new google.maps.places.AutocompleteService();
        var predictionsDropDown = $('<div class="city-autocomplete"></div>').appendTo('body');
        var input = this;

        input.keyup(function () {
            var searchStr = $(this).val();

            if (searchStr.length > 0) {

                if (!lpregions) {
                    var params = {
                        input: searchStr,
                        types: ['(cities)']
                    };
                } else {
                    var params = {
                        input: searchStr,
                        types: ['(regions)']
                    };
                }


                if (input.data('country').length > 0) {
                    params.componentRestrictions = { country: input.data('country') }
                }

                autocompleteService.getPlacePredictions(params, updatePredictions);
            } else {
                predictionsDropDown.hide();
            }
        });

        predictionsDropDown.delegate('div', 'click', function () {
            //New update 2.7.0
            substrr = $(this).text();
            substrr = substrr.split(",");
            if (substrr[1] == 'undefined' || substrr[1] == '' || substrr[1] == null) {
                substrr = substrr[0];
            } else {
                substrr = substrr[0] + ',' + substrr[1];
            }
            //End New update 2.7.0
            jQuery('input[name=lp_s_loc]').val(substrr);
            jQuery('input[name=location]').val(substrr);
            input.val($(this).text());
            input.data('isseleted', 'true');
            predictionsDropDown.hide();
        });

        $(document).mouseup(function (e) {
            if (!predictionsDropDown.is(e.target) && predictionsDropDown.has(e.target).length === 0) {
                predictionsDropDown.hide();
            }
        });

        $(window).resize(function () {
            updatePredictionsDropDownDisplay(predictionsDropDown, input);
        });

        updatePredictionsDropDownDisplay(predictionsDropDown, input);

        function updatePredictions(predictions, status) {
            if (google.maps.places.PlacesServiceStatus.OK != status) {
                predictionsDropDown.hide();
                return;
            }

            predictionsDropDown.empty();
            var predcities = [];
            $.each(predictions, function (i, prediction) {
                if (!lpregions) {
                    predcities.push($.fn.cityAutocomplete.transliterate(prediction.terms[0].value));
                } else {
                    predcities.push(prediction.description);
                }
            });
            if (!lpregions) {
                predcities = predcities.filter((v, i, a) => a.indexOf(v) === i);
            }
            $.each(predcities, function (i, cities) {
                predictionsDropDown.append('<div class="help">' + cities + '</div');
            });
            predictionsDropDown.show();
        }

        return input;
    };

    $.fn.cityAutocomplete.transliterate = function (s) {
        s = String(s);

        var char_map = {
            // Latin
            'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', 'Ç': 'C',
            'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', 'Î': 'I', 'Ï': 'I',
            'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 'O', 'Ő': 'O',
            'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U', 'Ű': 'U', 'Ý': 'Y', 'Þ': 'TH',
            'ß': 'ss',
            'à': 'a', 'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', 'æ': 'ae', 'ç': 'c',
            'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i',
            'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ő': 'o',
            'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u', 'ű': 'u', 'ý': 'y', 'þ': 'th',
            'ÿ': 'y',

            // Latin symbols
            '©': '(c)',

            // Greek
            'Α': 'A', 'Β': 'B', 'Γ': 'G', 'Δ': 'D', 'Ε': 'E', 'Ζ': 'Z', 'Η': 'H', 'Θ': '8',
            'Ι': 'I', 'Κ': 'K', 'Λ': 'L', 'Μ': 'M', 'Ν': 'N', 'Ξ': '3', 'Ο': 'O', 'Π': 'P',
            'Ρ': 'R', 'Σ': 'S', 'Τ': 'T', 'Υ': 'Y', 'Φ': 'F', 'Χ': 'X', 'Ψ': 'PS', 'Ω': 'W',
            'Ά': 'A', 'Έ': 'E', 'Ί': 'I', 'Ό': 'O', 'Ύ': 'Y', 'Ή': 'H', 'Ώ': 'W', 'Ϊ': 'I',
            'Ϋ': 'Y',
            'α': 'a', 'β': 'b', 'γ': 'g', 'δ': 'd', 'ε': 'e', 'ζ': 'z', 'η': 'h', 'θ': '8',
            'ι': 'i', 'κ': 'k', 'λ': 'l', 'μ': 'm', 'ν': 'n', 'ξ': '3', 'ο': 'o', 'π': 'p',
            'ρ': 'r', 'σ': 's', 'τ': 't', 'υ': 'y', 'φ': 'f', 'χ': 'x', 'ψ': 'ps', 'ω': 'w',
            'ά': 'a', 'έ': 'e', 'ί': 'i', 'ό': 'o', 'ύ': 'y', 'ή': 'h', 'ώ': 'w', 'ς': 's',
            'ϊ': 'i', 'ΰ': 'y', 'ϋ': 'y', 'ΐ': 'i',

            // Turkish
            'Ş': 'S', 'İ': 'I', 'Ç': 'C', 'Ü': 'U', 'Ö': 'O', 'Ğ': 'G',
            'ş': 's', 'ı': 'i', 'ç': 'c', 'ü': 'u', 'ö': 'o', 'ğ': 'g',

            // Russian
            'А': 'A', 'Б': 'B', 'В': 'V', 'Г': 'G', 'Д': 'D', 'Е': 'E', 'Ё': 'Yo', 'Ж': 'Zh',
            'З': 'Z', 'И': 'I', 'Й': 'J', 'К': 'K', 'Л': 'L', 'М': 'M', 'Н': 'N', 'О': 'O',
            'П': 'P', 'Р': 'R', 'С': 'S', 'Т': 'T', 'У': 'U', 'Ф': 'F', 'Х': 'H', 'Ц': 'C',
            'Ч': 'Ch', 'Ш': 'Sh', 'Щ': 'Sh', 'Ъ': '', 'Ы': 'Y', 'Ь': '', 'Э': 'E', 'Ю': 'Yu',
            'Я': 'Ya',
            'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo', 'ж': 'zh',
            'з': 'z', 'и': 'i', 'й': 'j', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'о': 'o',
            'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u', 'ф': 'f', 'х': 'h', 'ц': 'c',
            'ч': 'ch', 'ш': 'sh', 'щ': 'sh', 'ъ': '', 'ы': 'y', 'ь': '', 'э': 'e', 'ю': 'yu',
            'я': 'ya',

            // Ukrainian
            'Є': 'Ye', 'І': 'I', 'Ї': 'Yi', 'Ґ': 'G',
            'є': 'ye', 'і': 'i', 'ї': 'yi', 'ґ': 'g',

            // Czech
            'Č': 'C', 'Ď': 'D', 'Ě': 'E', 'Ň': 'N', 'Ř': 'R', 'Š': 'S', 'Ť': 'T', 'Ů': 'U',
            'Ž': 'Z',
            'č': 'c', 'ď': 'd', 'ě': 'e', 'ň': 'n', 'ř': 'r', 'š': 's', 'ť': 't', 'ů': 'u',
            'ž': 'z',

            // Polish
            'Ą': 'A', 'Ć': 'C', 'Ę': 'e', 'Ł': 'L', 'Ń': 'N', 'Ó': 'o', 'Ś': 'S', 'Ź': 'Z',
            'Ż': 'Z',
            'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z',
            'ż': 'z',

            // Latvian
            'Ā': 'A', 'Č': 'C', 'Ē': 'E', 'Ģ': 'G', 'Ī': 'i', 'Ķ': 'k', 'Ļ': 'L', 'Ņ': 'N',
            'Š': 'S', 'Ū': 'u', 'Ž': 'Z',
            'ā': 'a', 'č': 'c', 'ē': 'e', 'ģ': 'g', 'ī': 'i', 'ķ': 'k', 'ļ': 'l', 'ņ': 'n',
            'š': 's', 'ū': 'u', 'ž': 'z'
        };

        for (var k in char_map) {
            s = s.replace(new RegExp(k, 'g'), char_map[k]);
        }

        return s;
    };

    function updatePredictionsDropDownDisplay(dropDown, input) {
        dropDown.css({
            'width': input.outerWidth(),
            'left': input.offset().left,
            'top': input.offset().top + input.outerHeight()
        });
    }

}(jQuery));
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/lib/bootstrap/js/bootstrap-slider.js?ver=4fca74de5e3fa981b9659807f09e9e55 
"use strict";

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/*! =========================================================
 * bootstrap-slider.js
 *
 * Maintainers:
 *		Kyle Kemp
 *			- Twitter: @seiyria
 *			- Github:  seiyria
 *		Rohit Kalkur
 *			- Twitter: @Rovolutionary
 *			- Github:  rovolution
 *
 * =========================================================
 *
 * bootstrap-slider is released under the MIT License
 * Copyright (c) 2017 Kyle Kemp, Rohit Kalkur, and contributors
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * ========================================================= */

/**
 * Bridget makes jQuery widgets
 * v1.0.1
 * MIT license
 */
var windowIsDefined = (typeof window === "undefined" ? "undefined" : _typeof(window)) === "object";

(function (factory) {
	if (typeof define === "function" && define.amd) {
		define(["jquery"], factory);
	} else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) {
		var jQuery;
		try {
			jQuery = require("jquery");
		} catch (err) {
			jQuery = null;
		}
		module.exports = factory(jQuery);
	} else if (window) {
		window.Slider = factory(window.jQuery);
	}
})(function ($) {
	// Constants
	var NAMESPACE_MAIN = 'slider';
	var NAMESPACE_ALTERNATE = 'bootstrapSlider';

	// Polyfill console methods
	if (windowIsDefined && !window.console) {
		window.console = {};
	}
	if (windowIsDefined && !window.console.log) {
		window.console.log = function () {};
	}
	if (windowIsDefined && !window.console.warn) {
		window.console.warn = function () {};
	}

	// Reference to Slider constructor
	var Slider;

	(function ($) {

		'use strict';

		// -------------------------- utils -------------------------- //

		var slice = Array.prototype.slice;

		function noop() {}

		// -------------------------- definition -------------------------- //

		function defineBridget($) {

			// bail if no jQuery
			if (!$) {
				return;
			}

			// -------------------------- addOptionMethod -------------------------- //

			/**
    * adds option method -> $().plugin('option', {...})
    * @param {Function} PluginClass - constructor class
    */
			function addOptionMethod(PluginClass) {
				// don't overwrite original option method
				if (PluginClass.prototype.option) {
					return;
				}

				// option setter
				PluginClass.prototype.option = function (opts) {
					// bail out if not an object
					if (!$.isPlainObject(opts)) {
						return;
					}
					this.options = $.extend(true, this.options, opts);
				};
			}

			// -------------------------- plugin bridge -------------------------- //

			// helper function for logging errors
			// $.error breaks jQuery chaining
			var logError = typeof console === 'undefined' ? noop : function (message) {
				console.error(message);
			};

			/**
    * jQuery plugin bridge, access methods like $elem.plugin('method')
    * @param {String} namespace - plugin name
    * @param {Function} PluginClass - constructor class
    */
			function bridge(namespace, PluginClass) {
				// add to jQuery fn namespace
				$.fn[namespace] = function (options) {
					if (typeof options === 'string') {
						// call plugin method when first argument is a string
						// get arguments for method
						var args = slice.call(arguments, 1);

						for (var i = 0, len = this.length; i < len; i++) {
							var elem = this[i];
							var instance = $.data(elem, namespace);
							if (!instance) {
								logError("cannot call methods on " + namespace + " prior to initialization; " + "attempted to call '" + options + "'");
								continue;
							}
							if (!$.isFunction(instance[options]) || options.charAt(0) === '_') {
								logError("no such method '" + options + "' for " + namespace + " instance");
								continue;
							}

							// trigger method with arguments
							var returnValue = instance[options].apply(instance, args);

							// break look and return first value if provided
							if (returnValue !== undefined && returnValue !== instance) {
								return returnValue;
							}
						}
						// return this if no return value
						return this;
					} else {
						var objects = this.map(function () {
							var instance = $.data(this, namespace);
							if (instance) {
								// apply options & init
								instance.option(options);
								instance._init();
							} else {
								// initialize new instance
								instance = new PluginClass(this, options);
								$.data(this, namespace, instance);
							}
							return $(this);
						});

						if (!objects || objects.length > 1) {
							return objects;
						} else {
							return objects[0];
						}
					}
				};
			}

			// -------------------------- bridget -------------------------- //

			/**
    * converts a Prototypical class into a proper jQuery plugin
    *   the class must have a ._init method
    * @param {String} namespace - plugin name, used in $().pluginName
    * @param {Function} PluginClass - constructor class
    */
			$.bridget = function (namespace, PluginClass) {
				addOptionMethod(PluginClass);
				bridge(namespace, PluginClass);
			};

			return $.bridget;
		}

		// get jquery from browser global
		defineBridget($);
	})($);

	/*************************************************
 			BOOTSTRAP-SLIDER SOURCE CODE
 	**************************************************/

	(function ($) {

		var ErrorMsgs = {
			formatInvalidInputErrorMsg: function formatInvalidInputErrorMsg(input) {
				return "Invalid input value '" + input + "' passed in";
			},
			callingContextNotSliderInstance: "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"
		};

		var SliderScale = {
			linear: {
				toValue: function toValue(percentage) {
					var rawValue = percentage / 100 * (this.options.max - this.options.min);
					var shouldAdjustWithBase = true;
					if (this.options.ticks_positions.length > 0) {
						var minv,
						    maxv,
						    minp,
						    maxp = 0;
						for (var i = 1; i < this.options.ticks_positions.length; i++) {
							if (percentage <= this.options.ticks_positions[i]) {
								minv = this.options.ticks[i - 1];
								minp = this.options.ticks_positions[i - 1];
								maxv = this.options.ticks[i];
								maxp = this.options.ticks_positions[i];

								break;
							}
						}
						var partialPercentage = (percentage - minp) / (maxp - minp);
						rawValue = minv + partialPercentage * (maxv - minv);
						shouldAdjustWithBase = false;
					}

					var adjustment = shouldAdjustWithBase ? this.options.min : 0;
					var value = adjustment + Math.round(rawValue / this.options.step) * this.options.step;
					if (value < this.options.min) {
						return this.options.min;
					} else if (value > this.options.max) {
						return this.options.max;
					} else {
						return value;
					}
				},
				toPercentage: function toPercentage(value) {
					if (this.options.max === this.options.min) {
						return 0;
					}

					if (this.options.ticks_positions.length > 0) {
						var minv,
						    maxv,
						    minp,
						    maxp = 0;
						for (var i = 0; i < this.options.ticks.length; i++) {
							if (value <= this.options.ticks[i]) {
								minv = i > 0 ? this.options.ticks[i - 1] : 0;
								minp = i > 0 ? this.options.ticks_positions[i - 1] : 0;
								maxv = this.options.ticks[i];
								maxp = this.options.ticks_positions[i];

								break;
							}
						}
						if (i > 0) {
							var partialPercentage = (value - minv) / (maxv - minv);
							return minp + partialPercentage * (maxp - minp);
						}
					}

					return 100 * (value - this.options.min) / (this.options.max - this.options.min);
				}
			},

			logarithmic: {
				/* Based on http://stackoverflow.com/questions/846221/logarithmic-slider */
				toValue: function toValue(percentage) {
					var min = this.options.min === 0 ? 0 : Math.log(this.options.min);
					var max = Math.log(this.options.max);
					var value = Math.exp(min + (max - min) * percentage / 100);
					if (Math.round(value) === this.options.max) {
						return this.options.max;
					}
					value = this.options.min + Math.round((value - this.options.min) / this.options.step) * this.options.step;
					/* Rounding to the nearest step could exceed the min or
      * max, so clip to those values. */
					if (value < this.options.min) {
						return this.options.min;
					} else if (value > this.options.max) {
						return this.options.max;
					} else {
						return value;
					}
				},
				toPercentage: function toPercentage(value) {
					if (this.options.max === this.options.min) {
						return 0;
					} else {
						var max = Math.log(this.options.max);
						var min = this.options.min === 0 ? 0 : Math.log(this.options.min);
						var v = value === 0 ? 0 : Math.log(value);
						return 100 * (v - min) / (max - min);
					}
				}
			}
		};

		/*************************************************
  						CONSTRUCTOR
  	**************************************************/
		Slider = function Slider(element, options) {
			createNewSlider.call(this, element, options);
			return this;
		};

		function createNewSlider(element, options) {

			/*
   	The internal state object is used to store data about the current 'state' of slider.
   	This includes values such as the `value`, `enabled`, etc...
   */
			this._state = {
				value: null,
				enabled: null,
				offset: null,
				size: null,
				percentage: null,
				inDrag: false,
				over: false
			};

			// The objects used to store the reference to the tick methods if ticks_tooltip is on
			this.ticksCallbackMap = {};
			this.handleCallbackMap = {};

			if (typeof element === "string") {
				this.element = document.querySelector(element);
			} else if (element instanceof HTMLElement) {
				this.element = element;
			}

			/*************************************************
   					Process Options
   	**************************************************/
			options = options ? options : {};
			var optionTypes = Object.keys(this.defaultOptions);

			for (var i = 0; i < optionTypes.length; i++) {
				var optName = optionTypes[i];

				// First check if an option was passed in via the constructor
				var val = options[optName];
				// If no data attrib, then check data atrributes
				val = typeof val !== 'undefined' ? val : getDataAttrib(this.element, optName);
				// Finally, if nothing was specified, use the defaults
				val = val !== null ? val : this.defaultOptions[optName];

				// Set all options on the instance of the Slider
				if (!this.options) {
					this.options = {};
				}
				this.options[optName] = val;
			}

			// Check options.rtl
			if (this.options.rtl === 'auto') {
				this.options.rtl = window.getComputedStyle(this.element).direction === 'rtl';
			}

			/*
   	Validate `tooltip_position` against 'orientation`
   	- if `tooltip_position` is incompatible with orientation, swith it to a default compatible with specified `orientation`
   		-- default for "vertical" -> "right", "left" if rtl
   		-- default for "horizontal" -> "top"
   */
			if (this.options.orientation === "vertical" && (this.options.tooltip_position === "top" || this.options.tooltip_position === "bottom")) {
				if (this.options.rtl) {
					this.options.tooltip_position = "left";
				} else {
					this.options.tooltip_position = "right";
				}
			} else if (this.options.orientation === "horizontal" && (this.options.tooltip_position === "left" || this.options.tooltip_position === "right")) {

				this.options.tooltip_position = "top";
			}

			function getDataAttrib(element, optName) {
				var dataName = "data-slider-" + optName.replace(/_/g, '-');
				var dataValString = element.getAttribute(dataName);

				try {
					return JSON.parse(dataValString);
				} catch (err) {
					return dataValString;
				}
			}

			/*************************************************
   					Create Markup
   	**************************************************/

			var origWidth = this.element.style.width;
			var updateSlider = false;
			var parent = this.element.parentNode;
			var sliderTrackSelection;
			var sliderTrackLow, sliderTrackHigh;
			var sliderMinHandle;
			var sliderMaxHandle;

			if (this.sliderElem) {
				updateSlider = true;
			} else {
				/* Create elements needed for slider */
				this.sliderElem = document.createElement("div");
				this.sliderElem.className = "slider";

				/* Create slider track elements */
				var sliderTrack = document.createElement("div");
				sliderTrack.className = "slider-track";

				sliderTrackLow = document.createElement("div");
				sliderTrackLow.className = "slider-track-low";

				sliderTrackSelection = document.createElement("div");
				sliderTrackSelection.className = "slider-selection";

				sliderTrackHigh = document.createElement("div");
				sliderTrackHigh.className = "slider-track-high";

				sliderMinHandle = document.createElement("div");
				sliderMinHandle.className = "slider-handle min-slider-handle";
				sliderMinHandle.setAttribute('role', 'slider');
				sliderMinHandle.setAttribute('aria-valuemin', this.options.min);
				sliderMinHandle.setAttribute('aria-valuemax', this.options.max);

				sliderMaxHandle = document.createElement("div");
				sliderMaxHandle.className = "slider-handle max-slider-handle";
				sliderMaxHandle.setAttribute('role', 'slider');
				sliderMaxHandle.setAttribute('aria-valuemin', this.options.min);
				sliderMaxHandle.setAttribute('aria-valuemax', this.options.max);

				sliderTrack.appendChild(sliderTrackLow);
				sliderTrack.appendChild(sliderTrackSelection);
				sliderTrack.appendChild(sliderTrackHigh);

				/* Create highlight range elements */
				this.rangeHighlightElements = [];
				var rangeHighlightsOpts = this.options.rangeHighlights;
				if (Array.isArray(rangeHighlightsOpts) && rangeHighlightsOpts.length > 0) {
					for (var j = 0; j < rangeHighlightsOpts.length; j++) {
						var rangeHighlightElement = document.createElement("div");
						var customClassString = rangeHighlightsOpts[j].class || "";
						rangeHighlightElement.className = "slider-rangeHighlight slider-selection " + customClassString;
						this.rangeHighlightElements.push(rangeHighlightElement);
						sliderTrack.appendChild(rangeHighlightElement);
					}
				}

				/* Add aria-labelledby to handle's */
				var isLabelledbyArray = Array.isArray(this.options.labelledby);
				if (isLabelledbyArray && this.options.labelledby[0]) {
					sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby[0]);
				}
				if (isLabelledbyArray && this.options.labelledby[1]) {
					sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby[1]);
				}
				if (!isLabelledbyArray && this.options.labelledby) {
					sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby);
					sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby);
				}

				/* Create ticks */
				this.ticks = [];
				if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
					this.ticksContainer = document.createElement('div');
					this.ticksContainer.className = 'slider-tick-container';

					for (i = 0; i < this.options.ticks.length; i++) {
						var tick = document.createElement('div');
						tick.className = 'slider-tick';
						if (this.options.ticks_tooltip) {
							var tickListenerReference = this._addTickListener();
							var enterCallback = tickListenerReference.addMouseEnter(this, tick, i);
							var leaveCallback = tickListenerReference.addMouseLeave(this, tick);

							this.ticksCallbackMap[i] = {
								mouseEnter: enterCallback,
								mouseLeave: leaveCallback
							};
						}
						this.ticks.push(tick);
						this.ticksContainer.appendChild(tick);
					}

					sliderTrackSelection.className += " tick-slider-selection";
				}

				this.tickLabels = [];
				if (Array.isArray(this.options.ticks_labels) && this.options.ticks_labels.length > 0) {
					this.tickLabelContainer = document.createElement('div');
					this.tickLabelContainer.className = 'slider-tick-label-container';

					for (i = 0; i < this.options.ticks_labels.length; i++) {
						var label = document.createElement('div');
						var noTickPositionsSpecified = this.options.ticks_positions.length === 0;
						var tickLabelsIndex = this.options.reversed && noTickPositionsSpecified ? this.options.ticks_labels.length - (i + 1) : i;
						label.className = 'slider-tick-label';
						label.innerHTML = this.options.ticks_labels[tickLabelsIndex];

						this.tickLabels.push(label);
						this.tickLabelContainer.appendChild(label);
					}
				}

				var createAndAppendTooltipSubElements = function createAndAppendTooltipSubElements(tooltipElem) {
					var arrow = document.createElement("div");
					arrow.className = "tooltip-arrow";

					var inner = document.createElement("div");
					inner.className = "tooltip-inner";

					tooltipElem.appendChild(arrow);
					tooltipElem.appendChild(inner);
				};

				/* Create tooltip elements */
				var sliderTooltip = document.createElement("div");
				sliderTooltip.className = "tooltip tooltip-main";
				sliderTooltip.setAttribute('role', 'presentation');
				createAndAppendTooltipSubElements(sliderTooltip);

				var sliderTooltipMin = document.createElement("div");
				sliderTooltipMin.className = "tooltip tooltip-min";
				sliderTooltipMin.setAttribute('role', 'presentation');
				createAndAppendTooltipSubElements(sliderTooltipMin);

				var sliderTooltipMax = document.createElement("div");
				sliderTooltipMax.className = "tooltip tooltip-max";
				sliderTooltipMax.setAttribute('role', 'presentation');
				createAndAppendTooltipSubElements(sliderTooltipMax);

				/* Append components to sliderElem */
				this.sliderElem.appendChild(sliderTrack);
				this.sliderElem.appendChild(sliderTooltip);
				this.sliderElem.appendChild(sliderTooltipMin);
				this.sliderElem.appendChild(sliderTooltipMax);

				if (this.tickLabelContainer) {
					this.sliderElem.appendChild(this.tickLabelContainer);
				}
				if (this.ticksContainer) {
					this.sliderElem.appendChild(this.ticksContainer);
				}

				this.sliderElem.appendChild(sliderMinHandle);
				this.sliderElem.appendChild(sliderMaxHandle);

				/* Append slider element to parent container, right before the original <input> element */
				parent.insertBefore(this.sliderElem, this.element);

				/* Hide original <input> element */
				this.element.style.display = "none";
			}
			/* If JQuery exists, cache JQ references */
			if ($) {
				this.$element = $(this.element);
				this.$sliderElem = $(this.sliderElem);
			}

			/*************************************************
   						Setup
   	**************************************************/
			this.eventToCallbackMap = {};
			this.sliderElem.id = this.options.id;

			this.touchCapable = 'ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch;

			this.touchX = 0;
			this.touchY = 0;

			this.tooltip = this.sliderElem.querySelector('.tooltip-main');
			this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');

			this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
			this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');

			this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
			this.tooltipInner_max = this.tooltip_max.querySelector('.tooltip-inner');

			if (SliderScale[this.options.scale]) {
				this.options.scale = SliderScale[this.options.scale];
			}

			if (updateSlider === true) {
				// Reset classes
				this._removeClass(this.sliderElem, 'slider-horizontal');
				this._removeClass(this.sliderElem, 'slider-vertical');
				this._removeClass(this.sliderElem, 'slider-rtl');
				this._removeClass(this.tooltip, 'hide');
				this._removeClass(this.tooltip_min, 'hide');
				this._removeClass(this.tooltip_max, 'hide');

				// Undo existing inline styles for track
				["left", "right", "top", "width", "height"].forEach(function (prop) {
					this._removeProperty(this.trackLow, prop);
					this._removeProperty(this.trackSelection, prop);
					this._removeProperty(this.trackHigh, prop);
				}, this);

				// Undo inline styles on handles
				[this.handle1, this.handle2].forEach(function (handle) {
					this._removeProperty(handle, 'left');
					this._removeProperty(handle, 'right');
					this._removeProperty(handle, 'top');
				}, this);

				// Undo inline styles and classes on tooltips
				[this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function (tooltip) {
					this._removeProperty(tooltip, 'left');
					this._removeProperty(tooltip, 'right');
					this._removeProperty(tooltip, 'top');
					this._removeProperty(tooltip, 'margin-left');
					this._removeProperty(tooltip, 'margin-right');
					this._removeProperty(tooltip, 'margin-top');

					this._removeClass(tooltip, 'right');
					this._removeClass(tooltip, 'left');
					this._removeClass(tooltip, 'top');
				}, this);
			}

			if (this.options.orientation === 'vertical') {
				this._addClass(this.sliderElem, 'slider-vertical');
				this.stylePos = 'top';
				this.mousePos = 'pageY';
				this.sizePos = 'offsetHeight';
			} else {
				this._addClass(this.sliderElem, 'slider-horizontal');
				this.sliderElem.style.width = origWidth;
				this.options.orientation = 'horizontal';
				if (this.options.rtl) {
					this.stylePos = 'right';
				} else {
					this.stylePos = 'left';
				}
				this.mousePos = 'pageX';
				this.sizePos = 'offsetWidth';
			}
			// specific rtl class
			if (this.options.rtl) {
				this._addClass(this.sliderElem, 'slider-rtl');
			}
			this._setTooltipPosition();
			/* In case ticks are specified, overwrite the min and max bounds */
			if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
				this.options.max = Math.max.apply(Math, this.options.ticks);
				this.options.min = Math.min.apply(Math, this.options.ticks);
			}

			if (Array.isArray(this.options.value)) {
				this.options.range = true;
				this._state.value = this.options.value;
			} else if (this.options.range) {
				// User wants a range, but value is not an array
				this._state.value = [this.options.value, this.options.max];
			} else {
				this._state.value = this.options.value;
			}

			this.trackLow = sliderTrackLow || this.trackLow;
			this.trackSelection = sliderTrackSelection || this.trackSelection;
			this.trackHigh = sliderTrackHigh || this.trackHigh;

			if (this.options.selection === 'none') {
				this._addClass(this.trackLow, 'hide');
				this._addClass(this.trackSelection, 'hide');
				this._addClass(this.trackHigh, 'hide');
			} else if (this.options.selection === 'after' || this.options.selection === 'before') {
				this._removeClass(this.trackLow, 'hide');
				this._removeClass(this.trackSelection, 'hide');
				this._removeClass(this.trackHigh, 'hide');
			}

			this.handle1 = sliderMinHandle || this.handle1;
			this.handle2 = sliderMaxHandle || this.handle2;

			if (updateSlider === true) {
				// Reset classes
				this._removeClass(this.handle1, 'round triangle');
				this._removeClass(this.handle2, 'round triangle hide');

				for (i = 0; i < this.ticks.length; i++) {
					this._removeClass(this.ticks[i], 'round triangle hide');
				}
			}

			var availableHandleModifiers = ['round', 'triangle', 'custom'];
			var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
			if (isValidHandleType) {
				this._addClass(this.handle1, this.options.handle);
				this._addClass(this.handle2, this.options.handle);

				for (i = 0; i < this.ticks.length; i++) {
					this._addClass(this.ticks[i], this.options.handle);
				}
			}

			this._state.offset = this._offset(this.sliderElem);
			this._state.size = this.sliderElem[this.sizePos];
			this.setValue(this._state.value);

			/******************************************
   				Bind Event Listeners
   	******************************************/

			// Bind keyboard handlers
			this.handle1Keydown = this._keydown.bind(this, 0);
			this.handle1.addEventListener("keydown", this.handle1Keydown, false);

			this.handle2Keydown = this._keydown.bind(this, 1);
			this.handle2.addEventListener("keydown", this.handle2Keydown, false);

			this.mousedown = this._mousedown.bind(this);
			this.touchstart = this._touchstart.bind(this);
			this.touchmove = this._touchmove.bind(this);

			if (this.touchCapable) {
				// Test for passive event support
				var supportsPassive = false;
				try {
					var opts = Object.defineProperty({}, 'passive', {
						get: function get() {
							supportsPassive = true;
						}
					});
					window.addEventListener("test", null, opts);
				} catch (e) {}
				// Use our detect's results. passive applied if supported, capture will be false either way.
				var eventOptions = supportsPassive ? { passive: true } : false;
				// Bind touch handlers
				this.sliderElem.addEventListener("touchstart", this.touchstart, eventOptions);
				this.sliderElem.addEventListener("touchmove", this.touchmove, eventOptions);
			}
			this.sliderElem.addEventListener("mousedown", this.mousedown, false);

			// Bind window handlers
			this.resize = this._resize.bind(this);
			window.addEventListener("resize", this.resize, false);

			// Bind tooltip-related handlers
			if (this.options.tooltip === 'hide') {
				this._addClass(this.tooltip, 'hide');
				this._addClass(this.tooltip_min, 'hide');
				this._addClass(this.tooltip_max, 'hide');
			} else if (this.options.tooltip === 'always') {
				this._showTooltip();
				this._alwaysShowTooltip = true;
			} else {
				this.showTooltip = this._showTooltip.bind(this);
				this.hideTooltip = this._hideTooltip.bind(this);

				if (this.options.ticks_tooltip) {
					var callbackHandle = this._addTickListener();
					//create handle1 listeners and store references in map
					var mouseEnter = callbackHandle.addMouseEnter(this, this.handle1);
					var mouseLeave = callbackHandle.addMouseLeave(this, this.handle1);
					this.handleCallbackMap.handle1 = {
						mouseEnter: mouseEnter,
						mouseLeave: mouseLeave
					};
					//create handle2 listeners and store references in map
					mouseEnter = callbackHandle.addMouseEnter(this, this.handle2);
					mouseLeave = callbackHandle.addMouseLeave(this, this.handle2);
					this.handleCallbackMap.handle2 = {
						mouseEnter: mouseEnter,
						mouseLeave: mouseLeave
					};
				} else {
					this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);
					this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
				}

				this.handle1.addEventListener("focus", this.showTooltip, false);
				this.handle1.addEventListener("blur", this.hideTooltip, false);

				this.handle2.addEventListener("focus", this.showTooltip, false);
				this.handle2.addEventListener("blur", this.hideTooltip, false);
			}

			if (this.options.enabled) {
				this.enable();
			} else {
				this.disable();
			}
		}

		/*************************************************
  				INSTANCE PROPERTIES/METHODS
  	- Any methods bound to the prototype are considered
  part of the plugin's `public` interface
  	**************************************************/
		Slider.prototype = {
			_init: function _init() {}, // NOTE: Must exist to support bridget

			constructor: Slider,

			defaultOptions: {
				id: "",
				min: 0,
				max: 10,
				step: 1,
				precision: 0,
				orientation: 'horizontal',
				value: 5,
				range: false,
				selection: 'before',
				tooltip: 'show',
				tooltip_split: false,
				handle: 'round',
				reversed: false,
				rtl: 'auto',
				enabled: true,
				formatter: function formatter(val) {
					if (Array.isArray(val)) {
						return val[0] + " : " + val[1];
					} else {
						return val;
					}
				},
				natural_arrow_keys: false,
				ticks: [],
				ticks_positions: [],
				ticks_labels: [],
				ticks_snap_bounds: 0,
				ticks_tooltip: false,
				scale: 'linear',
				focus: false,
				tooltip_position: null,
				labelledby: null,
				rangeHighlights: []
			},

			getElement: function getElement() {
				return this.sliderElem;
			},

			getValue: function getValue() {
				if (this.options.range) {
					return this._state.value;
				} else {
					return this._state.value[0];
				}
			},

			setValue: function setValue(val, triggerSlideEvent, triggerChangeEvent) {
				if (!val) {
					val = 0;
				}
				var oldValue = this.getValue();
				this._state.value = this._validateInputValue(val);
				var applyPrecision = this._applyPrecision.bind(this);

				if (this.options.range) {
					this._state.value[0] = applyPrecision(this._state.value[0]);
					this._state.value[1] = applyPrecision(this._state.value[1]);

					this._state.value[0] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[0]));
					this._state.value[1] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[1]));
				} else {
					this._state.value = applyPrecision(this._state.value);
					this._state.value = [Math.max(this.options.min, Math.min(this.options.max, this._state.value))];
					this._addClass(this.handle2, 'hide');
					if (this.options.selection === 'after') {
						this._state.value[1] = this.options.max;
					} else {
						this._state.value[1] = this.options.min;
					}
				}

				if (this.options.max > this.options.min) {
					this._state.percentage = [this._toPercentage(this._state.value[0]), this._toPercentage(this._state.value[1]), this.options.step * 100 / (this.options.max - this.options.min)];
				} else {
					this._state.percentage = [0, 0, 100];
				}

				this._layout();
				var newValue = this.options.range ? this._state.value : this._state.value[0];

				this._setDataVal(newValue);
				if (triggerSlideEvent === true) {
					this._trigger('slide', newValue);
				}
				if (oldValue !== newValue && triggerChangeEvent === true) {
					this._trigger('change', {
						oldValue: oldValue,
						newValue: newValue
					});
				}

				return this;
			},

			destroy: function destroy() {
				// Remove event handlers on slider elements
				this._removeSliderEventHandlers();

				// Remove the slider from the DOM
				this.sliderElem.parentNode.removeChild(this.sliderElem);
				/* Show original <input> element */
				this.element.style.display = "";

				// Clear out custom event bindings
				this._cleanUpEventCallbacksMap();

				// Remove data values
				this.element.removeAttribute("data");

				// Remove JQuery handlers/data
				if ($) {
					this._unbindJQueryEventHandlers();
					this.$element.removeData('slider');
				}
			},

			disable: function disable() {
				this._state.enabled = false;
				this.handle1.removeAttribute("tabindex");
				this.handle2.removeAttribute("tabindex");
				this._addClass(this.sliderElem, 'slider-disabled');
				this._trigger('slideDisabled');

				return this;
			},

			enable: function enable() {
				this._state.enabled = true;
				this.handle1.setAttribute("tabindex", 0);
				this.handle2.setAttribute("tabindex", 0);
				this._removeClass(this.sliderElem, 'slider-disabled');
				this._trigger('slideEnabled');

				return this;
			},

			toggle: function toggle() {
				if (this._state.enabled) {
					this.disable();
				} else {
					this.enable();
				}
				return this;
			},

			isEnabled: function isEnabled() {
				return this._state.enabled;
			},

			on: function on(evt, callback) {
				this._bindNonQueryEventHandler(evt, callback);
				return this;
			},

			off: function off(evt, callback) {
				if ($) {
					this.$element.off(evt, callback);
					this.$sliderElem.off(evt, callback);
				} else {
					this._unbindNonQueryEventHandler(evt, callback);
				}
			},

			getAttribute: function getAttribute(attribute) {
				if (attribute) {
					return this.options[attribute];
				} else {
					return this.options;
				}
			},

			setAttribute: function setAttribute(attribute, value) {
				this.options[attribute] = value;
				return this;
			},

			refresh: function refresh() {
				this._removeSliderEventHandlers();
				createNewSlider.call(this, this.element, this.options);
				if ($) {
					// Bind new instance of slider to the element
					$.data(this.element, 'slider', this);
				}
				return this;
			},

			relayout: function relayout() {
				this._resize();
				this._layout();
				return this;
			},

			/******************************+
   				HELPERS
   	- Any method that is not part of the public interface.
   - Place it underneath this comment block and write its signature like so:
   		_fnName : function() {...}
   	********************************/
			_removeSliderEventHandlers: function _removeSliderEventHandlers() {
				// Remove keydown event listeners
				this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
				this.handle2.removeEventListener("keydown", this.handle2Keydown, false);

				//remove the listeners from the ticks and handles if they had their own listeners
				if (this.options.ticks_tooltip) {
					var ticks = this.ticksContainer.getElementsByClassName('slider-tick');
					for (var i = 0; i < ticks.length; i++) {
						ticks[i].removeEventListener('mouseenter', this.ticksCallbackMap[i].mouseEnter, false);
						ticks[i].removeEventListener('mouseleave', this.ticksCallbackMap[i].mouseLeave, false);
					}
					this.handle1.removeEventListener('mouseenter', this.handleCallbackMap.handle1.mouseEnter, false);
					this.handle2.removeEventListener('mouseenter', this.handleCallbackMap.handle2.mouseEnter, false);
					this.handle1.removeEventListener('mouseleave', this.handleCallbackMap.handle1.mouseLeave, false);
					this.handle2.removeEventListener('mouseleave', this.handleCallbackMap.handle2.mouseLeave, false);
				}

				this.handleCallbackMap = null;
				this.ticksCallbackMap = null;

				if (this.showTooltip) {
					this.handle1.removeEventListener("focus", this.showTooltip, false);
					this.handle2.removeEventListener("focus", this.showTooltip, false);
				}
				if (this.hideTooltip) {
					this.handle1.removeEventListener("blur", this.hideTooltip, false);
					this.handle2.removeEventListener("blur", this.hideTooltip, false);
				}

				// Remove event listeners from sliderElem
				if (this.showTooltip) {
					this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
				}
				if (this.hideTooltip) {
					this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
				}
				this.sliderElem.removeEventListener("touchstart", this.touchstart, false);
				this.sliderElem.removeEventListener("touchmove", this.touchmove, false);
				this.sliderElem.removeEventListener("mousedown", this.mousedown, false);

				// Remove window event listener
				window.removeEventListener("resize", this.resize, false);
			},
			_bindNonQueryEventHandler: function _bindNonQueryEventHandler(evt, callback) {
				if (this.eventToCallbackMap[evt] === undefined) {
					this.eventToCallbackMap[evt] = [];
				}
				this.eventToCallbackMap[evt].push(callback);
			},
			_unbindNonQueryEventHandler: function _unbindNonQueryEventHandler(evt, callback) {
				var callbacks = this.eventToCallbackMap[evt];
				if (callbacks !== undefined) {
					for (var i = 0; i < callbacks.length; i++) {
						if (callbacks[i] === callback) {
							callbacks.splice(i, 1);
							break;
						}
					}
				}
			},
			_cleanUpEventCallbacksMap: function _cleanUpEventCallbacksMap() {
				var eventNames = Object.keys(this.eventToCallbackMap);
				for (var i = 0; i < eventNames.length; i++) {
					var eventName = eventNames[i];
					delete this.eventToCallbackMap[eventName];
				}
			},
			_showTooltip: function _showTooltip() {
				if (this.options.tooltip_split === false) {
					this._addClass(this.tooltip, 'in');
					this.tooltip_min.style.display = 'none';
					this.tooltip_max.style.display = 'none';
				} else {
					this._addClass(this.tooltip_min, 'in');
					this._addClass(this.tooltip_max, 'in');
					this.tooltip.style.display = 'none';
				}
				this._state.over = true;
			},
			_hideTooltip: function _hideTooltip() {
				if (this._state.inDrag === false && this.alwaysShowTooltip !== true) {
					this._removeClass(this.tooltip, 'in');
					this._removeClass(this.tooltip_min, 'in');
					this._removeClass(this.tooltip_max, 'in');
				}
				this._state.over = false;
			},
			_setToolTipOnMouseOver: function _setToolTipOnMouseOver(tempState) {
				var formattedTooltipVal = this.options.formatter(!tempState ? this._state.value[0] : tempState.value[0]);
				var positionPercentages = !tempState ? getPositionPercentages(this._state, this.options.reversed) : getPositionPercentages(tempState, this.options.reversed);
				this._setText(this.tooltipInner, formattedTooltipVal);

				this.tooltip.style[this.stylePos] = positionPercentages[0] + "%";
				if (this.options.orientation === 'vertical') {
					this._css(this.tooltip, "margin-" + this.stylePos, -this.tooltip.offsetHeight / 2 + "px");
				} else {
					this._css(this.tooltip, "margin-" + this.stylePos, -this.tooltip.offsetWidth / 2 + "px");
				}

				function getPositionPercentages(state, reversed) {
					if (reversed) {
						return [100 - state.percentage[0], this.options.range ? 100 - state.percentage[1] : state.percentage[1]];
					}
					return [state.percentage[0], state.percentage[1]];
				}
			},
			_addTickListener: function _addTickListener() {
				return {
					addMouseEnter: function addMouseEnter(reference, tick, index) {
						var enter = function enter() {
							var tempState = reference._state;
							var idString = index >= 0 ? index : this.attributes['aria-valuenow'].value;
							var hoverIndex = parseInt(idString, 10);
							tempState.value[0] = hoverIndex;
							tempState.percentage[0] = reference.options.ticks_positions[hoverIndex];
							reference._setToolTipOnMouseOver(tempState);
							reference._showTooltip();
						};
						tick.addEventListener("mouseenter", enter, false);
						return enter;
					},
					addMouseLeave: function addMouseLeave(reference, tick) {
						var leave = function leave() {
							reference._hideTooltip();
						};
						tick.addEventListener("mouseleave", leave, false);
						return leave;
					}
				};
			},
			_layout: function _layout() {
				var positionPercentages;

				if (this.options.reversed) {
					positionPercentages = [100 - this._state.percentage[0], this.options.range ? 100 - this._state.percentage[1] : this._state.percentage[1]];
				} else {
					positionPercentages = [this._state.percentage[0], this._state.percentage[1]];
				}

				this.handle1.style[this.stylePos] = positionPercentages[0] + "%";
				this.handle1.setAttribute('aria-valuenow', this._state.value[0]);
				if (isNaN(this.options.formatter(this._state.value[0]))) {
					this.handle1.setAttribute('aria-valuetext', this.options.formatter(this._state.value[0]));
				}

				this.handle2.style[this.stylePos] = positionPercentages[1] + "%";
				this.handle2.setAttribute('aria-valuenow', this._state.value[1]);
				if (isNaN(this.options.formatter(this._state.value[1]))) {
					this.handle2.setAttribute('aria-valuetext', this.options.formatter(this._state.value[1]));
				}

				/* Position highlight range elements */
				if (this.rangeHighlightElements.length > 0 && Array.isArray(this.options.rangeHighlights) && this.options.rangeHighlights.length > 0) {
					for (var _i = 0; _i < this.options.rangeHighlights.length; _i++) {
						var startPercent = this._toPercentage(this.options.rangeHighlights[_i].start);
						var endPercent = this._toPercentage(this.options.rangeHighlights[_i].end);

						if (this.options.reversed) {
							var sp = 100 - endPercent;
							endPercent = 100 - startPercent;
							startPercent = sp;
						}

						var currentRange = this._createHighlightRange(startPercent, endPercent);

						if (currentRange) {
							if (this.options.orientation === 'vertical') {
								this.rangeHighlightElements[_i].style.top = currentRange.start + "%";
								this.rangeHighlightElements[_i].style.height = currentRange.size + "%";
							} else {
								if (this.options.rtl) {
									this.rangeHighlightElements[_i].style.right = currentRange.start + "%";
								} else {
									this.rangeHighlightElements[_i].style.left = currentRange.start + "%";
								}
								this.rangeHighlightElements[_i].style.width = currentRange.size + "%";
							}
						} else {
							this.rangeHighlightElements[_i].style.display = "none";
						}
					}
				}

				/* Position ticks and labels */
				if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {

					var styleSize = this.options.orientation === 'vertical' ? 'height' : 'width';
					var styleMargin;
					if (this.options.orientation === 'vertical') {
						styleMargin = 'marginTop';
					} else {
						if (this.options.rtl) {
							styleMargin = 'marginRight';
						} else {
							styleMargin = 'marginLeft';
						}
					}
					var labelSize = this._state.size / (this.options.ticks.length - 1);

					if (this.tickLabelContainer) {
						var extraMargin = 0;
						if (this.options.ticks_positions.length === 0) {
							if (this.options.orientation !== 'vertical') {
								this.tickLabelContainer.style[styleMargin] = -labelSize / 2 + "px";
							}

							extraMargin = this.tickLabelContainer.offsetHeight;
						} else {
							/* Chidren are position absolute, calculate height by finding the max offsetHeight of a child */
							for (i = 0; i < this.tickLabelContainer.childNodes.length; i++) {
								if (this.tickLabelContainer.childNodes[i].offsetHeight > extraMargin) {
									extraMargin = this.tickLabelContainer.childNodes[i].offsetHeight;
								}
							}
						}
						if (this.options.orientation === 'horizontal') {
							this.sliderElem.style.marginBottom = extraMargin + "px";
						}
					}
					for (var i = 0; i < this.options.ticks.length; i++) {

						var percentage = this.options.ticks_positions[i] || this._toPercentage(this.options.ticks[i]);

						if (this.options.reversed) {
							percentage = 100 - percentage;
						}

						this.ticks[i].style[this.stylePos] = percentage + "%";

						/* Set class labels to denote whether ticks are in the selection */
						this._removeClass(this.ticks[i], 'in-selection');
						if (!this.options.range) {
							if (this.options.selection === 'after' && percentage >= positionPercentages[0]) {
								this._addClass(this.ticks[i], 'in-selection');
							} else if (this.options.selection === 'before' && percentage <= positionPercentages[0]) {
								this._addClass(this.ticks[i], 'in-selection');
							}
						} else if (percentage >= positionPercentages[0] && percentage <= positionPercentages[1]) {
							this._addClass(this.ticks[i], 'in-selection');
						}

						if (this.tickLabels[i]) {
							this.tickLabels[i].style[styleSize] = labelSize + "px";

							if (this.options.orientation !== 'vertical' && this.options.ticks_positions[i] !== undefined) {
								this.tickLabels[i].style.position = 'absolute';
								this.tickLabels[i].style[this.stylePos] = percentage + "%";
								this.tickLabels[i].style[styleMargin] = -labelSize / 2 + 'px';
							} else if (this.options.orientation === 'vertical') {
								if (this.options.rtl) {
									this.tickLabels[i].style['marginRight'] = this.sliderElem.offsetWidth + "px";
								} else {
									this.tickLabels[i].style['marginLeft'] = this.sliderElem.offsetWidth + "px";
								}
								this.tickLabelContainer.style[styleMargin] = this.sliderElem.offsetWidth / 2 * -1 + 'px';
							}
						}
					}
				}

				var formattedTooltipVal;

				if (this.options.range) {
					formattedTooltipVal = this.options.formatter(this._state.value);
					this._setText(this.tooltipInner, formattedTooltipVal);
					this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0]) / 2 + "%";

					if (this.options.orientation === 'vertical') {
						this._css(this.tooltip, "margin-" + this.stylePos, -this.tooltip.offsetHeight / 2 + "px");
					} else {
						this._css(this.tooltip, "margin-" + this.stylePos, -this.tooltip.offsetWidth / 2 + "px");
					}

					var innerTooltipMinText = this.options.formatter(this._state.value[0]);
					this._setText(this.tooltipInner_min, innerTooltipMinText);

					var innerTooltipMaxText = this.options.formatter(this._state.value[1]);
					this._setText(this.tooltipInner_max, innerTooltipMaxText);

					this.tooltip_min.style[this.stylePos] = positionPercentages[0] + "%";

					if (this.options.orientation === 'vertical') {
						this._css(this.tooltip_min, "margin-" + this.stylePos, -this.tooltip_min.offsetHeight / 2 + "px");
					} else {
						this._css(this.tooltip_min, "margin-" + this.stylePos, -this.tooltip_min.offsetWidth / 2 + "px");
					}

					this.tooltip_max.style[this.stylePos] = positionPercentages[1] + "%";

					if (this.options.orientation === 'vertical') {
						this._css(this.tooltip_max, "margin-" + this.stylePos, -this.tooltip_max.offsetHeight / 2 + "px");
					} else {
						this._css(this.tooltip_max, "margin-" + this.stylePos, -this.tooltip_max.offsetWidth / 2 + "px");
					}
				} else {
					formattedTooltipVal = this.options.formatter(this._state.value[0]);
					this._setText(this.tooltipInner, formattedTooltipVal);

					this.tooltip.style[this.stylePos] = positionPercentages[0] + "%";
					if (this.options.orientation === 'vertical') {
						this._css(this.tooltip, "margin-" + this.stylePos, -this.tooltip.offsetHeight / 2 + "px");
					} else {
						this._css(this.tooltip, "margin-" + this.stylePos, -this.tooltip.offsetWidth / 2 + "px");
					}
				}

				if (this.options.orientation === 'vertical') {
					this.trackLow.style.top = '0';
					this.trackLow.style.height = Math.min(positionPercentages[0], positionPercentages[1]) + '%';

					this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
					this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';

					this.trackHigh.style.bottom = '0';
					this.trackHigh.style.height = 100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';
				} else {
					if (this.stylePos === 'right') {
						this.trackLow.style.right = '0';
					} else {
						this.trackLow.style.left = '0';
					}
					this.trackLow.style.width = Math.min(positionPercentages[0], positionPercentages[1]) + '%';

					if (this.stylePos === 'right') {
						this.trackSelection.style.right = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
					} else {
						this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
					}
					this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';

					if (this.stylePos === 'right') {
						this.trackHigh.style.left = '0';
					} else {
						this.trackHigh.style.right = '0';
					}
					this.trackHigh.style.width = 100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';

					var offset_min = this.tooltip_min.getBoundingClientRect();
					var offset_max = this.tooltip_max.getBoundingClientRect();

					if (this.options.tooltip_position === 'bottom') {
						if (offset_min.right > offset_max.left) {
							this._removeClass(this.tooltip_max, 'bottom');
							this._addClass(this.tooltip_max, 'top');
							this.tooltip_max.style.top = '';
							this.tooltip_max.style.bottom = 22 + 'px';
						} else {
							this._removeClass(this.tooltip_max, 'top');
							this._addClass(this.tooltip_max, 'bottom');
							this.tooltip_max.style.top = this.tooltip_min.style.top;
							this.tooltip_max.style.bottom = '';
						}
					} else {
						if (offset_min.right > offset_max.left) {
							this._removeClass(this.tooltip_max, 'top');
							this._addClass(this.tooltip_max, 'bottom');
							this.tooltip_max.style.top = 18 + 'px';
						} else {
							this._removeClass(this.tooltip_max, 'bottom');
							this._addClass(this.tooltip_max, 'top');
							this.tooltip_max.style.top = this.tooltip_min.style.top;
						}
					}
				}
			},
			_createHighlightRange: function _createHighlightRange(start, end) {
				if (this._isHighlightRange(start, end)) {
					if (start > end) {
						return { 'start': end, 'size': start - end };
					}
					return { 'start': start, 'size': end - start };
				}
				return null;
			},
			_isHighlightRange: function _isHighlightRange(start, end) {
				if (0 <= start && start <= 100 && 0 <= end && end <= 100) {
					return true;
				} else {
					return false;
				}
			},
			_resize: function _resize(ev) {
				/*jshint unused:false*/
				this._state.offset = this._offset(this.sliderElem);
				this._state.size = this.sliderElem[this.sizePos];
				this._layout();
			},
			_removeProperty: function _removeProperty(element, prop) {
				if (element.style.removeProperty) {
					element.style.removeProperty(prop);
				} else {
					element.style.removeAttribute(prop);
				}
			},
			_mousedown: function _mousedown(ev) {
				if (!this._state.enabled) {
					return false;
				}

				this._state.offset = this._offset(this.sliderElem);
				this._state.size = this.sliderElem[this.sizePos];

				var percentage = this._getPercentage(ev);

				if (this.options.range) {
					var diff1 = Math.abs(this._state.percentage[0] - percentage);
					var diff2 = Math.abs(this._state.percentage[1] - percentage);
					this._state.dragged = diff1 < diff2 ? 0 : 1;
					this._adjustPercentageForRangeSliders(percentage);
				} else {
					this._state.dragged = 0;
				}

				this._state.percentage[this._state.dragged] = percentage;
				this._layout();

				if (this.touchCapable) {
					document.removeEventListener("touchmove", this.mousemove, false);
					document.removeEventListener("touchend", this.mouseup, false);
				}

				if (this.mousemove) {
					document.removeEventListener("mousemove", this.mousemove, false);
				}
				if (this.mouseup) {
					document.removeEventListener("mouseup", this.mouseup, false);
				}

				this.mousemove = this._mousemove.bind(this);
				this.mouseup = this._mouseup.bind(this);

				if (this.touchCapable) {
					// Touch: Bind touch events:
					document.addEventListener("touchmove", this.mousemove, false);
					document.addEventListener("touchend", this.mouseup, false);
				}
				// Bind mouse events:
				document.addEventListener("mousemove", this.mousemove, false);
				document.addEventListener("mouseup", this.mouseup, false);

				this._state.inDrag = true;
				var newValue = this._calculateValue();

				this._trigger('slideStart', newValue);

				this._setDataVal(newValue);
				this.setValue(newValue, false, true);

				ev.returnValue = false;

				if (this.options.focus) {
					this._triggerFocusOnHandle(this._state.dragged);
				}

				return true;
			},
			_touchstart: function _touchstart(ev) {
				if (ev.changedTouches === undefined) {
					this._mousedown(ev);
					return;
				}

				var touch = ev.changedTouches[0];
				this.touchX = touch.pageX;
				this.touchY = touch.pageY;
			},
			_triggerFocusOnHandle: function _triggerFocusOnHandle(handleIdx) {
				if (handleIdx === 0) {
					this.handle1.focus();
				}
				if (handleIdx === 1) {
					this.handle2.focus();
				}
			},
			_keydown: function _keydown(handleIdx, ev) {
				if (!this._state.enabled) {
					return false;
				}

				var dir;
				switch (ev.keyCode) {
					case 37: // left
					case 40:
						// down
						dir = -1;
						break;
					case 39: // right
					case 38:
						// up
						dir = 1;
						break;
				}
				if (!dir) {
					return;
				}

				// use natural arrow keys instead of from min to max
				if (this.options.natural_arrow_keys) {
					var ifVerticalAndNotReversed = this.options.orientation === 'vertical' && !this.options.reversed;
					var ifHorizontalAndReversed = this.options.orientation === 'horizontal' && this.options.reversed; // @todo control with rtl

					if (ifVerticalAndNotReversed || ifHorizontalAndReversed) {
						dir = -dir;
					}
				}

				var val = this._state.value[handleIdx] + dir * this.options.step;
				var percentage = val / this.options.max * 100;
				this._state.keyCtrl = handleIdx;
				if (this.options.range) {
					this._adjustPercentageForRangeSliders(percentage);
					var val1 = !this._state.keyCtrl ? val : this._state.value[0];
					var val2 = this._state.keyCtrl ? val : this._state.value[1];
					val = [val1, val2];
				}

				this._trigger('slideStart', val);
				this._setDataVal(val);
				this.setValue(val, true, true);

				this._setDataVal(val);
				this._trigger('slideStop', val);
				this._layout();

				this._pauseEvent(ev);
				delete this._state.keyCtrl;

				return false;
			},
			_pauseEvent: function _pauseEvent(ev) {
				if (ev.stopPropagation) {
					ev.stopPropagation();
				}
				if (ev.preventDefault) {
					ev.preventDefault();
				}
				ev.cancelBubble = true;
				ev.returnValue = false;
			},
			_mousemove: function _mousemove(ev) {
				if (!this._state.enabled) {
					return false;
				}

				var percentage = this._getPercentage(ev);
				this._adjustPercentageForRangeSliders(percentage);
				this._state.percentage[this._state.dragged] = percentage;
				this._layout();

				var val = this._calculateValue(true);
				this.setValue(val, true, true);

				return false;
			},
			_touchmove: function _touchmove(ev) {
				if (ev.changedTouches === undefined) {
					return;
				}

				var touch = ev.changedTouches[0];

				var xDiff = touch.pageX - this.touchX;
				var yDiff = touch.pageY - this.touchY;

				if (!this._state.inDrag) {
					// Vertical Slider
					if (this.options.orientation === 'vertical' && xDiff <= 5 && xDiff >= -5 && (yDiff >= 15 || yDiff <= -15)) {
						this._mousedown(ev);
					}
					// Horizontal slider.
					else if (yDiff <= 5 && yDiff >= -5 && (xDiff >= 15 || xDiff <= -15)) {
							this._mousedown(ev);
						}
				}
			},
			_adjustPercentageForRangeSliders: function _adjustPercentageForRangeSliders(percentage) {
				if (this.options.range) {
					var precision = this._getNumDigitsAfterDecimalPlace(percentage);
					precision = precision ? precision - 1 : 0;
					var percentageWithAdjustedPrecision = this._applyToFixedAndParseFloat(percentage, precision);
					if (this._state.dragged === 0 && this._applyToFixedAndParseFloat(this._state.percentage[1], precision) < percentageWithAdjustedPrecision) {
						this._state.percentage[0] = this._state.percentage[1];
						this._state.dragged = 1;
					} else if (this._state.dragged === 1 && this._applyToFixedAndParseFloat(this._state.percentage[0], precision) > percentageWithAdjustedPrecision) {
						this._state.percentage[1] = this._state.percentage[0];
						this._state.dragged = 0;
					} else if (this._state.keyCtrl === 0 && this._state.value[1] / this.options.max * 100 < percentage) {
						this._state.percentage[0] = this._state.percentage[1];
						this._state.keyCtrl = 1;
						this.handle2.focus();
					} else if (this._state.keyCtrl === 1 && this._state.value[0] / this.options.max * 100 > percentage) {
						this._state.percentage[1] = this._state.percentage[0];
						this._state.keyCtrl = 0;
						this.handle1.focus();
					}
				}
			},
			_mouseup: function _mouseup() {
				if (!this._state.enabled) {
					return false;
				}
				if (this.touchCapable) {
					// Touch: Unbind touch event handlers:
					document.removeEventListener("touchmove", this.mousemove, false);
					document.removeEventListener("touchend", this.mouseup, false);
				}
				// Unbind mouse event handlers:
				document.removeEventListener("mousemove", this.mousemove, false);
				document.removeEventListener("mouseup", this.mouseup, false);

				this._state.inDrag = false;
				if (this._state.over === false) {
					this._hideTooltip();
				}
				var val = this._calculateValue(true);

				this._layout();
				this._setDataVal(val);
				this._trigger('slideStop', val);

				return false;
			},
			_calculateValue: function _calculateValue(snapToClosestTick) {
				var val;
				if (this.options.range) {
					val = [this.options.min, this.options.max];
					if (this._state.percentage[0] !== 0) {
						val[0] = this._toValue(this._state.percentage[0]);
						val[0] = this._applyPrecision(val[0]);
					}
					if (this._state.percentage[1] !== 100) {
						val[1] = this._toValue(this._state.percentage[1]);
						val[1] = this._applyPrecision(val[1]);
					}
				} else {
					val = this._toValue(this._state.percentage[0]);
					val = parseFloat(val);
					val = this._applyPrecision(val);
				}

				if (snapToClosestTick) {
					var min = [val, Infinity];
					for (var i = 0; i < this.options.ticks.length; i++) {
						var diff = Math.abs(this.options.ticks[i] - val);
						if (diff <= min[1]) {
							min = [this.options.ticks[i], diff];
						}
					}
					if (min[1] <= this.options.ticks_snap_bounds) {
						return min[0];
					}
				}

				return val;
			},
			_applyPrecision: function _applyPrecision(val) {
				var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.options.step);
				return this._applyToFixedAndParseFloat(val, precision);
			},
			_getNumDigitsAfterDecimalPlace: function _getNumDigitsAfterDecimalPlace(num) {
				var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
				if (!match) {
					return 0;
				}
				return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
			},
			_applyToFixedAndParseFloat: function _applyToFixedAndParseFloat(num, toFixedInput) {
				var truncatedNum = num.toFixed(toFixedInput);
				return parseFloat(truncatedNum);
			},
			/*
   	Credits to Mike Samuel for the following method!
   	Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
   */
			_getPercentage: function _getPercentage(ev) {
				if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) {
					ev = ev.touches[0];
				}

				var eventPosition = ev[this.mousePos];
				var sliderOffset = this._state.offset[this.stylePos];
				var distanceToSlide = eventPosition - sliderOffset;
				if (this.stylePos === 'right') {
					distanceToSlide = -distanceToSlide;
				}
				// Calculate what percent of the length the slider handle has slid
				var percentage = distanceToSlide / this._state.size * 100;
				percentage = Math.round(percentage / this._state.percentage[2]) * this._state.percentage[2];
				if (this.options.reversed) {
					percentage = 100 - percentage;
				}

				// Make sure the percent is within the bounds of the slider.
				// 0% corresponds to the 'min' value of the slide
				// 100% corresponds to the 'max' value of the slide
				return Math.max(0, Math.min(100, percentage));
			},
			_validateInputValue: function _validateInputValue(val) {
				if (!isNaN(+val)) {
					return +val;
				} else if (Array.isArray(val)) {
					this._validateArray(val);
					return val;
				} else {
					throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(val));
				}
			},
			_validateArray: function _validateArray(val) {
				for (var i = 0; i < val.length; i++) {
					var input = val[i];
					if (typeof input !== 'number') {
						throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(input));
					}
				}
			},
			_setDataVal: function _setDataVal(val) {
				this.element.setAttribute('data-value', val);
				this.element.setAttribute('value', val);
				this.element.value = val;
			},
			_trigger: function _trigger(evt, val) {
				val = val || val === 0 ? val : undefined;

				var callbackFnArray = this.eventToCallbackMap[evt];
				if (callbackFnArray && callbackFnArray.length) {
					for (var i = 0; i < callbackFnArray.length; i++) {
						var callbackFn = callbackFnArray[i];
						callbackFn(val);
					}
				}

				/* If JQuery exists, trigger JQuery events */
				if ($) {
					this._triggerJQueryEvent(evt, val);
				}
			},
			_triggerJQueryEvent: function _triggerJQueryEvent(evt, val) {
				var eventData = {
					type: evt,
					value: val
				};
				this.$element.trigger(eventData);
				this.$sliderElem.trigger(eventData);
			},
			_unbindJQueryEventHandlers: function _unbindJQueryEventHandlers() {
				this.$element.off();
				this.$sliderElem.off();
			},
			_setText: function _setText(element, text) {
				if (typeof element.textContent !== "undefined") {
					element.textContent = text;
				} else if (typeof element.innerText !== "undefined") {
					element.innerText = text;
				}
			},
			_removeClass: function _removeClass(element, classString) {
				var classes = classString.split(" ");
				var newClasses = element.className;

				for (var i = 0; i < classes.length; i++) {
					var classTag = classes[i];
					var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
					newClasses = newClasses.replace(regex, " ");
				}

				element.className = newClasses.trim();
			},
			_addClass: function _addClass(element, classString) {
				var classes = classString.split(" ");
				var newClasses = element.className;

				for (var i = 0; i < classes.length; i++) {
					var classTag = classes[i];
					var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
					var ifClassExists = regex.test(newClasses);

					if (!ifClassExists) {
						newClasses += " " + classTag;
					}
				}

				element.className = newClasses.trim();
			},
			_offsetLeft: function _offsetLeft(obj) {
				return obj.getBoundingClientRect().left;
			},
			_offsetRight: function _offsetRight(obj) {
				return obj.getBoundingClientRect().right;
			},
			_offsetTop: function _offsetTop(obj) {
				var offsetTop = obj.offsetTop;
				while ((obj = obj.offsetParent) && !isNaN(obj.offsetTop)) {
					offsetTop += obj.offsetTop;
					if (obj.tagName !== 'BODY') {
						offsetTop -= obj.scrollTop;
					}
				}
				return offsetTop;
			},
			_offset: function _offset(obj) {
				return {
					left: this._offsetLeft(obj),
					right: this._offsetRight(obj),
					top: this._offsetTop(obj)
				};
			},
			_css: function _css(elementRef, styleName, value) {
				if ($) {
					$.style(elementRef, styleName, value);
				} else {
					var style = styleName.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function (all, letter) {
						return letter.toUpperCase();
					});
					elementRef.style[style] = value;
				}
			},
			_toValue: function _toValue(percentage) {
				return this.options.scale.toValue.apply(this, [percentage]);
			},
			_toPercentage: function _toPercentage(value) {
				return this.options.scale.toPercentage.apply(this, [value]);
			},
			_setTooltipPosition: function _setTooltipPosition() {
				var tooltips = [this.tooltip, this.tooltip_min, this.tooltip_max];
				if (this.options.orientation === 'vertical') {
					var tooltipPos;
					if (this.options.tooltip_position) {
						tooltipPos = this.options.tooltip_position;
					} else {
						if (this.options.rtl) {
							tooltipPos = 'left';
						} else {
							tooltipPos = 'right';
						}
					}
					var oppositeSide = tooltipPos === 'left' ? 'right' : 'left';
					tooltips.forEach(function (tooltip) {
						this._addClass(tooltip, tooltipPos);
						tooltip.style[oppositeSide] = '100%';
					}.bind(this));
				} else if (this.options.tooltip_position === 'bottom') {
					tooltips.forEach(function (tooltip) {
						this._addClass(tooltip, 'bottom');
						tooltip.style.top = 22 + 'px';
					}.bind(this));
				} else {
					tooltips.forEach(function (tooltip) {
						this._addClass(tooltip, 'top');
						tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px';
					}.bind(this));
				}
			}
		};

		/*********************************
  		Attach to global namespace
  	*********************************/
		if ($ && $.fn) {
			var autoRegisterNamespace = void 0;

			if (!$.fn.slider) {
				$.bridget(NAMESPACE_MAIN, Slider);
				autoRegisterNamespace = NAMESPACE_MAIN;
			} else {
				if (windowIsDefined) {
					window.console.warn("bootstrap-slider.js - WARNING: $.fn.slider namespace is already bound. Use the $.fn.bootstrapSlider namespace instead.");
				}
				autoRegisterNamespace = NAMESPACE_ALTERNATE;
			}
			$.bridget(NAMESPACE_ALTERNATE, Slider);

			// Auto-Register data-provide="slider" Elements
			$(function () {
				$("input[data-provide=slider]")[autoRegisterNamespace]();
			});
		}
	})($);

	return Slider;
});
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/lp-iconcolor.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/* iconcolor.js contains all js for icon changes  */
/*  Author : CrdioStudio Dev team */

jQuery.noConflict();
/* for 1.2.9 */

function changeColInUri(data, colfrom, colto) {
    // create fake image to calculate height / width
    //var img = document.createElement("img");
    var img = new Image();
    img.src = data;
    img.style.visibility = "hidden";
    document.body.appendChild(img);

    var canvas = document.createElement("canvas");
    canvas.id = 'canvas';
    canvas.width = img.offsetWidth;
    canvas.height = img.offsetHeight;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // remove image
    img.parentNode.removeChild(img);

    // do actual color replacement

    if (canvas.width != 0 && canvas != undefined) {
        var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

        var data = imageData.data;

        var rgbfrom = hexToRGB(colfrom);
        var rgbto = hexToRGB(colto);

        var r, g, b;
        for (var x = 0, len = data.length; x < len; x += 4) {
            r = data[x];
            g = data[x + 1];
            b = data[x + 2];


            data[x] = rgbto.r;
            data[x + 1] = rgbto.g;
            data[x + 2] = rgbto.b;


        }

        ctx.putImageData(imageData, 0, 0);
    }
    return canvas.toDataURL();
}


jQuery(document).ready(function($) {


    jQuery('#input-dropdown').find('li').each(function() {
        var iconsrc = jQuery(this).find('img').attr('src');
        if (iconsrc != '' && iconsrc != undefined) {
            var changecolor = changeColInUri(iconsrc, "#41A6DF", "#ffffff");
            jQuery(this).prepend('<img class="h-icon" alt="image" src="' + changecolor + '" />');
        }
    });

    jQuery('.listing-single-cat').find('li').each(function() {
        var iconsrc = jQuery(this).find('.base-icon').attr('src');
        if (iconsrc != '' && iconsrc != undefined) {
            var changecolor = changeColInUri(iconsrc, "#41A6DF", "#ffffff");
            jQuery(this).find('.base-icon').attr("src", changecolor);
        }
    });

    jQuery('.user-portfolio ul.post-socials').find('li').each(function() {
        var iconsrc = jQuery(this).find('.icon').attr('src');
        if (iconsrc != '' && iconsrc != undefined) {
            var changecolor = changeColInUri(iconsrc, "#ffffff", "#41A6DF");
            jQuery(this).find('.icon').attr("src", changecolor);
        }
    });


    jQuery('.blog-social ul.blog-social').find('li').each(function() {
        var iconsrc = jQuery(this).find('.icon').attr('src');
        if (iconsrc != '' && iconsrc != undefined) {
            var changecolor = changeColInUri(iconsrc, "#ffffff", "#41A6DF");
            jQuery(this).find('.icon').attr("src", changecolor);
        }
    });

    jQuery('.user-info ul.social-icons').find('li').each(function() {
        var iconsrc = jQuery(this).find('.icon').attr('src');
        if (iconsrc != '' && iconsrc != undefined) {
            var changecolor = changeColInUri(iconsrc, "#ffffff", "#6e6e6e");
            jQuery(this).find('.icon').attr("src", changecolor);
        }
    });

    jQuery('.popup-post-left-bottom ul.social-icons').find('li').each(function() {
        var iconsrc = jQuery(this).find('.icon').attr('src');
        if (iconsrc != '' && iconsrc != undefined) {
            var changecolor = changeColInUri(iconsrc, "#ffffff", "#6e6e6e");
            jQuery(this).find('.icon').attr("src", changecolor);
        }
    });

});
/* end for 1.2.9 */;
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/lp-gps.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/* lp gps  */

var geocoderr;

function lpGetGpsLocName(lpcalback){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position){
            var clat = position.coords.latitude;
            var clong = position.coords.longitude;
            jpCodeLatLng(clat,clong, function(citynamevalue){
                lpcalback(citynamevalue);
            });
        });

    } else {
        alert("Geolocation is not supported by this browser.");
    }

}

function lpgeocodeinitialize() {
    geocoderr = new google.maps.Geocoder();
}

function jpCodeLatLng(lat, lng, lpcitycallback) {
    var geocoder, city, state, country;
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);

    geocoder.geocode(
        {'latLng': latlng},
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                for (var ac = 0; ac < results[0].address_components.length; ac++) {
                    var component = results[0].address_components[ac];

                    switch(component.types[0]) {
                        case 'locality':
                            city = component.long_name;
                            break;
                        case 'administrative_area_level_1':
                            state = component.short_name;
                            break;
                        case 'country':

                            country = component.short_name;
                            break;
                    }
                };

                //lpcitycallback(state);
                //lpcitycallback(country);
                lpcitycallback(city);


            }
            else {
                console.log("Geocoder failed due to: " + status);
            }
        }
    );



}


/* test call */

jQuery(document).ready(function(){
    lpgeocodeinitialize();
});
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/pricing.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/*--------------------------------- Price plan Hide and show features----------------------------------*/

jQuery(document).ready(function () {

    //new code 2.6.15
    jQuery(document).on('click', '.lp-hide-show-price-features', function () {
        var $this = jQuery(this);
        var showfeaures = jQuery(this).data('show');
        var hidefeaures = jQuery(this).data('hide');
        jQuery('.lp-hide-show-price-features').text(showfeaures);


        if (false == jQuery(this).next().is(':visible')) { //hide current tab when click on other tab
            //jQuery('.lp-price-list').slideUp(700);
            jQuery(".lp-hide-show-price-features").removeClass('expanded');

        }

        $this.toggleClass('MoreDetails');

        if ($this.hasClass('MoreDetails')) {
            $this.text(hidefeaures);

            //jQuery(this).closest('.section-lp-price-list').find('.lp-price-list').slideDown(700);
            jQuery(".lp-price-list").fadeIn('400');

        } else {

            //jQuery(this).closest('.section-lp-price-list').find('.lp-price-list').slideUp(700);

            $this.text(showfeaures);

            jQuery(".lp-price-list").fadeOut('400');

        }

    });
    //end new code 2.6.15
});


/*-------------------Selected Radio Button ----------------*/
jQuery(document).ready(function () {
    jQuery('.lp-price-cats-with-icon li input[type=radio]').click(function () {
        jQuery('.lp-price-cats-with-icon li input[type=radio]:not(:checked)').parent().removeClass("active-category-radio");
        jQuery('.lp-price-cats-with-icon li input[type=radio]:checked').parent().addClass("active-category-radio");
    });
});


jQuery(document).ready(function () {
    jQuery('.lp-price-cats-with-icon-v2 li input[type=radio]').click(function () {
        jQuery('.lp-price-cats-with-icon-v2 li input[type=radio]:not(:checked)').parent().removeClass("active-category-radio-v2");
        jQuery('.lp-price-cats-with-icon-v2 li input[type=radio]:checked').parent().addClass("active-category-radio-v2");
    });
});

// Horizontal view 1 pricing version
jQuery(document).ready(function () {
    jQuery(document).on('click', '.horizontal_view_list li input[type=radio]', function () {

        jQuery('.horizontal_view_list li input[type=radio]:not(:checked)').parent('label').removeClass("price_plan_active_disable");
        jQuery('.horizontal_view_list li input[type=radio]:checked').parent('label').addClass("price_plan_active_disable");

        // Add class for show horizontial view with the reference of this class    
        jQuery('.lp_hori_view_plan_left_section').removeClass('horizontal_choose_button');
        jQuery(this).closest('.lp_hori_view_plan_left_section').addClass('horizontal_choose_button');
        // add class for horizontial plan height 
        jQuery(this).closest('.lp-horizontial-specific').addClass('lp-horizontial-specific-height');

    });
    // remove class for horizontial plan height
    jQuery(document).on('click', '.lp-standerd-exlusiv button', function (event) {
        jQuery('.lp-horizontial-specific').removeClass('lp-horizontial-specific-height');
    });
    jQuery(document).on('click', '.lp_button_switcher span', function (event) {
        jQuery('.lp-horizontial-specific').removeClass('lp-horizontial-specific-height');
    });

    jQuery('.horizontal_view_list li:nth(0) input[type=radio]').trigger('click').parent('label').addClass("price_plan_active_disable");
});



/*----------------slider for pricing plan category-----------------*/

jQuery(document).ready(function () {

    var x = jQuery('.lp_category_list_slide').children();

    for (i = 0; i < x.length; i += 1) {
        x.slice(i, i + 1).wrapAll('<div class="' + i + '"></div>');
    }
    if (jQuery('.lp_category_list_slide').length != 0) {
        jQuery('.lp_category_list_slide').slick({
            slidesToShow: 5,
            slidesToScroll: 1,
            prevNext: true,
            arrows: true,
            dots: false,
            responsive: [
                {
                    breakpoint: 768,
                    settings: {
                        arrows: true,
                        infinite: false,
                        slidesToShow: 4,
                        slidesToScroll: 1
                    }
                },
                {
                    breakpoint: 481,
                    settings: {
                        arrows: true,
                        infinite: false,
                        slidesToShow: 3,
                        slidesToScroll: 1
                    }
                },

                {
                    breakpoint: 390,
                    settings: {
                        arrows: true,
                        infinite: false,
                        slidesToShow: 2,
                        slidesToScroll: 1
                    }
                }
            ]
        });
    }

});


/*--------------- Slider For pricing plan packages--------------*/


/*jQuery(document).ready(function(){
  jQuery('.slider_pricing_Plan').slick({
   slidesToShow: 3,
   slidesToScroll: 1,
  arrows: true,
  fade: true,
  dots: true,
  arrows:true
  });
});*/


/*----------Drop down Category list for pricing plan-------------------*/

jQuery(document).ready(function () {
    //jQuery("#category_dropdown").select2({minimumResultsForSearch: -1});

    jQuery('#category_dropdown').on('select2:select', function (e) {

        $this = jQuery(this);
        jQuery("body").addClass("listingpro-loading");
        jQuery('#cats-selected-plans').html('');
        var templatestyle = jQuery(this).closest('#select_style').data('style');

        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_term_object.ajaxurl,
            data: {
                'action': 'listingpro_select_plan_by_cat',
                'term_id': $this.val(),
                'templatestyle': templatestyle,
            },
            success: function (data) {
                jQuery("body").removeClass("listingpro-loading");
                if (data.plans) {
                    jQuery('#cats-selected-plans').html(data.plans);
                    var $hiddenField = '<input type="hidden" name="lp_pre_selected_cats" value="' + $this.val() + '" />';
                    jQuery($hiddenField).appendTo(".price-plan-button");
                }
            }
        });
    });

});


// Pricing Plan tool tip 

jQuery(document).ready(function () {


    jQuery('.tooltip_price_features span').on('mouseover', function () {
        var $this = jQuery(this);
        $this.closest('.tooltip_price_features').find('.lp_tooltip_text').css("visibility", "visible");

    });

    jQuery('.tooltip_price_features span').on('mouseout', function () {
        var $this = jQuery(this);
        $this.closest('.tooltip_price_features').find('.lp_tooltip_text').css("visibility", "hidden");

    });

});

// Pricing Plan tool tip  for ajax response

jQuery(document).ready(function () {

    jQuery(document).on('mouseover', '.tooltip_price_features span', function () {
        var $this = jQuery(this);
        $this.closest('.tooltip_price_features').find('.lp_tooltip_text').css("visibility", "visible");

    });

    jQuery(document).on('mouseout', '.tooltip_price_features span', function () {
        var $this = jQuery(this);
        $this.closest('.tooltip_price_features').find('.lp_tooltip_text').css("visibility", "hidden");

    });
});
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/main.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/* Main.js contains all main JS  */
/*  Author : CrdioStudio Dev team */

/*moin 31-03-017 strt*/
jQuery.noConflict();

jQuery(window).on("resize load live", function () {
    jQuery(window).resize(function () {
        if (jQuery(window).width() <= 768) {
            jQuery("a.open-map-view").on("click", function (event) {
                event.preventDefault();
                jQuery(".sidemap-container").addClass("open-map");
                jQuery("header").addClass("map-view-content");
            });

            jQuery("a.open-img-view").on("click", function (event) {
                event.preventDefault();
                jQuery(".sidemap-container").removeClass("open-map");
                jQuery("header").removeClass("map-view-content");
            });

            if (jQuery("#wpadminbar").length > 0) {
                jQuery("html body").css("margin-top", "-46px");
            }
        } else {
            jQuery(".sidemap-container").removeClass("open-map");
            if (jQuery("#wpadminbar").length > 0) {
                jQuery("html body").css("margin-top", "0px");
            }

            jQuery("a.open-map-view").on("click", function (event) {
                event.preventDefault();
                jQuery(".sidemap-container").addClass("open-map");
                jQuery("header").addClass("map-view-content");
            });

            jQuery("a.open-img-view").on("click", function (event) {
                event.preventDefault();
                jQuery(".sidemap-container").removeClass("open-map");
                jQuery("header").removeClass("map-view-content");
            });
        }
        if (jQuery(window).width() <= 480) {
            jQuery("#more_filters").hide();
        } else {
            jQuery("#more_filters").show();
        }
    });
});
jQuery(document).ready(function () {
    jQuery(".lp_cancel_notic").click(function (e) {
        e.preventDefault();

        jQuery(".lp_notification_wrapper").slideToggle(400);
    });

    jQuery(".claimformtrigger2").click(function () {
        jQuery("header").addClass("lp-head-zindex");
        var divHeight = jQuery(".leftside").height();
        jQuery(".rightside").css("height", divHeight + "px");
    });

    jQuery(".lp-click-zindex").click(function () {
        jQuery("header").removeClass("lp-head-zindex");
    });

    jQuery('.lp-tagline-submit-tagline label input[type="checkbox"]').click(
        function (event) {
            if (jQuery(this).prop("checked") == true) {
                jQuery(".with-title-cond").fadeIn(700);
            } else if (jQuery(this).prop("checked") == false) {
                jQuery(".with-title-cond").fadeOut(700);
            }
        }
    );

    jQuery(".stickynavbar ul li").each(function (e) {
        var tagetID = jQuery(this).find("a").attr("href");
        if (jQuery(tagetID).length == 0) {
            jQuery(this).remove();
        }
    });

    // Search Top margin in map view
    var hh = jQuery("header").outerHeight();
    var ab = jQuery(".absolute");
    ab.css("top", hh);

    // Touch Behaviorr for Mobile devices
    if (jQuery(".chosen-container").length > 0) {
        jQuery(".chosen-container").on("touchstart", function (e) {
            e.stopPropagation();
            e.preventDefault();
            // Trigger the mousedown event.
            jQuery(this).trigger("mousedown");
        });
    }

    jQuery("#see_filter").on("click", function (event) {
        event.preventDefault();
        var filter = jQuery("#more_filters");
        jQuery(this).next("#more_filters").toggleClass("open_filter");
        if (filter.hasClass("open_filter")) {
            jQuery(this).next("#more_filters").slideDown(400);
        } else {
            jQuery(this).next("#more_filters").slideUp(400);
        }
    });
});
/*moin 31-03-017 ends*/

/* by zaheer on 30 march */
jQuery(document).ready(function ($) {
    var loc = jQuery(".ui-widget").data("option");
    var apiType = jQuery("#page").data("ipapi");

    var currentlocationswitch = "1";

    currentlocationswitch = jQuery("#page").data("lpcurrentloconhome");
    if (currentlocationswitch == "0") {
        loc = "locationifoff";
        jQuery(".lp-location-search .ui-widget > i").fadeOut("fast");
    }

    if (loc == "yes") {
        if (
            (jQuery(".form-group").is(".lp-location-search") ||
                jQuery(".form-group").is(".lp-location-inner-search")) &&
            (jQuery("body").is(".home") || jQuery("body").is(".app-view-home"))
        ) {
            if (apiType === "ip_api") {
                jQuery.get(
                    "https://ipapi.co/json",
                    function (location) {
                        var c_loc = location.city;
                        var lp_s_loc = c_loc;
                        if (jQuery("#page").data("lpattern") == "with_region") {
                            c_loc =
                                location.city +
                                " " +
                                location.region_code +
                                ", " +
                                location.country_name;
                            lp_s_loc = location.city + " " + location.region_code;
                        }
                        jQuery("#searchlocation")
                            .prop("disabled", true)
                            .trigger("chosen:updated");
                        jQuery("#searchlocation").find("#def_location").text(c_loc);
                        jQuery("#searchlocation").find("#def_location").val(c_loc);
                        jQuery("#cities").val(c_loc);
                        jQuery("input[name=lp_s_loc]").val(lp_s_loc);
                        // jQuery(".select2-selection__rendered").attr("title",location.city).text(location.city);
                        jQuery("#searchlocation")
                            .prop("disabled", false)
                            .trigger("chosen:updated");
                        jQuery(".select2-selection__rendered")
                            .parent(".select2-selection")
                            .addClass("slide-right");
                        jQuery(".lp-location-search .ui-widget > i").fadeOut("slow");
                    },
                    "json"
                );
            } else {
                lpGetGpsLocName(function (lpgetcurrentcityvalue) {
                    lpgpsclocation = lpgetcurrentcityvalue;
                    jQuery("#searchlocation")
                        .prop("disabled", true)
                        .trigger("chosen:updated");
                    jQuery("#searchlocation").find("#def_location").text(lpgpsclocation);
                    jQuery("#searchlocation").find("#def_location").val(lpgpsclocation);
                    jQuery("#cities").val(lpgpsclocation);
                    jQuery("input[name=lp_s_loc]").val(lpgpsclocation);
                    // jQuery(".select2-selection__rendered").attr("title",lpgpsclocation).text(lpgpsclocation);
                    jQuery("#searchlocation")
                        .prop("disabled", false)
                        .trigger("chosen:updated");
                    jQuery(".select2-selection__rendered")
                        .parent(".select2-selection")
                        .addClass("slide-right");
                    jQuery(".lp-location-search .ui-widget > i").fadeOut("slow");
                });
            }
            jQuery(".chosen-select2").chosen({
                disable_search: true,
            });
            jQuery(".chosen-select1").chosen({
                disable_search: true,
            });
            jQuery(".chosen-select7").chosen({
                disable_search: true,
            });
            jQuery(".chosen-select5").chosen({
                disable_search: true,
            });
        }
    } else if (loc == "no") {
        jQuery(".lp-location-search .ui-widget > i").on("click", function (event) {
            event.preventDefault();
            jQuery(this).addClass("fa-circle-o-notch fa-spin");
            jQuery(this).removeClass("fa-crosshairs");
            if (jQuery(".form-group").is(".lp-location-search")) {
                if (apiType === "ip_api") {
                    jQuery.get(
                        "https://ipapi.co/json",
                        function (location) {
                            jQuery(".chosen-single").addClass("remove-margin");
                            jQuery("#searchlocation")
                                .prop("disabled", true)
                                .trigger("chosen:updated");

                            if (location.city == null) { } else {
                                jQuery("#select2-searchlocation-container").text(location.city);
                                // jQuery('#searchlocation').find('#def_location').text(location.city);
                                jQuery("#searchlocation")
                                    .find("#def_location")
                                    .val(location.city)
                                    .text(location.city);
                                jQuery("#cities").val(location.city);
                                jQuery("input[name=lp_s_loc]").val(location.city);
                            }

                            // jQuery(".select2-selection__rendered").attr("title",location.city).text(location.city);
                            jQuery("#searchlocation")
                                .prop("disabled", false)
                                .trigger("chosen:updated");
                            jQuery(".select2-selection__rendered")
                                .parent(".select2-selection")
                                .addClass("slide-right");
                            jQuery(".lp-location-search .ui-widget > i").fadeOut("slow");
                        },
                        "json"
                    );
                } else {
                    lpGetGpsLocName(function (lpgetcurrentcityvalue) {
                        lpgpsclocation = lpgetcurrentcityvalue;
                        jQuery(".chosen-single").addClass("remove-margin");
                        jQuery("#searchlocation")
                            .prop("disabled", true)
                            .trigger("chosen:updated");
                        jQuery("#select2-searchlocation-container").text(lpgpsclocation);
                        jQuery("#searchlocation")
                            .find("#def_location")
                            .val(lpgpsclocation)
                            .text(lpgpsclocation);
                        jQuery("#cities").val(lpgpsclocation);
                        jQuery("input[name=lp_s_loc]").val(lpgpsclocation);
                        // jQuery(".select2-selection__rendered").attr("title",lpgpsclocation).text(lpgpsclocation);
                        jQuery("#searchlocation")
                            .prop("disabled", false)
                            .trigger("chosen:updated");
                        jQuery(".select2-selection__rendered")
                            .parent(".select2-selection")
                            .addClass("slide-right");
                        jQuery(".lp-location-search .ui-widget > i").fadeOut("slow");
                    });
                }
                jQuery(".chosen-select2").chosen({
                    disable_search: true,
                });
                jQuery(".chosen-select1").chosen({
                    disable_search: true,
                });
                jQuery(".chosen-select7").chosen({
                    disable_search: true,
                });
                jQuery(".chosen-select5").chosen({
                    disable_search: true,
                });
            }
        });
    }

    jQuery("#lp-new-ad-compaignForm").on("submit", function (e) {
        var $this = jQuery(this);
        if ($this.data("type") == "adsperclick") {
            totalPrice = jQuery('input[name="ads_price"]').val();
            var spotlight = 0,
                topos = 0,
                sidebar = 0;
            if ($this.find("#spotlightcmp").is(":checked")) {
                spotlight = $this.find("#spotlightcmp").data("price");
            }
            if ($this.find("#camp-for-search").is(":checked")) {
                topos = $this.find("#camp-for-search").data("price");
            }
            if ($this.find("#for-sidebar-camp").is(":checked")) {
                sidebar = $this.find("#for-sidebar-camp").data("price");
            }
            var minbujet = spotlight + topos + sidebar;
            if (totalPrice < minbujet) {
                e.preventDefault();
                e.stopPropagation();
                alert($this.data("string") + " " + minbujet);
                return false;
            }
        } else {
            totalPrice = jQuery('input[name="ads_price"]').val();
        }

        method = jQuery('input[name="method"]:checked').val();
        currency = $this.find('input[name="currency"]').val();
        listing_id = jQuery("input[name=lp_ads_for_listing]").val();
        listing_name = jQuery("input[name=lp_ads_title]").val();
        taxRate = $this.find('input[name="taxprice"]').val();

        if (listing_id === "" || method === "") {
            alert(jQuery("input#ad-blank-errorMsg").val());
            e.preventDefault();
        } else if (method === "stripe") {
            currency = $this.data("paid_currency");
            totalPrice = parseFloat(totalPrice) * 100;
            totalPrice = parseFloat(totalPrice).toFixed();

            handler.open({
                name: listing_name,
                description: "",
                zipCode: true,
                amount: totalPrice,
                currency: currency,
            });
            e.preventDefault();
        } else if (method === "2checkout") {
            var packages = [];
            jQuery('input.checked_class[type="checkbox"]:checked').each(function () {
                packages.push($this.data("package"));
            });
            jQuery("#myCCForm #tprice").val(totalPrice);
            jQuery("#myCCForm #listing_id_2check").val(listing_id);
            jQuery("#myCCForm #packages").val(packages);
            jQuery("#myCCForm #taxprice").val(
                $this.find('input[name="taxprice"]').val()
            );
            jQuery("button.lp-2checkout-modal2").trigger("click");
            e.preventDefault();
        }
    });
});
/* end by zaheer on 30 march */

jQuery(window).on("load", function () {
    jQuery(".lp-suggested-search").on("click", function (event) {
        jQuery("#input-dropdown").niceScroll({
            cursorcolor: "#363F48",
            cursoropacitymax: 1,
            boxzoom: false,
            cursorwidth: "10px",
            cursorborderradius: "0px",
            cursorborder: "0px solid #fff",
            touchbehavior: true,
            preventmultitouchscrolling: false,
            cursordragontouch: true,
            background: "#f7f7f7",
            horizrailenabled: false,
            autohidemode: false,
            zindex: "999999",
        });
    });

    // Notices Box Script
    jQuery(".notice a.close").on("click", function (event) {
        event.preventDefault();
        jQuery(this).parent(".notice").fadeOut("slow");
    });

    jQuery(
        ".lp-header-full-width .lp-menu-bar .header-filter, .lp-menu-bar .header-filter.pos-relative.form-group"
    ).css("display", "block");

    var logoH = jQuery(".lp-logo").outerHeight();
    var acHgt = jQuery(".header-right-panel.clearfix");
    var a = parseInt(logoH + 10);
    var b = jQuery(".header-right-panel").height();
    var c = a - b;
    var d = c / 2;
    //alert(b);
    acHgt.css({
        "padding-top": d + "px",
    });

    jQuery(".rating-symbol:nth-child(1)").hover(
        function () {
            jQuery(".review.angry").css({
                opacity: "1",
                visibility: "visible",
            });
        },
        function () {
            jQuery(".review.angry").css({
                opacity: "0",
                visibility: "hidden",
            });
        }
    );
    jQuery(".rating-symbol:nth-child(2)").hover(
        function () {
            jQuery(".review.cry").css({
                opacity: "1",
                visibility: "visible",
            });
        },
        function () {
            jQuery(".review.cry").css({
                opacity: "0",
                visibility: "hidden",
            });
        }
    );
    jQuery(".rating-symbol:nth-child(3)").hover(
        function () {
            jQuery(".review.sleeping").css({
                opacity: "1",
                visibility: "visible",
            });
        },
        function () {
            jQuery(".review.sleeping").css({
                opacity: "0",
                visibility: "hidden",
            });
        }
    );
    jQuery(".rating-symbol:nth-child(4)").hover(
        function () {
            jQuery(".review.smily").css({
                opacity: "1",
                visibility: "visible",
            });
        },
        function () {
            jQuery(".review.smily").css({
                opacity: "0",
                visibility: "hidden",
            });
        }
    );
    jQuery(".rating-symbol:nth-child(5)").hover(
        function () {
            jQuery(".review.cool").css({
                opacity: "1",
                visibility: "visible",
            });
        },
        function () {
            jQuery(".review.cool").css({
                opacity: "0",
                visibility: "hidden",
            });
        }
    );

    var rtngSym = jQuery(".rating-symbol");
    var rtngTip = jQuery("input.rating-tooltip");

    jQuery(".rating-symbol:first-of-type").hover(
        function () {
            jQuery(this).closest("span").addClass("active-stars-wrap");
            jQuery(
                ".active-stars-wrap .rating-symbol:first-of-type .rating-symbol-foreground span"
            ).css("color", "#de9147");
        },
        function () {
            jQuery(".active-stars-wrap").removeClass("active-stars-wrap");
        }
    );
    jQuery(".rating-symbol:nth-of-type(2)").hover(
        function () {
            jQuery(this).closest("span").addClass("active-stars-wrap");
            jQuery(
                ".active-stars-wrap .rating-symbol:first-of-type .rating-symbol-foreground span"
            ).css("color", "#de9147");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(2) .rating-symbol-foreground span"
            ).css("color", "#de9147");
        },
        function () {
            jQuery(".active-stars-wrap").removeClass("active-stars-wrap");
        }
    );
    jQuery(".rating-symbol:nth-of-type(3)").hover(
        function () {
            jQuery(this).closest("span").addClass("active-stars-wrap");
            jQuery(
                ".active-stars-wrap .rating-symbol:first-of-type .rating-symbol-foreground span"
            ).css("color", "#dec435");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(2) .rating-symbol-foreground span"
            ).css("color", "#dec435");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(3) .rating-symbol-foreground span"
            ).css("color", "#dec435");
        },
        function () {
            jQuery(".active-stars-wrap").removeClass("active-stars-wrap");
        }
    );
    jQuery(".rating-symbol:nth-of-type(4)").hover(
        function () {
            jQuery(this).closest("span").addClass("active-stars-wrap");
            jQuery(
                ".active-stars-wrap .rating-symbol:first-of-type .rating-symbol-foreground span"
            ).css("color", "#c5de35");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(2) .rating-symbol-foreground span"
            ).css("color", "#c5de35");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(3) .rating-symbol-foreground span"
            ).css("color", "#c5de35");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(4) .rating-symbol-foreground span"
            ).css("color", "#c5de35");
        },
        function () {
            jQuery(".active-stars-wrap").removeClass("active-stars-wrap");
        }
    );
    jQuery(".rating-symbol:nth-of-type(5)").hover(
        function () {
            jQuery(this).closest("span").addClass("active-stars-wrap");
            jQuery(
                ".active-stars-wrap .rating-symbol:first-of-type .rating-symbol-foreground span"
            ).css("color", "#73cf42");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(2) .rating-symbol-foreground span"
            ).css("color", "#73cf42");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(3) .rating-symbol-foreground span"
            ).css("color", "#73cf42");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(4) .rating-symbol-foreground span"
            ).css("color", "#73cf42");
            jQuery(
                ".active-stars-wrap .rating-symbol:nth-of-type(5) .rating-symbol-foreground span"
            ).css("color", "#73cf42");
        },
        function () {
            jQuery(".active-stars-wrap").removeClass("active-stars-wrap");
        }
    );

    rtngSym.on("click", function (event) {
        event.preventDefault();
        var thsVal = jQuery("input.rating-tooltip").val();

        //alert(thsVal);
        if (thsVal == 1) {
            jQuery(".review.angry").addClass("visible");
            jQuery(".rating-symbol:first-of-type").addClass("angry");
            jQuery(".rating-symbol").removeClass("cry");
            jQuery(".rating-symbol").removeClass("sleeping");
            jQuery(".rating-symbol").removeClass("smily");
            jQuery(".rating-symbol").removeClass("cool");
        } else {
            jQuery(".review.angry").removeClass("visible");
        }

        if (thsVal == 2) {
            jQuery(".review.cry").addClass("visible");
            jQuery(".rating-symbol:first-of-type").addClass("cry");
            jQuery(".rating-symbol:nth-of-type(2)").addClass("cry");
            jQuery(".rating-symbol").removeClass("angry");
            jQuery(".rating-symbol").removeClass("sleeping");
            jQuery(".rating-symbol").removeClass("smily");
            jQuery(".rating-symbol").removeClass("cool");
        } else {
            jQuery(".review.cry").removeClass("visible");
        }

        if (thsVal == 3) {
            jQuery(".review.sleeping").addClass("visible");
            jQuery(".rating-symbol:first-of-type").addClass("sleeping");
            jQuery(".rating-symbol:nth-of-type(2)").addClass("sleeping");
            jQuery(".rating-symbol:nth-of-type(3)").addClass("sleeping");
            jQuery(".rating-symbol").removeClass("angry");
            jQuery(".rating-symbol").removeClass("cry");
            jQuery(".rating-symbol").removeClass("smily");
            jQuery(".rating-symbol").removeClass("cool");
        } else {
            jQuery(".review.sleeping").removeClass("visible");
        }

        if (thsVal == 4) {
            jQuery(".review.smily").addClass("visible");
            jQuery(".rating-symbol:first-of-type").addClass("smily");
            jQuery(".rating-symbol:nth-of-type(2)").addClass("smily");
            jQuery(".rating-symbol:nth-of-type(3)").addClass("smily");
            jQuery(".rating-symbol:nth-of-type(4)").addClass("smily");
            jQuery(".rating-symbol").removeClass("angry");
            jQuery(".rating-symbol").removeClass("cry");
            jQuery(".rating-symbol").removeClass("sleeping");
            jQuery(".rating-symbol").removeClass("cool");
        } else {
            jQuery(".review.smily").removeClass("visible");
        }

        if (thsVal == 5) {
            jQuery(".review.cool").addClass("visible");
            jQuery(".rating-symbol:first-of-type").addClass("cool");
            jQuery(".rating-symbol:nth-of-type(2)").addClass("cool");
            jQuery(".rating-symbol:nth-of-type(3)").addClass("cool");
            jQuery(".rating-symbol:nth-of-type(4)").addClass("cool");
            jQuery(".rating-symbol:nth-of-type(5)").addClass("cool");
            jQuery(".rating-symbol").removeClass("angry");
            jQuery(".rating-symbol").removeClass("cry");
            jQuery(".rating-symbol").removeClass("sleeping");
            jQuery(".rating-symbol").removeClass("smily");
        } else {
            jQuery(".review.cool").removeClass("visible");
        }

        var CheckMultiRatingState = jQuery("#rewies_form").data("multi-rating");
        var ratingSumTotal = 0;
        if (CheckMultiRatingState == 1) {
            var activeRatingLength = jQuery(".lp-multi-rating-val").length;
            jQuery(".lp-multi-rating-val").each(function (index) {
                ratingSumTotal += Number(jQuery(this).val());
            });
            var activeRatingClass = Math.round(ratingSumTotal / activeRatingLength);

            jQuery(".lp-review-stars").removeClass(function (index, css) {
                return (css.match(/\bactive-rating-avg\S+/g) || []).join(" ");
            });
            jQuery(".lp-review-stars").addClass(
                "active-rating-avg" + activeRatingClass
            );

            jQuery(
                ".lp-review-stars i.fa:nth-child(" + Number(activeRatingClass + 1) + ")"
            )
                .removeClass("fa-star-o")
                .addClass("fa-star");
            jQuery(
                ".lp-review-stars i.fa:nth-child(" + Number(activeRatingClass + 1) + ")"
            )
                .prevAll(".fa-star-o")
                .removeClass("fa-star-o")
                .addClass("fa-star");
            jQuery(
                ".lp-review-stars i.fa:nth-child(" + Number(activeRatingClass + 1) + ")"
            )
                .nextAll(".fa-star")
                .removeClass("fa-star-o")
                .addClass("fa-star-o");
        }
    });
});

var siteurl = jQuery("#page").data("site-url");
var sitelogo = jQuery("#page").data("sitelogo");
var $menu = jQuery("#menu");
if ($menu.length > 0) {
    $menu.css("visibility", "visible");
    $menu.mmenu({
        extensions: ["pagedim-black"],
        iconPanels: true,
        navbar: {
            title: "",
        },
        navbars: {
            height: 3,
            content: [
                '<a href="' +
                siteurl +
                '" class="userimage"><img class="icon icons8-Contacts" src="' +
                sitelogo +
                '" alt="user"></a>',
            ],
        },
    });
    jQuery("div#menu").removeClass("menu-height-0");
    var API = $menu.data("mmenu");
    jQuery(
        ".lpl-button.md-trigger, .sign-login-wrap .md-trigger,.lpl-button.app-view-popup-style"
    ).click(function () {
        API.close();
    });
}

jQuery(document).on(
    "click",
    ".footer-btn-right.map-view-btn, .v2-map-load .v2mapwrap, .listing-app-view-bar .right-icons a, .sidemap-fixed .sidemarpInside",
    function (e) {
        if (jQuery("#map").is(".mapSidebar")) {
            var defmaplat = jQuery("body").data("defaultmaplat");
            var defmaplong = jQuery("body").data("defaultmaplot");
            jQuery(".map-pop").empty();
            jQuery(".map-pop").html('<div class="mapSidebar" id="map"></div>');
            var map = null;
            $mtoken = jQuery("#page").data("mtoken");
            $mtype = jQuery("#page").data("mtype");
            $mapboxDesign = jQuery("#page").data("mstyle");

            if ($mtoken !== "" && $mtype === "mapbox") {
                L.mapbox.accessToken = $mtoken;
                map = L.mapbox.map("map").setView([defmaplat, defmaplong], 2);
                L.tileLayer(
                    "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", {
                    maxZoom: 18,
                    id: jQuery("#page").data("mstyle"),
                    accessToken: jQuery("#page").data("mtoken"),
                }
                ).addTo(map);

                var markers = new L.MarkerClusterGroup();
                initializeMap(markers);
                map.fitBounds(markers.getBounds(), {
                    padding: [50, 50],
                });
                jQuery(document).on("click", ".open-map-view", function () {
                    L.Util.requestAnimFrame(map.invalidateSize, map, !1, map._container);
                });
            } else {
                var map = new L.Map("map", {
                    minZoom: 3,
                }).setView(new L.LatLng(defmaplat, defmaplong), 6);
                if ($mtype == "google") {
                    L.tileLayer("http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}", {
                        maxZoom: 6,
                        subdomains: ["mt0", "mt1", "mt2", "mt3"],
                        noWrap: true,
                    });
                    var googleLayer = new L.Google("ROADMAP");
                    map.addLayer(googleLayer);
                } else {
                    L.tileLayer(
                        "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    ).addTo(map);
                }

                var markers = new L.MarkerClusterGroup();
                var resmarkers = initializeMap(markers);
                if (typeof resmarkers === "undefined") { } else {
                    map.fitBounds(markers.getBounds(), {
                        padding: [50, 50],
                    });
                    map.scrollWheelZoom.enable();
                    map.invalidateSize();
                    map.dragging.enable();
                    jQuery(document).on("click", ".open-map-view", function () {
                        L.Util.requestAnimFrame(
                            map.invalidateSize,
                            map,
                            !1,
                            map._container
                        );
                    });
                }
            }

            function initializeMap(markers) {
                if (jQuery(".lp-grid-box-contianer").length != 0) {
                    markers.clearLayers();
                    jQuery(".lp-grid-box-contianer").each(function (i) {
                        var LPtitle = jQuery(this).data("title");
                        var LPposturl = jQuery(this).data("posturl");
                        var LPlattitue = jQuery(this).data("lattitue");
                        var LPlongitute = jQuery(this).data("longitute");
                        var LPpostid = jQuery(this).data("postid");
                        var LPiconSrc = "";

                        if (jQuery(".v2-map-load").length == 1) {
                            if (jQuery(".v2-map-load").hasClass("v2_map_load_old")) {
                                var LPaddress = jQuery(this).find(".gaddress").text();
                                var LPimageSrc = jQuery(this)
                                    .find(".lp-grid-box-thumb")
                                    .find("img")
                                    .attr("src");
                                if (typeof jQuery("body").data("deficon") !== "undefined") {
                                    // your code here
                                    LPiconSrc = jQuery("body").data("deficon");
                                } else {
                                    LPiconSrc = jQuery(this)
                                        .find(".cat-icon")
                                        .find("img")
                                        .attr("src");
                                }
                            } else {
                                var LPaddress = jQuery(this)
                                    .find(".lp-listing-location")
                                    .find("a")
                                    .text();
                                var LPimageSrc = jQuery(this)
                                    .find(".lp-listing-top-thumb")
                                    .find("img")
                                    .attr("src");

                                if (typeof jQuery("body").data("deficon") !== "undefined") {
                                    // your code here
                                    LPiconSrc = jQuery("body").data("deficon");
                                } else {
                                    LPiconSrc = jQuery(this)
                                        .find(".cat-icon")
                                        .find("img")
                                        .attr("src");
                                }
                            }
                        } else if (jQuery(".lp-compact-view-outer").length > 0) {
                            var LPaddress = jQuery(this).find(".lp_list_address").text();
                            var LPimageSrc = jQuery(this)
                                .find(".lp-listing-top-thumb")
                                .find("img")
                                .attr("src");
                            var LPiconSrc = jQuery(this)
                                .find(".cat-icon")
                                .find("img")
                                .attr("src");
                            if (typeof jQuery("body").data("deficon") !== "undefined") {
                                LPiconSrc = jQuery("body").data("deficon");
                            }
                        } else {
                            var LPaddress = jQuery(this).find(".gaddress").text();
                            var LPimageSrc = jQuery(this)
                                .find(".listing-app-view-new-wrap")
                                .find("img")
                                .attr("src");
                            if (LPimageSrc === undefined) {
                                LPimageSrc = jQuery(this).data("feaimg");
                            }
                            if (LPimageSrc === undefined) {
                                if (jQuery(".lp-grid-box-thumb .show-img").length > 0) {
                                    LPimageSrc = jQuery(this)
                                        .find(".lp-grid-box-thumb .show-img img")
                                        .attr("src");
                                } else {
                                    LPimageSrc = jQuery(this)
                                        .find(".lp-grid-box-thumb .show img")
                                        .attr("src");
                                }
                            }
                            if (typeof jQuery("body").data("deficon") !== "undefined") {
                                // your code here
                                LPiconSrc = jQuery("body").data("deficon");
                            } else {
                                LPiconSrc = jQuery(this)
                                    .find(".cat-icon")
                                    .find("img")
                                    .attr("src");
                            }
                        }
                        if (LPlattitue != "" && LPlongitute != "") {
                            var LPimage = "";
                            if (LPimageSrc != "") {
                                LPimage = LPimageSrc;
                            }

                            var LPicon = "";
                            if (LPiconSrc != "") {
                                LPicon = LPiconSrc;
                            }

                            if (jQuery(this).find(".cat-icon i").length > 0) {
                                LPicon = jQuery(this).find(".cat-icon").html();
                            } else {
                                LPicon = "<img alt='image' src='" + LPicon + "' />";
                            }

                            var markerLocation = new L.LatLng(LPlattitue, LPlongitute); // London

                            var CustomHtmlIcon = L.divIcon({
                                html: "<div class='lpmap-icon-shape pin card" +
                                    LPpostid +
                                    "'><div class='lpmap-icon-contianer'>" +
                                    LPicon +
                                    "</div></div>",
                            });

                            var marker = new L.Marker(markerLocation, {
                                icon: CustomHtmlIcon,
                            })
                                .bindPopup(
                                    '<div class="map-post"><div class="map-post-thumb"><a target="_blank" href="' +
                                    LPposturl +
                                    '"><img alt="image" src="' +
                                    LPimage +
                                    '" ></a></div><div class="map-post-des"><div class="map-post-title"><h5><a target="_blank" href="' +
                                    LPposturl +
                                    '">' +
                                    LPtitle +
                                    '</a></h5></div><div class="map-post-address"><p><i class="fa fa-map-marker"></i> ' +
                                    LPaddress +
                                    "</p></div></div></div>"
                                )
                                .addTo(map);
                            markers.addLayer(marker);
                            map.addLayer(markers);
                        }
                    });
                    return true;
                }
            }
        }
    }
);
jQuery(document).ready(function () {
    "use-strict";
    // Disable next button
    var checkdInput = jQuery(".checkboxx input.checked_class");
    checkdInput.on("change", function (event) {
        event.preventDefault();
        if (checkdInput.is(":checked")) {
            jQuery("a#lp-next").css("display", "block");
            jQuery("a#lp-next").removeClass("hide");
            jQuery("span.show").removeClass("show");
            jQuery(
                ".promotional-section > .lp-face.lp-pay-options.lp-dash-sec > span"
            ).addClass("hide");
        } else {
            jQuery("a#lp-next").addClass("hide");
            jQuery(
                ".promotional-section > .lp-face.lp-pay-options.lp-dash-sec > span"
            ).addClass("show");
        }
    });

    var rdoInput = jQuery(".lp-method-wrap input.radio_checked");
    rdoInput.on("change", function (event) {
        event.preventDefault();
        if (rdoInput.is(":checked")) {
            jQuery("input.lp-next2.promotebtn").css("display", "block");
            jQuery("input.lp-next2.promotebtn").removeClass("hide");
            jQuery(".promotional-section span.proceed-btn").removeClass("show");
            jQuery(".promotional-section span.proceed-btn").addClass("hide");
        } else {
            jQuery("input.lp-next2.promotebtn").addClass("hide");
            jQuery(".promotional-section span.proceed-btn").addClass("show");
        }
    });

    //Dashboard promotional script
    jQuery(".promotional-section a.lp-submit-btn").on("click", function (event) {
        event.preventDefault();
        jQuery(this).parent(".promotional-section").slideUp(500);
        jQuery(this)
            .parent(".promotional-section")
            .next(".lp-card > form#ads_promotion")
            .slideDown(1000);
    });

    // Dashboard Left Panel Script

    var dash = jQuery(
        ".dashboard-tabs.lp-main-tabs.text-center > ul > li.dropdown > a"
    );

    var dashli = jQuery(
        ".dashboard-tabs.lp-main-tabs.text-center > ul > li.dropdown"
    );

    var dashul = jQuery(
        ".dashboard-tabs.lp-main-tabs.text-center > ul > li.dropdown > ul"
    );

    dash.on("click", function (event) {
        event.preventDefault();

        if (dashli.hasClass("opened")) {
            jQuery(dashli).removeClass("opened");

            jQuery(dashul).removeClass("opened");

            jQuery(this).parent("li").addClass("opened");

            jQuery(this).next("ul").addClass("opened");
        } else {
            //if(dashli.hasClass('dropdown'))

            jQuery(dashul).removeClass("opened");

            jQuery(dashli).removeClass("opened");

            jQuery(this).parent("li").addClass("opened");

            jQuery(this).next("ul").addClass("opened");
        }
    });

    // Review Script
    jQuery("h3#reply-title").on("click", function (event) {
        event.preventDefault();
        var thiss = jQuery(this);
        if (thiss.hasClass("active")) {
            jQuery(this).removeClass("active");
            jQuery(this).next("#rewies_form").slideUp();
            jQuery(this).next("#rewies_formm").slideUp();
        } else {
            jQuery(this).addClass("active");
            jQuery(this).next("#rewies_form").slideDown();
            jQuery(this).next("#rewies_formm").slideDown();
        }

        //jQuery(this).next('#rewies_form').toggleClass('open_review_form');
    });
    jQuery("#clicktoreview").on("click", function (event) {
        event.preventDefault();

        var thiss = jQuery("#reply-title");
        thiss.addClass("active");
        thiss.next("#rewies_form").slideDown();
        thiss.next("#rewies_formm").slideDown();
        jQuery("html, body").animate({
            scrollTop: jQuery("#reply-title").offset().top,
        },
            2000
        );
    });

    jQuery(".leadformtrigger").on("click", function (e) {
        e.preventDefault();
        jQuery(".app-view-lead-form").slideToggle(500);
    });
    jQuery(".open-lead-form-app-view").on("click", function (e) {
        if (jQuery(".app-view-lead-form")[0]) {
            jQuery(".app-view-lead-form").slideToggle(500);
            jQuery("html, body").animate({
                scrollTop: jQuery(".leadformtrigger").offset().top,
            },
                2000
            );
        }
    });

    jQuery("#rewies_form input[type=file]").change(function (e) {
        $in = jQuery(this);
        $in.prev().prev().text($in.val());
    });
    // listing layout
    //jQuery('.listing-simple').addClass('listing_list_view');
    jQuery("a.grid").on("click", function (event) {
        event.preventDefault();
        jQuery("a.list").removeClass("active");
        jQuery(this).addClass("active");
        jQuery(".listing-simple").removeClass("listing_list_view");

        if (
            jQuery("#list-grid-view-v2").length != 0 &&
            jQuery("#list-grid-view-v2").hasClass("swtch-ll")
        ) {
            jQuery("#list-grid-view-v2").attr("data-layout-class", "grid");
        }

        if (jQuery("#content-grids").hasClass("v2-toggle")) {
            jQuery(".loop-switch-class").removeClass("col-md-12");
            jQuery(".loop-switch-class").addClass("col-md-6");
            jQuery(".lp-listings.active-view").removeClass("list-style");
            jQuery(".lp-listings.active-view").addClass("grid-style");
        } else {
            jQuery(".post-with-map-container")
                .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                .removeClass("col-sm-12 list_view");
            jQuery(".post-with-map-container")
                .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                .addClass("col-md-6 col-sm-12 grid_view2");

            // Listing Simple
            if (
                jQuery("#content-grids").hasClass("listing-with-header-filters-wrap")
            ) {
                jQuery(".listing-simple")
                    .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                    .removeClass("col-sm-12 list_view");
                jQuery(".listing-simple")
                    .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                    .addClass("col-md-6 col-sm-12 grid_view2");
            } else {
                jQuery(".listing-simple")
                    .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                    .removeClass("col-sm-12 list_view");
                jQuery(".listing-simple")
                    .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                    .addClass("col-md-4 col-sm-12 grid_view2");
            }

            // Listing Sidebar
            jQuery(".listing-with-sidebar")
                .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                .removeClass("col-sm-12 list_view");
            jQuery(".listing-with-sidebar")
                .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                .addClass("col-md-6 col-sm-12 grid_view2");
        }

        // Listing with Map
    });
    jQuery("a.list").on("click", function (event) {
        event.preventDefault();
        jQuery("a.grid").removeClass("active");
        jQuery(this).addClass("active");
        jQuery(".listing-simple").addClass("listing_list_view");

        if (
            jQuery("#list-grid-view-v2").length != 0 &&
            jQuery("#list-grid-view-v2").hasClass("swtch-ll")
        ) {
            jQuery("#list-grid-view-v2").attr("data-layout-class", "list");
        }

        if (jQuery("#content-grids").hasClass("v2-toggle")) {
            jQuery(".loop-switch-class").removeClass("col-md-6");
            jQuery(".loop-switch-class").addClass("col-md-12");
            jQuery(".lp-listings.active-view").addClass("list-style");
            jQuery(".lp-listings.active-view").removeClass("grid-style");
        } else {
            // Listing with Map
            jQuery(".post-with-map-container")
                .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                .removeClass("col-md-6 col-sm-6 grid_view2");
            jQuery(".post-with-map-container")
                .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                .addClass("col-sm-12 list_view");

            // Listing Simple
            if (
                jQuery("#content-grids").hasClass("listing-with-header-filters-wrap")
            ) {
                jQuery(".listing-simple")
                    .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                    .removeClass("col-md-6 col-sm-6 grid_view2");
                jQuery(".listing-simple")
                    .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                    .addClass("col-sm-12 list_view");
            } else {
                jQuery(".listing-simple")
                    .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                    .removeClass("col-md-4 col-sm-6 grid_view2");
                jQuery(".listing-simple")
                    .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                    .addClass("col-sm-12 list_view");
            }

            jQuery(".listing-with-sidebar")
                .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                .removeClass("col-md-6 col-sm-6 grid_view3");
            jQuery(".listing-with-sidebar")
                .find(".lp-grid-box-contianer.card1.lp-grid-box-contianer1")
                .addClass("col-sm-12 list_view");
        }
    });

    //============================================ Harry Code ==================================================//
    // Open Hours Script
    jQuery("a.show-all-timings").on("click", function (event) {
        event.preventDefault();
        jQuery(this).toggleClass("opened");
        jQuery(this).next("ul.hidding-timings").slideToggle(400);
    });

    // shebi Script
    jQuery(".detail-page2-tab-content .review-form h3").removeAttr("id");

    jQuery(
        ".listing-app-view .listing-app-view-bar .pricy-form-group #lp-find-near-me-outer ul > li > a"
    ).click(function () {
        jQuery(this).toggleClass("margin-right-0 lp-remove-border");
    });

    var inputs = document.querySelectorAll(".inputfile");
    Array.prototype.forEach.call(inputs, function (input) {
        var label = input.nextElementSibling,
            labelVal = label.innerHTML;

        input.addEventListener("change", function (e) {
            var fileName = "";
            if (this.files && this.files.length > 1)
                fileName = (this.getAttribute("data-multiple-caption") || "").replace(
                    "{count}",
                    this.files.length
                );
            else fileName = e.target.value.split("\\").pop();

            if (fileName) label.querySelector("span").innerHTML = fileName;
            else label.innerHTML = labelVal;
        });

        // Firefox bug fix
        input.addEventListener("focus", function () {
            input.classList.add("has-focus");
        });
        input.addEventListener("blur", function () {
            input.classList.remove("has-focus");
        });
    });

    /* from sheibi */

    if (
        jQuery("body").hasClass("home") ||
        jQuery("body").hasClass("app-view-home")
    ) {
        jQuery(
            ".listing-app-view.home .map-view-list-container2,.listing-app-view.app-view-home .map-view-list-container2"
        ).slick({
            centerMode: false,
            centerPadding: "0px",
            infinite: true,
            accesibility: false,
            draggable: true,
            swipe: true,
            touchMove: false,
            autoplaySpeed: 1400,
            speed: 100,
            slidesToShow: 2,
            dots: true,
            arrows: false,
        });

        jQuery(
            ".listing-app-view.home .lp-location-slider,.listing-app-view.app-view-home .lp-location-slider"
        ).slick({
            centerMode: false,
            centerPadding: "0px",
            infinite: true,
            accesibility: false,
            draggable: true,
            swipe: true,
            touchMove: false,
            autoplaySpeed: 1400,
            speed: 100,
            slidesToShow: 3,
            dots: true,
            arrows: false,
        });
    }
    if (jQuery(".listing-category-slider4").length > 0) {
        jQuery(".listing-category-slider4").slick({
            centerMode: false,
            centerPadding: "0px",
            infinite: true,
            accesibility: false,
            draggable: true,
            swipe: true,
            touchMove: false,
            autoplaySpeed: 1400,
            speed: 100,
            slidesToShow: 4,
            dots: false,
            arrows: true,
            responsive: [{
                breakpoint: 768,
                settings: {
                    arrows: false,
                    centerMode: false,
                    centerPadding: "0px",
                    slidesToShow: 4,
                },
            },
            {
                breakpoint: 480,
                settings: {
                    arrows: false,
                    centerMode: false,
                    centerPadding: "0px",
                    slidesToShow: 1,
                },
            },
            ],
        });
    }

    jQuery("#map-view-icon2").click(function () {
        jQuery("#search-filter-attr-filter").animate({
            width: "toggle",
        },
            5
        );
    });

    jQuery(".listing-app-view .lp-search-toggle .user-menu").click(function (e) {
        jQuery(".lp-user-menu").toggleClass("main");
    });

    jQuery(document).mouseup(function (e) {
        var container = jQuery(".lp-user-menu");
        if (!container.is(e.target) && container.has(e.target).length === 0) {
            jQuery(".lp-user-menu").removeClass("main");
        }
    });
    jQuery(".lp-detail-page-template-3 #clicktoreview2").on(
        "click",
        function (event) {
            event.preventDefault();
            jQuery(".single-tabber2 ul li").removeClass("active");
            jQuery(".detail-page2-tab-content .tab-content .tab-pane").removeClass(
                "active"
            );
            jQuery(".single-tabber2 ul .lpreviews").addClass("active");
            jQuery(".detail-page2-tab-content .tab-content .lpreviews").addClass(
                "active"
            );

            jQuery("html, body").animate({
                scrollTop: jQuery("#review-section").offset().top,
            },
                200
            );
        }
    );
    // end shoaib Script

    jQuery('[data-toggle="tooltip"]').tooltip();

    // Open review reply
    jQuery("a.see_more_btn").on("click", function (event) {
        event.preventDefault();
        var $this = jQuery(this);
        if ($this.hasClass("closedd")) {
            $this.removeClass("closedd");
            $this.addClass("openedd");
            jQuery(this).find("i").removeClass("fa-arrow-down");
            jQuery(this).find("i").addClass("fa-arrow-up");
        } else {
            $this.removeClass("openedd");
            $this.addClass("closedd");
            jQuery(this).find("i").removeClass("fa-arrow-up");
            jQuery(this).find("i").addClass("fa-arrow-down");
        }
        jQuery(this).next(".review-content").slideToggle(200);
    });

    jQuery("a.open-reply").on("click", function (event) {
        event.preventDefault();
        var $this = jQuery(this);
        if ($this.hasClass("closeddd")) {
            $this.removeClass("closeddd");
            $this.addClass("openeddd");
            jQuery(this).find("i").removeClass("fa-arrow-down");
            jQuery(this).find("i").addClass("fa-arrow-up");
        } else {
            $this.removeClass("openeddd");
            $this.addClass("closeddd");
            jQuery(this).find("i").removeClass("fa-arrow-up");
            jQuery(this).find("i").addClass("fa-arrow-down");
        }
        jQuery(this).next(".post_response").slideToggle(200);
    });

    jQuery(document).ready(function () {
        jQuery("select.hours-start2").prop("disabled", true);
        jQuery("select.hours-end2").prop("disabled", true);
        jQuery(".lp-check-doubletime .enable2ndday").change(function () {
            if (this.checked) {
                jQuery("select.hours-start2").prop("disabled", false);
                jQuery("select.hours-end2").prop("disabled", false);
                jQuery(".hours-select.lp-slot2-time").slideToggle(300);
            } else {
                jQuery("select.hours-start2").prop("disabled", true);
                jQuery("select.hours-end2").prop("disabled", true);
                jQuery(".hours-select.lp-slot2-time").slideToggle(300);
            }
        });
    });

    // Remove Hours Script

    jQuery(document).on("click", "a.remove-hours", function (event) {
        event.preventDefault();
        jQuery(this).parent(".hours").remove();
    });
    // Toggle Script for Currency area
    jQuery("a.toggle-currencey-area").on("click", function (event) {
        event.preventDefault();
        jQuery(this).next(".currency-area").slideToggle(400);
        jQuery(this).toggleClass("active");
    });
    // Magnific Popup
    jQuery(".review-img-slider").magnificPopup({
        delegate: "a",
        type: "image",
        tLoading: "Loading image #%curr%...",
        mainClass: "mfp-img-mobile",
        gallery: {
            enabled: true,
            navigateByImgClick: true,
            preload: [0, 1], // Will preload 0 - before current, and 1 after the current image
        },
        image: {
            tError: '<a href="%url%">The image #%curr%</a> could not be loaded.',
            titleSrc: function (item) {
                return item.el.attr("title") + "<small>by Listingpro team</small>";
            },
        },
    });

    jQuery(document).ready(function () {
        jQuery(".fulldayopen").change(function () {
            if (this.checked) {
                jQuery("select.hours-start").prop("disabled", true);
                jQuery("select.hours-end").prop("disabled", true);
                jQuery("select.hours-start2").prop("disabled", true);
                jQuery("select.hours-end2").prop("disabled", true);
            } else {
                jQuery("select.hours-start").prop("disabled", false);
                jQuery("select.hours-end").prop("disabled", false);
                jQuery("select.hours-start2").prop("disabled", false);
                jQuery("select.hours-end2").prop("disabled", false);
            }
        });
    });

    jQuery(document).ready(function () {
        jQuery(".add-more").click(function () {
            jQuery("#lp_feature_panel").slideToggle("slow");
        });
    });
    var hdrHeight = jQuery("header.header-normal").outerHeight();

    jQuery(".top-section .absolute").css("top", hdrHeight);

    if (jQuery("body").is(".single-listing")) {
        if (jQuery(window).width() >= 768) {
            // Listing Detail Gallery
            jQuery("a[rel^='prettyPhoto']").prettyPhoto({
                animation_speed: "fast",
                theme: "dark_rounded",
                slideshow: 7000,
                autoplay_slideshow: true,
                social_tools: "",
                deeplinking: false,
                show_title: false,
            });
        } else {
            jQuery("a[rel^='prettyPhoto']").prettyPhoto({
                animation_speed: "fast",
                theme: "dark_rounded",
                slideshow: 7000,
                autoplay_slideshow: true,
                social_tools: "",
                deeplinking: false,
                show_title: false,
            });
        }
    }

    jQuery("a.onlineform").on("click", function (event) {
        event.preventDefault();
        jQuery(this).next(".booking-form").slideToggle(400);
        jQuery(this).toggleClass("active");
    });

    jQuery(".listing-second-view .ask-question-area > a.ask_question_popup").on(
        "click",
        function (event) {
            event.preventDefault();
            jQuery(this).next(".faq-form").slideToggle(400);
        }
    );

    if (jQuery("body").is(".single-listing")) {
        var sliderstyle = jQuery("body").data("sliderstyle");

        if (sliderstyle == "style1") {
            var images = jQuery(".listing-slide").data("images-num");
            var center_mode = true;
            if (images > 5) {
                images = 5;
                center_mode = true;
            } else {
                center_mode = false;
            }
            // Listing Detail Slider
            jQuery(".listing-slide").slick({
                centerPadding: "10px",
                slidesToShow: images,
                autoplay: true,
                draggable: false,
                autoplaySpeed: 5000,
                centerMode: center_mode,
                focusOnSelect: true,
                arrows: true,
                responsive: [{
                    breakpoint: 768,
                    settings: {
                        arrows: false,
                        centerMode: false,
                        centerPadding: "0px",
                        slidesToShow: 5,
                    },
                },
                {
                    breakpoint: 480,
                    settings: {
                        arrows: true,
                        centerMode: false,
                        centerPadding: "0px",
                        slidesToShow: 1,
                    },
                },
                ],
            });
        } else if (sliderstyle == "style2") {
            var images = jQuery(".listing-slide").data("images-num");
            //alert(images);
            var center_mode = true;
            var variable = true;
            if (images > 3) {
                center_mode = false;
            } else if ((images = 3)) {
                //jQuery('.listing-slide img').css('height','auto');
                jQuery(".single-page-slider-container").addClass("three-imgs");
                variable = false;
            } else if ((images = 2)) {
                jQuery(".single-page-slider-container").addClass("new-cls");
            } else if ((images = 1)) {
                jQuery(".single-page-slider-container").addClass("one-img");
            } else {
                center_mode = false;
                variable = false;
            }

            // Listing Detail Slider
            jQuery(".listing-slide").slick({
                slidesToShow: 2,
                autoplay: true,
                draggable: false,
                autoplaySpeed: 5000,
                centerMode: true,
                focusOnSelect: true,
                variableWidth: variable,
                adaptiveHeight: true,
                responsive: [{
                    breakpoint: 768,
                    settings: {
                        arrows: true,
                        centerMode: false,
                        centerPadding: "0px",
                        //slidesToShow: 5
                    },
                },
                {
                    breakpoint: 480,
                    settings: {
                        arrows: true,
                        centerMode: false,
                        centerPadding: "0px",
                        slidesToShow: 1,
                    },
                },
                ],
            });
        } else if (sliderstyle == "style3") {
            var images = jQuery(".listing-slide").data("images-num");
            var slidestoshow = 2;
            if (images == 1) {
                jQuery(".listing-slide img").css("width", "100%");
                slidestoshow = 1;
            } else if (images == 2) {
                slidestoshow = 2;
            } else if (images == 3) {
                slidestoshow = 2;
            } else if (images == 4) {
                slidestoshow = 3;
            } else if (images == 6) {
                slidestoshow = 4;
            } else if (images == 8) {
                slidestoshow = 6;
            } else if (images == 10) {
                slidestoshow = 8;
            } else if (images >= 12) {
                slidestoshow = 10;
            }

            // Listing Detail Slider
            jQuery(".listing-slide").slick({
                slidesToShow: 2,
                autoplay: true,
                draggable: false,
                autoplaySpeed: 5000,
                centerMode: true,
                focusOnSelect: true,
                variableWidth: true,
                adaptiveHeight: true,
                responsive: [{
                    breakpoint: 9999,
                    settings: {
                        slidesToShow: slidestoshow,
                    },
                },
                {
                    breakpoint: 768,
                    settings: {
                        arrows: true,
                        centerMode: false,
                        centerPadding: "0px",
                        //slidesToShow: 5
                    },
                },
                {
                    breakpoint: 480,
                    settings: {
                        arrows: true,
                        centerMode: false,
                        centerPadding: "0px",
                        slidesToShow: 1,
                    },
                },
                ],
            });
        }
    }

    // Listing Detail Slider
    if (jQuery(".listing-slide2").length != 0) {
        jQuery(".listing-slide2").slick({
            slidesToShow: 1,
            autoplay: false,
            draggable: false,
            autoplaySpeed: 5000,
            centerMode: true,
            centerPadding: "0px",
            focusOnSelect: true,
            variableWidth: variable,
            adaptiveHeight: true,
            responsive: [{
                breakpoint: 768,
                settings: {
                    arrows: true,
                    centerMode: false,
                    centerPadding: "0px",
                    //slidesToShow: 5
                },
            },
            {
                breakpoint: 480,
                settings: {
                    arrows: false,
                    centerMode: false,
                    centerPadding: "0px",
                    slidesToShow: 1,
                },
            },
            ],
        });
    }

    jQuery(".select2").select2();

    if (jQuery("body").is(".single-listing")) {
        jQuery(".review-img-slider").slick({
            infinite: true,
            slidesToShow: 3,
            slidesToScroll: 1,
            autoplay: false,
            autoplaySpeed: 5000,
            arrows: true,
            dots: false,
            responsive: [{
                breakpoint: 790,
                settings: {
                    arrows: false,
                    centerMode: true,
                    centerPadding: "40px",
                    slidesToShow: 2,
                },
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 1,
                },
            },
            ],
        });
        /* end  by haroon */

        /* code for tab style two of single list */
        if (
            jQuery(".single-inner-container .single-tabber2 ul .lpreviews").length > 0
        ) {
            jQuery(document).on(
                "click",
                ".single-inner-container .single-tabber2 ul .lpreviews",
                function () {
                    if (jQuery(".review-img-slider").hasClass("slick-initialized")) {
                        jQuery(".review-img-slider").slick("unslick");
                        jQuery(".review-img-slider").slick({
                            infinite: true,
                            slidesToShow: 3,
                            slidesToScroll: 1,
                            autoplay: false,
                            autoplaySpeed: 5000,
                            arrows: true,
                            dots: false,
                            responsive: [{
                                breakpoint: 790,
                                settings: {
                                    arrows: false,
                                    centerMode: true,
                                    centerPadding: "40px",
                                    slidesToShow: 2,
                                },
                            },
                            {
                                breakpoint: 480,
                                settings: {
                                    slidesToShow: 1,
                                },
                            },
                            ],
                        });
                    }
                }
            );
        }

        jQuery(".post-slide").slick({
            infinite: true,
            slidesToShow: 2,
            slidesToScroll: 1,
            arrows: false,
            dots: true,
            responsive: [{
                breakpoint: 2,
                settings: {
                    arrows: false,
                    centerMode: true,
                    centerPadding: "40px",
                    slidesToShow: 3,
                },
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 1,
                },
            },
            ],
        });

        //Slick One Per Slide Testimonials
        jQuery(".testimonial-slider").slick({
            dots: true,
            infinite: true,
            autoplay: true,
            autoplaySpeed: 1000,
            speed: 1000,
            arrows: false,
            slidesToShow: 1,
        });
    }
    // Accordion
    var icons = {
        header: "fa fa-plus",
        activeHeader: "fa fa-minus",
    };
    jQuery("#accordion").accordion({
        icons: icons,
        heightStyle: "content",
    });
    jQuery("#toggle")
        .button()
        .on("click", function () {
            if (jQuery("#accordion").accordion("option", "icons")) {
                jQuery("#accordion").accordion("option", "icons", null);
            } else {
                jQuery("#accordion").accordion("option", "icons", icons);
            }
        });
    // Popup Gallery
    jQuery(".popup-youtube, .popup-vimeo, .popup-gmaps").magnificPopup({
        disableOn: 319,
        type: "iframe",
        iframe: {
            markup: '<div class="mfp-iframe-scaler">' +
                '<div class="mfp-close"></div>' +
                '<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>' +
                "</div>",
            patterns: {
                youtube: {
                    index: "youtube.com/",
                    id: "v=",
                    src: "//www.youtube.com/embed/%id%?rel=0&autoplay=1",
                },
            },
            srcAction: "iframe_src",
        },
        mainClass: "mfp-fade",
        removalDelay: 160,
        preloader: false,
        fixedContentPos: false,
    });

    jQuery(".popup-gallery").magnificPopup({
        delegate: ".image-popup",
        type: "image",
        tLoading: "Loading image #%curr%...",
        mainClass: "mfp-img-mobile",
        gallery: {
            enabled: true,
            navigateByImgClick: true,
            preload: [0, 1], // Will preload 0 - before current, and 1 after the current image
        },
    });
    //Boostrap Rating
    //http://dreyescat.github.io/bootstrap-rating/
    jQuery("input.check").on("change", function () {
        alert("Rating: " + jQuery(this).val());
    });
    if (jQuery("body").is(".single-listing")) {
        jQuery("#programmatically-set").on("click", function () {
            jQuery("#programmatically-rating").rating(
                "rate",
                jQuery("#programmatically-value").val()
            );
        });
        jQuery("#programmatically-get").on("click", function () {
            alert(jQuery("#programmatically-rating").rating("rate"));
        });

        jQuery(".rating-tooltip-manual").rating({
            extendSymbol: function () {
                var title;
                jQuery(this).tooltip({
                    container: "body",
                    placement: "bottom",
                    trigger: "manual",
                    title: function () {
                        return title;
                    },
                });
                jQuery(this)
                    .on("rating.rateenter", function (e, rate) {
                        title = rate;
                        jQuery(this).tooltip("show");
                    })
                    .on("rating.rateleave", function () {
                        jQuery(this).tooltip("hide");
                    });
            },
        });
        jQuery(".rating").each(function () {
            jQuery('<span class="label label-default"></span>')
                .text(jQuery(this).val() || " ")
                .insertAfter(this);
        });
        jQuery(".rating").on("change", function () {
            jQuery(this).next(".label").text(jQuery(this).val());
        });
    }
    // Mapbox
});
jQuery(window).on("load", function () {
    if (jQuery(this).width() < 981) {
        jQuery(".claimformtrigger").on("click", function () {
            if (jQuery(".claimform").hasClass("claimform-open")) {
                jQuery(".claimform").removeClass("claimform-open");
                jQuery(".claimform").hide();
            } else {
                jQuery(this).closest(".post-row").addClass("rowopen");
                jQuery(".claimform").addClass("claimform-open");
                jQuery(".claimform").show();
            }
        });
    }

    jQuery(window)
        .resize(function () {
            if (jQuery(this).width() < 781) {
                jQuery(".mobilemap").removeAttr("id");
                jQuery(".mobilemap").removeClass("md-modal");
                jQuery(".mobilemap").removeClass("md-effect-3");
                jQuery(".mobilelink").removeClass("md-trigger");
                jQuery(".mobile-map-space .md-overlayi").removeClass("md-overlay");
                jQuery(".listing-container-right .md-overlayi").removeClass(
                    "md-overlay"
                );
                jQuery(".mobilelink").on("click", function () {
                    if (jQuery(".mobilemap").hasClass("map-open")) {
                        jQuery(".mobilemap").removeClass("map-open");
                        jQuery(".mobilemap .mapbilemap-content").css({
                            opacity: "0",
                            "margin-top": "-520px",
                        });
                        jQuery("a.mobilelink").text("View on map");
                    } else {
                        jQuery(".mobilemap").addClass("map-open");
                        jQuery(".mobilemap .mapbilemap-content").css({
                            opacity: "1",
                            "margin-top": "0px",
                        });
                        jQuery("a.mobilelink").text("Close map");
                    }
                });
                jQuery(".quickformtrigger").on("click", function () {
                    if (jQuery(".quickform").hasClass("quickform-open")) {
                        jQuery(".quickform").removeClass("quickform-open");
                        jQuery(".quickform").slideUp(600);
                    } else {
                        jQuery(".quickform").addClass("quickform-open");
                        jQuery(".quickform").slideDown(600);
                    }
                });
            } else {
                var headertop = jQuery("header").height();
                jQuery(".section-fixed").css("padding-top", headertop + "px");
            }
        })
        .resize(); //triggcurrentColorer the event manually when the page is loaded

    jQuery(".listing-sidebar-left .form-inline").fadeTo(600, 1);
    jQuery(".post-with-map-container .form-inline").fadeTo(600, 1);
    jQuery(".spinner").css("display", "none");
    //jQuery('.single-page-slider-container').css("opacity","1");

    /*
     * L.TileLayer is used for standard xyz-numbered tile layers.
     */

    L.Google = L.Class.extend({
        includes: L.Mixin.Events,

        options: {
            minZoom: 0,
            maxZoom: 18,
            tileSize: 256,
            subdomains: "abc",
            errorTileUrl: "",
            attribution: "",
            opacity: 1,
            continuousWorld: false,
            noWrap: false,
            mapOptions: {
                backgroundColor: "#dddddd",
            },
        },

        // Possible types: SATELLITE, ROADMAP, HYBRID, TERRAIN
        initialize: function (type, options) {
            L.Util.setOptions(this, options);

            this._ready = google.maps.Map != undefined;
            if (!this._ready) L.Google.asyncWait.push(this);

            this._type = type || "SATELLITE";
        },

        onAdd: function (map, insertAtTheBottom) {
            this._map = map;
            this._insertAtTheBottom = insertAtTheBottom;

            // create a container div for tiles
            this._initContainer();
            this._initMapObject();

            // set up events
            map.on("viewreset", this._resetCallback, this);

            this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
            map.on("move", this._update, this);

            map.on("zoomanim", this._handleZoomAnim, this);

            //20px instead of 1em to avoid a slight overlap with google's attribution
            map._controlCorners["bottomright"].style.marginBottom = "20px";

            this._reset();
            this._update();
        },

        onRemove: function (map) {
            this._map._container.removeChild(this._container);
            //this._container = null;

            this._map.off("viewreset", this._resetCallback, this);

            this._map.off("move", this._update, this);

            this._map.off("zoomanim", this._handleZoomAnim, this);

            map._controlCorners["bottomright"].style.marginBottom = "0em";
            //this._map.off('moveend', this._update, this);
        },

        getAttribution: function () {
            return this.options.attribution;
        },

        setOpacity: function (opacity) {
            this.options.opacity = opacity;
            if (opacity < 1) {
                L.DomUtil.setOpacity(this._container, opacity);
            }
        },

        setElementSize: function (e, size) {
            e.style.width = size.x + "px";
            e.style.height = size.y + "px";
        },

        _initContainer: function () {
            var tilePane = this._map._container,
                first = tilePane.firstChild;

            if (!this._container) {
                this._container = L.DomUtil.create(
                    "div",
                    "leaflet-google-layer leaflet-top leaflet-left"
                );
                this._container.id = "_GMapContainer_" + L.Util.stamp(this);
                this._container.style.zIndex = "auto";
            }

            tilePane.insertBefore(this._container, first);

            this.setOpacity(this.options.opacity);
            this.setElementSize(this._container, this._map.getSize());
        },

        _initMapObject: function () {
            if (!this._ready) return;
            this._google_center = new google.maps.LatLng(0, 0);
            var map = new google.maps.Map(this._container, {
                center: this._google_center,
                zoom: 0,
                tilt: 0,
                mapTypeId: google.maps.MapTypeId[this._type],
                disableDefaultUI: false,
                keyboardShortcuts: false,
                draggable: false,
                disableDoubleClickZoom: true,
                scrollwheel: false,
                streetViewControl: true,
                styles: this.options.mapOptions.styles,
                backgroundColor: this.options.mapOptions.backgroundColor,
            });

            var _this = this;
            this._reposition = google.maps.event.addListenerOnce(
                map,
                "center_changed",
                function () {
                    _this.onReposition();
                }
            );
            this._google = map;

            google.maps.event.addListenerOnce(map, "idle", function () {
                _this._checkZoomLevels();
            });
        },

        _checkZoomLevels: function () {
            //setting the zoom level on the Google map may result in a different zoom level than the one requested
            //(it won't go beyond the level for which they have data).
            // verify and make sure the zoom levels on both Leaflet and Google maps are consistent
            if (this._google.getZoom() !== this._map.getZoom()) {
                //zoom levels are out of sync. Set the leaflet zoom level to match the google one
                this._map.setZoom(this._google.getZoom());
            }
        },

        _resetCallback: function (e) {
            this._reset(e.hard);
        },

        _reset: function (clearOldContainer) {
            this._initContainer();
        },

        _update: function (e) {
            if (!this._google) return;
            this._resize();

            var center = e && e.latlng ? e.latlng : this._map.getCenter();
            var _center = new google.maps.LatLng(center.lat, center.lng);

            this._google.setCenter(_center);
            this._google.setZoom(this._map.getZoom());

            this._checkZoomLevels();
            //this._google.fitBounds(google_bounds);
        },

        _resize: function () {
            var size = this._map.getSize();
            if (
                this._container.style.width == size.x &&
                this._container.style.height == size.y
            )
                return;
            this.setElementSize(this._container, size);
            this.onReposition();
        },

        _handleZoomAnim: function (e) {
            var center = e.center;
            var _center = new google.maps.LatLng(center.lat, center.lng);

            this._google.setCenter(_center);
            this._google.setZoom(e.zoom);
        },

        onReposition: function () {
            if (!this._google) return;
            google.maps.event.trigger(this._google, "resize");
        },
    });

    L.Google.asyncWait = [];
    L.Google.asyncInitialize = function () {
        var i;
        for (i = 0; i < L.Google.asyncWait.length; i++) {
            var o = L.Google.asyncWait[i];
            o._ready = true;
            if (o._container) {
                o._initMapObject();
                o._update();
            }
        }
        L.Google.asyncWait = [];
    };

    L.HtmlIcon = L.Icon.extend({
        options: {
            /*
                         html: (String) (required)
                         iconAnchor: (Point)
                         popupAnchor: (Point)
                         */
        },

        initialize: function (options) {
            L.Util.setOptions(this, options);
        },

        createIcon: function () {
            var div = document.createElement("div");
            div.innerHTML = this.options.html;
            if (div.classList) div.classList.add("leaflet-marker-icon");
            else div.className += " " + "leaflet-marker-icon";
            return div;
        },

        createShadow: function () {
            return null;
        },
    });

    jQuery(".all-list-map").on("click", function () {
        var defmaplat = jQuery("body").data("defaultmaplat");
        var defmaplong = jQuery("body").data("defaultmaplot");
        jQuery(".map-pop").empty();
        if (jQuery("#map-section").is(".map-container3")) {
            jQuery(".map-pop").html('<div class="mapSidebar" id="map"></div>');
        } else {
            jQuery(".map-pop").html('<div class="listingmap" id="map"></div>');
        }
        var map = null;
        $mtoken = jQuery("#page").data("mtoken");
        $mtype = jQuery("#page").data("mtype");
        $mapboxDesign = jQuery("#page").data("mstyle");

        if ($mtoken != "" && $mtype == "mapbox") {
            L.mapbox.accessToken = $mtoken;
            map = L.mapbox.map("map");
            L.tileLayer(
                "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", {
                maxZoom: 18,
                attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
                    '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                    'Imagery © <a href="http://mapbox.com">Mapbox</a>',
                id: jQuery("#page").data("mstyle"),
                accessToken: $mtoken,
            }
            ).addTo(map);

            var markers = new L.MarkerClusterGroup();
            initializeMap(markers);
            if (markers === undefined) { } else {
                map.fitBounds(markers.getBounds());
                map.scrollWheelZoom.disable();
            }
        } else {
            var map = new L.Map("map", {
                minZoom: 3,
            }).setView(new L.LatLng(defmaplat, defmaplong), 18);
            if ($mtype == "google") {
                L.tileLayer("http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}", {
                    maxZoom: 6,
                    subdomains: ["mt0", "mt1", "mt2", "mt3"],
                    noWrap: true,
                });
                var googleLayer = new L.Google("ROADMAP");
                map.addLayer(googleLayer);
            } else {
                L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(
                    map
                );
            }
            var markers = new L.MarkerClusterGroup();
            initializeMap(markers);
            if (markers === undefined) { } else {
                map.fitBounds(markers.getBounds(), {
                    padding: [50, 50],
                });
            }
        }

        function initializeMap(markers) {
            markers.clearLayers();

            jQuery(".lp-grid-box-contianer").each(function (i) {
                var LPtitle = jQuery(this).data("title");
                var LPposturl = jQuery(this).data("posturl");
                var LPlattitue = jQuery(this).data("lattitue");
                var LPlongitute = jQuery(this).data("longitute");
                var LPpostid = jQuery(this).data("postid");
                if (jQuery(".v2-map-load").length == 1) {
                    var LPaddress = jQuery(this).find(".gaddress").text();
                    var LPimageSrc = jQuery(this)
                        .find(".lp-listing-top-thumb")
                        .find("img")
                        .attr("src");
                    var LPiconSrc = jQuery(this)
                        .find(".cat-icon")
                        .find("img")
                        .attr("src");
                    if (typeof jQuery("body").data("deficon") !== "undefined") {
                        LPiconSrc = jQuery("body").data("deficon");
                    }
                } else {
                    var LPaddress = jQuery(this).find(".gaddress").text();
                    var LPimageSrc = jQuery(this)
                        .find(".lp-grid-box-thumb")
                        .find("img")
                        .attr("src");
                    var LPiconSrc = jQuery(this)
                        .find(".cat-icon")
                        .find("img")
                        .attr("src");
                    if (typeof jQuery("body").data("deficon") !== "undefined") {
                        LPiconSrc = jQuery("body").data("deficon");
                    }
                }

                if (LPlattitue != "" && LPlongitute != "") {
                    var LPimage = "";
                    if (LPimageSrc != "") {
                        LPimage = LPimageSrc;
                    }

                    var LPicon = "";
                    if (LPiconSrc != "") {
                        LPicon = LPiconSrc;
                    }
                    if (jQuery(this).find(".cat-icon i").length > 0) {
                        LPicon = jQuery(this).find(".cat-icon").html();
                    } else {
                        LPicon = "<img alt='image' src='" + LPicon + "' />";
                    }
                    var markerLocation = new L.LatLng(LPlattitue, LPlongitute); // London

                    var CustomHtmlIcon = L.HtmlIcon.extend({
                        options: {
                            html: "<div class='lpmap-icon-shape pin card" +
                                LPpostid +
                                "'><div class='lpmap-icon-contianer'>" +
                                LPicon +
                                "</div></div>",
                        },
                    });

                    if (LPimage == "undefined") {
                        LPimage = jQuery(this)
                            .find(".lp-grid-box-thumb")
                            .find("img")
                            .attr("src");
                    }

                    var customHtmlIcon = new CustomHtmlIcon();

                    var marker = new L.Marker(markerLocation, {
                        icon: customHtmlIcon,
                    })
                        .bindPopup(
                            '<div class="map-post"><div class="map-post-thumb"><a href="' +
                            LPposturl +
                            '"><img alt="image" src="' +
                            LPimage +
                            '" ></a></div><div class="map-post-des"><div class="map-post-title"><h5><a href="' +
                            LPposturl +
                            '">' +
                            LPtitle +
                            '</a></h5></div><div class="map-post-address"><p><i class="fa fa-map-marker"></i> ' +
                            LPaddress +
                            "</p></div></div></div>"
                        )
                        .addTo(map);
                    markers.addLayer(marker);
                    map.addLayer(markers);
                }
            });
        }
    });

    if (jQuery("#cpmap").is(".contactmap")) {
        jQuery("#cpmap").empty();
        var map = null;
        $mtoken = jQuery("#page").data("mtoken");
        $mtype = jQuery("#page").data("mtype");
        $siteURL = jQuery("#page").data("site-url");
        $lat = jQuery(".cp-lat").data("lat");
        $lan = jQuery(".cp-lan").data("lan");
        if ($mtoken != "" && $mtype == "mapbox") {
            L.mapbox.accessToken = $mtoken;

            $mapboxDesign = jQuery("#page").data("mstyle");
            var map = L.mapbox.map("cpmap").setView([$lat, $lan], 14);
            L.tileLayer(
                "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", {
                id: jQuery("#page").data("mstyle"),
                accessToken: jQuery("#page").data("mtoken"),
            }
            ).addTo(map);
            map.scrollWheelZoom.disable();
        } else {
            var map = new L.Map("cpmap", "").setView(new L.LatLng($lat, $lan), 16);
            if ($mtype == "google") {
                var googleLayer = new L.Google("ROADMAP");
                map.addLayer(googleLayer);
            } else {
                L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(
                    map
                );
            }

            map.scrollWheelZoom.disable();
        }

        var markers = new L.MarkerClusterGroup();
        var $pinicon = jQuery("#cpmap").data("pinicon");
        if ($pinicon === "") {
            $pinicon =
                "<div class='lpmap-icon-shape pin'><div class='lpmap-icon-contianer'><img alt='image' src='" +
                $siteURL +
                "wp-content/themes/listingpro/assets/images/pins/lp-logo.png'  /></div></div>";
        } else {
            $pinicon =
                "<div style='width:50px; height:50px; margin: -50px 0 0 -20px;'><img alt='image' src='" +
                $pinicon +
                "'  /></div>";
        }

        var markerLocation = new L.LatLng($lat, $lan); // London

        var CustomHtmlIcon = L.HtmlIcon.extend({
            options: {
                html: $pinicon,
            },
        });

        var customHtmlIcon = new CustomHtmlIcon();

        var marker = new L.Marker(markerLocation, {
            icon: customHtmlIcon,
        })
            .bindPopup("")
            .addTo(map);
        markers.addLayer(marker);
    } else if (jQuery("#map").is(".singlebigpost")) {
        jQuery(".singlebigmaptrigger").click(function () {
            $mtoken = jQuery("#page").data("mtoken");
            $siteURL = jQuery("#page").data("site-url");
            $mtype = jQuery("#page").data("mtype");
            $lat = jQuery(".singlebigmaptrigger").data("lat");
            $lan = jQuery(".singlebigmaptrigger").data("lan");
            if ($mtoken != "" && $mtype == "mapbox") {
                L.mapbox.accessToken = $mtoken;
                var map = L.mapbox.map("map").setView([$lat, $lan], 14);
                L.tileLayer(
                    "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", {
                    id: jQuery("#page").data("mstyle"),
                    accessToken: jQuery("#page").data("mtoken"),
                }
                ).addTo(map);

                var markers = new L.MarkerClusterGroup();

                var markerLocation = new L.LatLng($lat, $lan); // London

                var CustomHtmlIcon = L.HtmlIcon.extend({
                    options: {
                        html: "<div class='lpmap-icon-shape pin '><div class='lpmap-icon-contianer'><img alt='image' src='" +
                            $siteURL +
                            "wp-content/themes/listingpro/assets/images/pins/lp-logo.png'  /></div></div>",
                    },
                });

                var customHtmlIcon = new CustomHtmlIcon();

                var marker = new L.Marker(markerLocation, {
                    icon: customHtmlIcon,
                })
                    .bindPopup("")
                    .addTo(map);
                markers.addLayer(marker);
                map.fitBounds(markers.getBounds());

                map.scrollWheelZoom.disable();
                map.invalidateSize();
            } else {
                var map = new L.Map("map", {
                    center: new L.LatLng($lat, $lan),
                    zoom: 14,
                });
                if ($mtype == "google") {
                    var googleLayer = new L.Google("ROADMAP");
                    map.addLayer(googleLayer);
                } else {
                    L.tileLayer(
                        "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    ).addTo(map);
                }
                var markers = new L.MarkerClusterGroup();
                var markerLocation = new L.LatLng($lat, $lan); // London
                var CustomHtmlIcon = L.HtmlIcon.extend({
                    options: {
                        html: "<div class='lpmap-icon-shape pin '><div class='lpmap-icon-contianer'><img alt='image' src='" +
                            $siteURL +
                            "wp-content/themes/listingpro/assets/images/pins/lp-logo.png'  /></div></div>",
                    },
                });

                var customHtmlIcon = new CustomHtmlIcon();

                var marker = new L.Marker(markerLocation, {
                    icon: customHtmlIcon,
                })
                    .bindPopup("")
                    .addTo(map);
                markers.addLayer(marker);
                map.fitBounds(markers.getBounds());

                map.scrollWheelZoom.disable();
                map.invalidateSize();
            }
        });
    }
});
jQuery(document).ready(function () {
    // Autocomplete

    jQuery.widget("custom.combobox", {
        _create: function () {
            this.wrapper = jQuery("<span>")
                .addClass("custom-combobox")
                .insertAfter(this.element);

            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
        },
        _createAutocomplete: function () {
            var selected = this.element.children(":selected"),
                value = selected.val() ? selected.text() : "";

            this.input = jQuery("<input>")
                .appendTo(this.wrapper)
                .val(value)
                .attr("title", "")
                .addClass(
                    "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left lp-search-input location_input lp-home-locaton-input"
                )
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: $.proxy(this, "_source"),
                })
                .tooltip({
                    tooltipClass: "ui-state-highlight",
                });
        },

        _createShowAllButton: function () {
            var input = this.input,
                wasOpen = false;

            jQuery("<a>")
                .attr("tabIndex", -1)
                .attr("title", "Show All Items")
                .tooltip()
                .appendTo(this.wrapper)
                .button({
                    icons: {
                        primary: "ui-icon-triangle-1-s",
                    },
                    text: false,
                })
                .removeClass("ui-corner-all")
                .addClass("custom-combobox-toggle ui-corner-right")
                .mousedown(function () {
                    wasOpen = input.autocomplete("widget").is(":visible");
                })
                .on("click", function () {
                    input.focus();

                    // Close if already visible
                    if (wasOpen) {
                        return;
                    }

                    // Pass empty string as value to search for, displaying all results
                    input.autocomplete("search", "");
                });
        },

        _source: function (request, response) {
            var matcher = new RegExp(
                $.ui.autocomplete.escapeRegex(request.term),
                "i"
            );
            response(
                this.element.children("option").map(function () {
                    var text = jQuery(this).text();
                    if (this.value && (!request.term || matcher.test(text)))
                        return {
                            label: text,
                            value: text,
                            option: this,
                        };
                })
            );
        },

        _removeIfInvalid: function (event, ui) {
            // Selected an item, nothing to do
            if (ui.item) {
                return;
            }

            // Search for a match (case-insensitive)
            var value = this.input.val(),
                valueLowerCase = value.toLowerCase(),
                valid = false;
            this.element.children("option").each(function () {
                if (jQuery(this).text().toLowerCase() === valueLowerCase) {
                    this.selected = valid = true;
                    return false;
                }
            });

            // Found a match, nothing to do
            if (valid) {
                return;
            }

            // Remove invalid value
            this.input
                .val("")
                .attr("title", value + " didn't match any item")
                .tooltip("open");
            this.element.val("");
            this._delay(function () {
                this.input.tooltip("close").attr("title", "");
            }, 2500);
            this.input.autocomplete("instance").term = "";
        },

        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        },
    });

    jQuery(".comboboxs").combobox();
    jQuery("#toggle").on("click", function () {
        jQuery(".comboboxs").toggle();
    });
    // jQuery( "#searchcategory" ).combobox();
    jQuery("#toggle").on("click", function () {
        jQuery("#searchcategory").toggle();
    });
    jQuery(".ui-autocomplete").autocomplete({
        appendTo: ".input-group",
    });
    jQuery(".custom-combobox-input").autocomplete({
        minLength: 0,
    });
    jQuery(".custom-combobox-input").on("click", function () {
        jQuery(this).autocomplete("search", "");
    });

    // Location Placeholder
    jQuery(".location_input").attr("placeholder", "Your Location");
    jQuery(".comboboxCategory .location_input").attr("placeholder", "Food");
    jQuery(".postSubmitCat .location_input").attr(
        "placeholder",
        "Chose one or more than one categories"
    );

    jQuery(document).on("click", ".md-close", function () {
        jQuery(".md-modal").modal("hide");
        jQuery(".md-modal").removeClass("md-show");
        jQuery(".modal-backdrop").remove();
    });

    // Popup Data
    jQuery(document).on("click", ".qickpopup", function () {
        // variables
        jQuery(".content-loading").removeAttr("style");
        var LPtitle = jQuery(this).closest(".lp-grid-box-contianer").data("title");
        var LPlattitue = jQuery(this)
            .closest(".lp-grid-box-contianer")
            .data("lattitue");
        var LPlongitute = jQuery(this)
            .closest(".lp-grid-box-contianer")
            .data("longitute");
        var LPpostID = jQuery(this)
            .closest(".lp-grid-box-contianer")
            .data("postid");
        var feaImg = jQuery(this).closest(".lp-grid-box-contianer").data("feaimg");
        var mapPin = jQuery(this).data("mappin");
        jQuery("#listing-preview-popup .md-close").hide();
        var docHeight = jQuery(document).height();
        jQuery("#listing-preview-popup .popup-inner-left-padding")
            .html("")
            .css("min-hegiht", "300px");
        if (jQuery("#listing-preview-popup").is(".md-show")) { } else {
            jQuery("#listing-preview-popup").modal({
                show: "true",
            });
            if (jQuery(this).closest(".classic-view-grid-saved-options").length > 0) {
                jQuery("#listing-preview-popup").addClass("lp-classic-preview-modal");
            }
            jQuery("#listing-preview-popup").addClass("md-show");
        }
        jQuery.ajax({
            url: ajax_search_term_object.ajaxurl,
            dataType: "json",
            data: {
                action: "quick_preivew_cb",
                LPpostID: LPpostID,
                lpNonce: jQuery("#lpNonce").val(),
            },
            success: function (data) {
                jQuery("#listing-preview-popup .md-close")
                    .show()
                    .children("i")
                    .css("right", "20px");
                jQuery("#listing-preview-popup .popup-inner-left-padding").html(data);
                var mapinSrc = "";

                mapinSrc = jQuery(data).find("span.cat-icon").find("img").attr("src");
                if (mapinSrc != "") {
                    mapPin = mapinSrc;
                }
                if (jQuery(data).find(".cat-icon i").length > 0) {
                    mapPin = jQuery(data).find(".cat-icon").html();
                } else {
                    mapPin = "<img alt='image' src='" + mapPin + "' />";
                }

                var markers = false;
                $mtoken = jQuery("#page").data("mtoken");
                $siteURL = jQuery("#page").data("site-url");
                $lat = LPlattitue;
                $lan = LPlongitute;
                $mapboxDesign = jQuery("#page").data("mstyle");
                $mtype = jQuery("#page").data("mtype");
                if ($mtoken != "" && $mtype == "mapbox") {
                    L.mapbox.accessToken = $mtoken;
                    map = L.mapbox.map("quickmap" + LPpostID);
                    L.tileLayer(
                        "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", {
                        id: jQuery("#page").data("mstyle"),
                        accessToken: jQuery("#page").data("mtoken"),
                    }
                    ).addTo(map);
                } else {
                    var map = new L.Map("quickmap" + LPpostID, {
                        center: new L.LatLng($lat, $lan),
                        zoom: 14,
                    });
                    if ($mtype == "google") {
                        var googleLayer = new L.Google("ROADMAP");
                        map.addLayer(googleLayer);
                    } else {
                        L.tileLayer(
                            "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                        ).addTo(map);
                    }
                }
                map.setView([$lat, $lan], 14);
                markers = new L.MarkerClusterGroup();
                var markerLocation = new L.LatLng($lat, $lan); // London
                var CustomHtmlIcon = L.HtmlIcon.extend({
                    options: {
                        html: '<div class="lpmap-icon-shape pin"><div class="lpmap-icon-contianer">' +
                            mapPin +
                            "</div></div>",
                    },
                });
                var customHtmlIcon = new CustomHtmlIcon();
                var marker = new L.Marker(markerLocation, {
                    icon: customHtmlIcon,
                })
                    .bindPopup("")
                    .addTo(map);
                markers.addLayer(marker);
                //alert(data.cats_markup);
                jQuery(".content-loading").css("background-image", "none");
            },
            error: function (errorThrown) {
                alert(errorThrown);
            },
        });
    });

    //href Smooth Scroll

    // handle links with @href started with '#' only
    jQuery('.post-meta-right-box a.secondary-btn[href^="#"]').on(
        "click",
        function (e) {
            e.preventDefault();

            var target = this.hash;
            var $target = jQuery(target);

            jQuery("html, body")
                .stop()
                .animate({
                    scrollTop: $target.offset().top,
                },
                    900,
                    "swing",
                    function () {
                        window.location.hash = target;
                    }
                );
        }
    );
    //Tags Container
    jQuery(".chosen-select2").chosen({
        disable_search: true,
    });
    jQuery(".chosen-select1").chosen({
        disable_search: true,
    });
    jQuery(".chosen-select7").chosen({
        disable_search: true,
    });
    jQuery(".chosen-select5").chosen({
        disable_search: true,
    });
    // jQuery( ".chosen-select.chosen-select5" ).select2({minimumResultsForSearch: -1});

    var $tags = jQuery("#searchtags").chosen(),
        LPnewTags = function () {
            jQuery(".LPtagsContainer").empty();
            $tags.find(":selected").each(function (i, obj) {
                jQuery(
                    '<div class="active-tag">' +
                    obj.value +
                    '<div class="remove-tag"><i class="fa fa-times"></i></div></div>'
                )
                    .appendTo(".LPtagsContainer")
                    .on("click", function () {
                        jQuery(this).remove();
                        jQuery(obj).attr("selected", false);
                        $tags.trigger("chosen:updated");
                        jQuery(
                            '.LPtagsContainer input[value="' + obj.value + '"]'
                        ).remove();
                    });

                jQuery(
                    '<input type="hidden" name="select_tag" value="' + obj.value + '" />'
                ).appendTo(".LPtagsContainer");
            });
        };

    $tags.on("change", LPnewTags);

    /* Social Share */
    var social = jQuery(".post-stat li ul.social-icons.post-socials");
    var socialOvrly = jQuery(".reviews.sbutton .md-overlay");

    jQuery(".sbutton a.reviews-quantity").on("click", function (event) {
        event.preventDefault();
        social.fadeIn(400);

        if (socialOvrly.hasClass("hide")) {
            jQuery(socialOvrly).removeClass("hide");
            jQuery(socialOvrly).addClass("show");
        } else {
            jQuery(socialOvrly).removeClass("show");
            jQuery(socialOvrly).addClass("hide");
        }
    });

    socialOvrly.on("click", function (event) {
        event.preventDefault();
        social.fadeOut(400);

        if (socialOvrly.hasClass("show")) {
            jQuery(socialOvrly).removeClass("show");
            jQuery(socialOvrly).addClass("hide");
        } else {
            jQuery(socialOvrly).removeClass("hide");
            jQuery(socialOvrly).addClass("show");
        }
    });

    // Reserwa Popup
    jQuery("a.make-reservation").on("click", function (event) {
        event.preventDefault();
        jQuery(".ifram-reservation").fadeIn(400);
    });
    jQuery("a.close-btn").on("click", function (event) {
        event.preventDefault();
        jQuery(".ifram-reservation").fadeOut(400);
    });

    //Menu Popup
    if (jQuery(window).width() > 767) {
        //Menu Popup
        jQuery(".widget-box a.open-modal, .menu-hotel a.open-modal").on(
            "click",
            function (event) {
                event.preventDefault();
                jQuery(".hotel-menu").fadeIn(400);
            }
        );
        jQuery("a.close-menu-popup").on("click", function (event) {
            event.preventDefault();
            jQuery(".hotel-menu").fadeOut(400);
        });
    } else if (jQuery(window).width() < 767) {
        //Menu Popup
        jQuery(".widget-box a.open-modal, .menu-hotel a.open-modal").on(
            "click",
            function (event) {
                event.preventDefault();
                jQuery(".hotel-menu").slideToggle(400);
            }
        );

        jQuery(".listing-app-view .hotel-menu a.close-menu-popup").on(
            "click",
            function (event) {
                event.preventDefault();
                jQuery(".hotel-menu").slideToggle(400);
            }
        );
    }

    // Resurva Booking Switcher
    jQuery("a.switch-fields").on("click", function (event) {
        event.preventDefault();
        jQuery(this).toggleClass("active");
        jQuery(".hidden-items").fadeToggle(400);
    });

    // Dashboard Notices
    jQuery("a.dismiss").on("click", function (event) {
        event.preventDefault();
        jQuery(this).parent(".panel-dash-dismiss").slideUp(400);
    });

    /* Pins Hover */

    jQuery(document).on("mouseenter", ".lp-grid-box-contianer", function () {
        var cardID = jQuery(this).data("postid");
        var cardclass = ".lpmap-icon-shape.card" + cardID;
        if (jQuery(cardclass).hasClass("cardHighlight")) {
            jQuery(cardclass).removeClass("cardHighlight");
        } else {
            jQuery(cardclass).addClass("cardHighlight");
        }
    });
    jQuery(document).on("mouseleave", ".lp-grid-box-contianer", function () {
        var cardID = jQuery(this).data("postid");
        var cardclass = ".lpmap-icon-shape.card" + cardID;
        jQuery(cardclass).removeClass("cardHighlight");
    });

    /* Select Category */
    jQuery(".postsubmitSelect").on("change", function () {
        jQuery(".feature-fields-error-container").remove();
        jQuery(".featuresDataRow").show();
        var cvalue = jQuery(this).val();
        jQuery(".featuresData").css({
            opacity: "0",
            visibility: "hidden",
            display: "none",
        });
        jQuery(".featuresDataContainer")
            .find(".featuresData" + cvalue)
            .css({
                opacity: "1",
                visibility: "visible",
                display: "block",
            });
    });
});
jQuery(document).on("change", ".btn-file :file", function () {
    var input = jQuery(this),
        numFiles = input.get(0).files ? input.get(0).files.length : 1,
        label = input.val().replace(/\\/g, "/").replace(/.*\//, "");
    input.trigger("fileselect", [numFiles, label]);
});

jQuery(document).ready(function () {
    if (jQuery("form").is("#lp-submit-formdf")) {
        var validator = new FormValidator(
            "lp-submit-form",
            [{
                name: "postTitle",
                display: "Title",
                rules: "required",
            },
            {
                name: "category",
                display: "Category",
                rules: "required",
            },
            {
                name: "postContent",
                display: "Description",
                rules: "required",
            },
            {
                name: "location",
                display: "Location",
                rules: "required",
            },
            {
                name: "gAddress",
                display: "Google Address",
                rules: "required",
            },
            {
                name: "email",
                rules: "valid_email",
            },
            {
                name: "username",
                display: "UserName",
                rules: "required",
            },
            {
                name: "policycheck",
                display: "Terms and Conditions Check",
                rules: "required",
            },
            ],
            function (errors, evt) {
                var SELECTOR_ERRORS = jQuery(".error_box"),
                    SELECTOR_SUCCESS = jQuery(".success_box");

                if (errors.length > 0) {
                    SELECTOR_ERRORS.empty();

                    for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
                        SELECTOR_ERRORS.append(errors[i].message + "<br />");
                    }

                    SELECTOR_SUCCESS.css({
                        display: "none",
                    });
                    SELECTOR_ERRORS.fadeIn(200);
                } else {
                    SELECTOR_ERRORS.css({
                        display: "none",
                    });
                    SELECTOR_SUCCESS.fadeIn(200);
                }
            }
        );
    }
});
var image_custom_uploader;
var $thisItem = "";

jQuery(document).on("click", ".upload-author-image", function (e) {
    e.preventDefault();

    $thisItem = jQuery(this);
    $form = jQuery("#profileupdate");

    //If the uploader object has already been created, reopen the dialog
    if (image_custom_uploader) {
        image_custom_uploader.open();
        return;
    }

    //Extend the wp.media object
    image_custom_uploader = wp.media.frames.file_frame = wp.media({
        title: "Choose Image",
        button: {
            text: "Choose Image",
        },
        library: {
            type: "image", // Restrict to images only
        },
        multiple: false,
    });

    image_custom_uploader.on("open", function () {
        var filterable = image_custom_uploader.state().get("library");
        filterable.props.set("type", "image");
    });

    //When a file is selected, grab the URL and set it as the text field's value
    image_custom_uploader.on("select", function () {
        attachment = image_custom_uploader
            .state()
            .get("selection")
            .first()
            .toJSON();
        var url = "";
        url = attachment["url"];
        var attachId = "";
        attachId = attachment["id"];

        jQuery("img.author-avatar").attr({
            src: url,
        });
        $form.parent().parent().find(".criteria-image-url").attr({
            value: url,
        });
        $form.parent().parent().find(".criteria-image-id").attr({
            value: attachId,
        });
    });

    //Open the uploader dialog
    image_custom_uploader.open();
});

/* update by zaheer on 25 feb  */
jQuery(document).ready(function ($) {
    jQuery("#listings_checkout input[name=listing_id]").on("change", function () {
        jQuery("#listings_checkout input[name=post_id]").val(
            jQuery(this, "#listings_checkout").val()
        );
    });
    jQuery("#listings_checkout input[name=plan]").on("change", function () {
        jQuery("#listings_checkout input[name=method]").val(
            jQuery(this, "#listings_checkout").val()
        );
    });

    jQuery(".lp-promotebtn").on("click", function () {
        var $this = jQuery(this);
        jQuery("#ads_promotion input[name=listing_id]").val(
            $this.data("listingnid")
        );
        var listtitle = $this.data("listingtitle");
        jQuery("input[name=cur_listing_title]").val(listtitle);
    });
    jQuery("#ads_promotion input[name=plan]").on("change", function () {
        jQuery("#ads_promotion input[name=method]").val(
            jQuery(this, "#listings_checkout").val()
        );
    });
});
/* by zaheer on 25 feb */
jQuery(".availableprice_options input").change(function ($) {
    var $total,
        taxrate = "",
        taxprice,
        taxTotal;
    if (jQuery("span").hasClass("pricetax")) {
        taxrate = jQuery("span.pricetax").data("taxprice");
    }
    $oldtotal = jQuery("#totalprice").val();
    oldTax = jQuery('input[name="taxprice"]').val();
    if (jQuery(this).is(":checked")) {
        var $val = jQuery(this).val();
        $total = parseFloat($val) + parseFloat($oldtotal);
        taxprice = parseFloat((taxrate / 100) * $val);
        taxTotal = parseFloat(oldTax) + parseFloat(taxprice);
        $total = $total + taxprice;
        $total = $total.toFixed(2);
        taxTotal = taxTotal.toFixed(2);
        jQuery("#totalprice").val($total);
        jQuery(".pricetotal #price").html($total);
        jQuery('input[name="lp_total_price"]').val($total);
        jQuery('input[name="taxprice"]').val(taxTotal);
    } else {
        var $val = jQuery(this).val();
        $total = parseFloat($oldtotal) - parseFloat($val);
        taxprice = parseFloat((taxrate / 100) * $val);
        taxTotal = parseFloat(oldTax) - parseFloat(taxprice);
        $total = $total - taxprice;
        $total = $total.toFixed(2);
        taxTotal = taxTotal.toFixed(2);
        if ($total > 0) {
            jQuery("#totalprice").val($total);
            jQuery(".pricetotal #price").html($total);
            jQuery('input[name="lp_total_price"]').val($total);
            jQuery('input[name="taxprice"]').val(taxTotal);
        } else {
            $total = 0.0;
            jQuery("#totalprice").val($total);
            jQuery(".pricetotal #price").html($total);
            jQuery('input[name="lp_total_price"]').val($total);
            jQuery('input[name="taxprice"]').val(taxTotal);
        }
    }
});

/* update by zaheer on 25 feb  */
jQuery(".lp-front").on("click", ".lp-frontBtn", function (e) {
    e.preventDefault();
    //jQuery('.lp-front').hide(200);
    jQuery(".lp-front").slideUp(500);
    jQuery(".lp-back1").slideDown(1000);
    //jQuery('.lp-back').show(500);
});
jQuery(".lp-back1").on("click", "#lp-back1", function (e) {
    e.preventDefault();
    jQuery(".lp-back1").slideUp(500);
    jQuery(".lp-front").slideDown(1000);
});
jQuery(".lp-back1").on("click", "#lp-next", function (e) {
    e.preventDefault();
    jQuery(".lp-back1").slideUp(500);
    jQuery(".lp-back2").slideDown(1000);
});
jQuery(".lp-back2").on("click", "#lp-back2", function (e) {
    e.preventDefault();
    jQuery(".lp-back2").slideUp(500);
    jQuery(".lp-back1").slideDown(1000);
});
/* end update by zaheer on 25 feb  */

//dynamic model for invoices by zaheer
jQuery(document).ready(function ($) {
    jQuery(".invoice-section a.showme").click(function (ev) {
        var $this = jQuery(this);
        $this.after('<i class="lp-modal-spinn fa-li fa fa-spinner fa-spin"></i>');
        ev.preventDefault();
        var rowid = jQuery(this).data("id");
        reqlink = jQuery(this).data("url");
        var invoiceFor = "";
        invoiceFor = jQuery(this).data("lpinvoice");
        //invoiceFor = 'dddf';

        jQuery.get(
            reqlink + "?lp_p_id=" + rowid + "&lp_invoice=" + invoiceFor,
            function (html) {
                jQuery("#modal-invoice .modal-body").html("");
                jQuery("#modal-invoice .modal-body").html(html);
                jQuery("#modal-invoice").modal("show", {
                    backdrop: "static",
                });
                $this.next(".lp-modal-spinn").hide("");
                $this.next(".lp-modal-spinn").remove("");
            }
        );
    });
});

/* print preview */
jQuery(function ($) {
    "use strict";
    jQuery("#modal-invoice")
        .find(".lp-print-list")
        .on("click", function () {
            //jQuery.print("#modal-invoice");
            /* jQuery("#modal-invoice").print({
                     noPrintSelector : ".modal-footer",
                     }); */

            var divToPrint = document.getElementById("modal-invoice");

            var newWin = window.open("", "Print-Window");

            newWin.document.open();

            newWin.document.write(
                '<html><body onload="window.print()">' +
                divToPrint.innerHTML +
                "</body></html>"
            );

            newWin.document.close();

            setTimeout(function () {
                newWin.close();
            }, 10);
        });
});

jQuery(document).ready(function ($) {
    jQuery(".googleAddressbtn").on("click", function (e) {
        var dtype = jQuery(this).data("type");
        if (dtype == "gaddress") {
            if (jQuery(this).hasClass("events-dash")) {
                jQuery(".events-map-wrap #inputAddresss").slideUp(300);
                jQuery(".lp-custom-lat").slideUp(300);
                jQuery(".events-map-wrap #inputAddress").slideDown();
                jQuery(".events-map-wrap .googlefulladdress").slideDown(300);
                jQuery(".events-map-wrap #latitude").attr("type", "hidden");
                jQuery(".events-map-wrap #longitude").attr("type", "hidden");
                jQuery(this).next(".googleAddressbtn").removeClass("active");
                jQuery(this).addClass("active");
            } else {
                jQuery(".post-submit #inputAddresss").slideUp(300);
                jQuery(".lp-custom-lat").slideUp(300);
                jQuery(".post-submit #inputAddress").slideDown();
                jQuery(".post-submit .googlefulladdress").slideDown(300);
                jQuery(".post-submit #latitude").attr("type", "hidden");
                jQuery(".post-submit #longitude").attr("type", "hidden");
                jQuery(this).next(".googleAddressbtn").removeClass("active");
                jQuery(this).addClass("active");
            }
        } else {
            if (jQuery(this).hasClass("events-dash")) {
                jQuery(".events-map-wrap #inputAddress").slideUp();
                jQuery(".events-map-wrap .googlefulladdress").slideUp(300);
                jQuery(".events-map-wrap #inputAddresss").slideDown(300);
                jQuery(".lp-custom-lat").slideDown(300);
                jQuery(".events-map-wrap #latitude").attr("type", "text");
                jQuery(".events-map-wrap #longitude").attr("type", "text");
                jQuery(this).prev(".googleAddressbtn").removeClass("active");
                jQuery(this).addClass("active");
            } else {
                jQuery(".post-submit #inputAddress").slideUp();
                jQuery(".post-submit .googlefulladdress").slideUp(300);
                jQuery(".post-submit #inputAddresss").slideDown(300);
                jQuery(".lp-custom-lat").slideDown(300);
                jQuery(".post-submit #latitude").attr("type", "text");
                jQuery(".post-submit #longitude").attr("type", "text");
                jQuery(this).prev(".googleAddressbtn").removeClass("active");
                jQuery(this).addClass("active");
            }
        }
        e.preventDefault();
    });
});

/* ======27 may mm=========== */
jQuery(document).ready(function ($) {
    jQuery("#slide-nav.navbar-inverse").after(
        jQuery('<div class="inverse" id="navbar-height-col"></div>')
    );
    jQuery("#slide-nav.navbar-default").after(
        jQuery('<div id="navbar-height-col"></div>')
    );
    var toggler = ".navbar-toggle";
    var pagewrapper = "#page-content";
    var navigationwrapper = ".navbar-header";
    var menuwidth = "100%";
    var slidewidth = "80%";
    var menuneg = "-100%";
    var slideneg = "-80%";
    jQuery("#slide-nav").on("click", toggler, function (e) {
        var selected = $(this).hasClass("slide-active");
        jQuery("#slidemenu")
            .stop()
            .animate({
                left: selected ? menuneg : "0px",
            });
        jQuery("#navbar-height-col")
            .stop()
            .animate({
                left: selected ? slideneg : "0px",
            });
        jQuery(pagewrapper)
            .stop()
            .animate({
                left: selected ? "0px" : slidewidth,
            });
        jQuery(navigationwrapper)
            .stop()
            .animate({
                left: selected ? "0px" : slidewidth,
            });
        jQuery(this).toggleClass("slide-active", !selected);
        jQuery("#slidemenu").toggleClass("slide-active");
        jQuery("#page-content, .navbar, body, .navbar-header").toggleClass(
            "slide-active"
        );
    });
    var selected = "#slidemenu, #page-content, body, .navbar, .navbar-header";
    jQuery(window).on("resize", function () {
        if (jQuery(window).width() > 767 && $(".navbar-toggle").is(":hidden")) {
            jQuery(selected).removeClass("slide-active");
        }
    });

    jQuery(".lp_price_trigger_checkout input").on("click", function ($) {
        var taxEnable = jQuery(this).data("taxenable");
        plantitle = jQuery(this).data("title");
        planprice = jQuery(this).data("planprice");
        taxprice = "";
        totalprice = "";
        if (taxEnable == "1") {
            taxrate = jQuery(".lp_price_trigger_checkout input").data("taxrate");
            taxprice = (taxrate / 100) * planprice;
            taxprice = taxprice.toFixed(2);
            jQuery('input[name="listings_tax_price"]').attr("value", taxprice);
            totalprice = parseFloat(planprice) + parseFloat(taxprice);
            totalprice = totalprice.toFixed(2);
            jQuery("span#lp_price_plan").text(plantitle);
            jQuery("span#lp_price_plan_price").text(planprice);
            jQuery("span#lp_tax_price").text(taxprice);
            jQuery("span#lp_price_subtotal").text(totalprice);
            jQuery("input#lp_paypal_price").val(totalprice);
            jQuery(".lp_section_inner .lp_billing_total").show(400);
        } else {
            totalprice = parseFloat(planprice);
            jQuery("span#lp_price_plan").text(plantitle);
            jQuery("span#lp_price_plan_price").text(planprice);
            jQuery("span#lp_price_subtotal").text(totalprice);
            jQuery("input#lp_paypal_price").val(totalprice);
        }
    });

    if (jQuery("form#register .check_policy").is(".termpolicy")) {
        jQuery("input#lp_usr_reg_btn").prop("disabled", true);
        jQuery(".check_policy").on("click", function () {
            if (jQuery("#check_policy").is(":checked")) {
                jQuery("input#lp_usr_reg_btn").prop("disabled", false);
            } else {
                jQuery("input#lp_usr_reg_btn").prop("disabled", true);
            }
        });
    }

    if (jQuery(".blue-section .check_policy").is(".termpolicy")) {
        jQuery("#listingsubmitBTN").prop("disabled", true);
        jQuery("#listingsubmitBTN").addClass("dissablebutton");
        jQuery(".check_policy").on("click", function () {
            if (jQuery("#policycheck").is(":checked")) {
                jQuery("#listingsubmitBTN").prop("disabled", false);
                jQuery("#listingsubmitBTN").removeClass("dissablebutton");
            } else {
                jQuery("#listingsubmitBTN").prop("disabled", true);
                jQuery("#listingsubmitBTN").addClass("dissablebutton");
            }
        });
    }
    if (jQuery(".white-section .check_policy").is(".termpolicy")) {
        jQuery("#listingsubmitBTN").prop("disabled", true);
        jQuery("#listingsubmitBTN").addClass("dissablebutton");
        jQuery(".check_policy").on("click", function () {
            if (jQuery("#policycheck").is(":checked")) {
                jQuery("#listingsubmitBTN").prop("disabled", false);
                jQuery("#listingsubmitBTN").removeClass("dissablebutton");
            } else {
                jQuery("#listingsubmitBTN").prop("disabled", true);
                jQuery("#listingsubmitBTN").addClass("dissablebutton");
            }
        });
    }
});

jQuery(window).ready(function () {
    if (jQuery(".header-container").hasClass(".lp-vedio-bg")) {
        jQuery("#lp_vedio").play();
    }
    if (jQuery("input").is(".rating-tooltip")) {
        jQuery(".rating-tooltip").rating({
            extendSymbol: function (rate) {
                jQuery(this).tooltip({
                    container: "body",
                    placement: "bottom",
                    title: "Rate " + rate,
                });
            },
        });
    }
});

jQuery(document).ready(function ($) {
    if (jQuery(".lp-home-banner-contianer").is(".lp-home-banner-with-loc")) {
        var locType = jQuery(".lp_auto_loc_container h1,p.lp-app-view2-des").data(
            "locnmethod"
        );

        var currentlocationswitch = "1";
        var currentlocationswitch = jQuery("#page").data("lpcurrentloconhome");
        if (currentlocationswitch == "0") {
            locType = "locationifoff";
        }

        var apiType = jQuery("#page").data("ipapi");

        if (locType == "withip") {
            if (apiType === "ip_api") {
                jQuery.get(
                    "https://ipapi.co/json",
                    function (location) {
                        var locc = location.city;
                        if (locc == null) { } else {
                            jQuery(".lp-dyn-city").text(location.city);
                        }
                    },
                    "json"
                );
            } else {
                lpGetGpsLocName(function (lpgetcurrentcityvalue) {
                    lpgpsclocation = lpgetcurrentcityvalue;
                    jQuery(".lp-dyn-city").text(lpgpsclocation);
                });
            }
        }
    }

    if (jQuery(".lp-header-search-tagline").length != 0) {
        var locType = jQuery(
            ".lp_auto_loc_container .lp-header-search-tagline"
        ).data("locnmethod");
        var currentlocationswitch = "1";
        var currentlocationswitch = jQuery("#page").data("lpcurrentloconhome");
        if (currentlocationswitch == "0") {
            locType = "locationifoff";
        }

        var apiType = jQuery("#page").data("ipapi");

        if (locType == "withip") {
            if (apiType === "ip_api") {
                jQuery.get(
                    "https://ipapi.co/json",
                    function (location) {
                        var locc = location.city;
                        if (locc == null) { } else {
                            jQuery(".lp-dyn-city").text(location.city);
                        }
                    },
                    "json"
                );
            } else {
                lpGetGpsLocName(function (lpgetcurrentcityvalue) {
                    lpgpsclocation = lpgetcurrentcityvalue;
                    jQuery(".lp-dyn-city").text(lpgpsclocation);
                });
            }
        }
    }

    // lp-header-search-tagline
});

function hexToRGB(hexStr) {
    var col = {};
    col.r = parseInt(hexStr.substr(1, 2), 16);
    col.g = parseInt(hexStr.substr(3, 2), 16);
    col.b = parseInt(hexStr.substr(5, 2), 16);
    return col;
}

/* for recurring stripe */
jQuery(document).ready(function () {
    var plantype = "";
    var recurringtext = "";
    var recurringhtml = "";
    var $thislisting = "";
    var $thisplan = "";
    var $recurringon = "";
    $recurringon = jQuery("form#listings_checkout").data("recurring");
    if ($recurringon === "yes") {
        jQuery("#listings_checkout input[type=radio]").on("change", function ($) {
            if (
                jQuery("#listings_checkout input[name=listing_id]").is(":checked") &&
                jQuery("#listings_checkout input[name=plan]").is(":checked")
            ) {
                $thislisting = jQuery(
                    "#listings_checkout input[name=listing_id]:checked"
                );
                $thisplan = jQuery("#listings_checkout input[name=plan]:checked").val();
                plantype = $thislisting.closest(".lp-user-listings").data("plantype");
                if (plantype === "Pay Per Listing") {
                    recurringtext = $thislisting
                        .closest(".lp-user-listings")
                        .data("recurringtext");
                    recurringhtml =
                        '<div class="checkbox"><input type="checkbox" id="listing-recurring-recurrsive" name="lp-recurring-option" value="yes"><label for="listing-recurring-recurrsive">' +
                        recurringtext +
                        "</label></div>";
                    if ($thisplan === "stripe") {
                        jQuery("div.lp-recurring-button-wrap").html(recurringhtml);
                    } else {
                        jQuery("div.lp-recurring-button-wrap").html("");
                    }
                } else {
                    jQuery("div.lp-recurring-button-wrap").html("");
                }
            } else {
                jQuery("div.lp-recurring-button-wrap").html("");
            }
        });
    }

    /* for dynamic location */
    if (jQuery("input#cities").length) {
        jQuery("input#cities").cityAutocomplete();
    }
    if (jQuery("input#citiess").length) {
        jQuery("input#citiess").cityAutocomplete();
    }

    if (jQuery("input#cities").length) {
        jQuery(document).on("click", "#cities", function (e) {
            jQuery("input#cities").cityAutocomplete();
        });
    }
    if (jQuery("input#citiess").length) {
        jQuery(document).on("click", "#citiess", function (e) {
            jQuery("input#citiess").cityAutocomplete();
        });
    }

    jQuery(document).on("click", "#citiess", function (e) {
        var target = e.target;
        if (!jQuery(target).is(".help")) {
            if (jQuery("input#citiess").length) {
                var isseleted = jQuery("input#citiess").data("isseleted");
                if (isseleted == false) {
                    jQuery("input#citiess").val("");
                }
            }
        }
    });

    if (jQuery("input#citiess").length) {
        jQuery("#citiess").on("input", function () {
            jQuery(this).data("isseleted", false);
        });
    }
});
/* for recurring stripe */
jQuery(document).ready(function ($) {
    jQuery("#select-plan-form .select-plan-form input[name=plans-posts]").on(
        "click",
        function () {
            jQuery("a.lp_change_plan_action").hide("");
            jQuery("div.lp-action-div form").hide("");
        }
    );
});

/* for range slider */
var nearmeunit = jQuery("#lp-find-near-me").data("nearmeunit");
if (jQuery("#distance_range").length != 0) {
    jQuery("#distance_range").bootstrapSlider({
        formatter: function (value) {
            return value + " " + nearmeunit;
        },
        tooltip: "always",
    });
}

/* for show click on div radius */
jQuery("li.lp-tooltip-outer").on("click", function () {
    var $this = jQuery(this);
    jQuery(".lp-tooltip-div").removeClass("active");
    $this.find(".lp-tooltip-div").addClass("active");
});

/* for hide div on outer click to divs */
jQuery(document).mouseup(function (e) {
    var container = jQuery(".lp-tooltip-div");
    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) {
        jQuery(".lp-tooltip-div").removeClass("active");
    }

    var containerr = jQuery(".lp-tooltip-div-hidden");
    if (!containerr.is(e.target) && containerr.has(e.target).length === 0) {
        jQuery(".lp-tooltip-div-hidden").removeClass("active");
    }

    var foodmenucontainer = jQuery(".hotel-menu .inner-menu");
    if (
        !foodmenucontainer.is(e.target) &&
        foodmenucontainer.has(e.target).length === 0
    ) {
        jQuery(".hotel-menu").fadeOut();
    }
});

jQuery("li.lp-tooltip-outer").hover(function () {
    var $this = jQuery(this);
    jQuery(".lp-tooltip-div").removeClass("active");
    jQuery(".lp-tooltip-div-hidden").removeClass("active");
    $this.find(".lp-tooltip-div").addClass("active");
    if ($this.find("a.near-me-btn, a.near-me-btn-style-3").hasClass("active")) {
        jQuery(".lp-tooltip-div-hidden").addClass("active");
    }
});

/* for first tab auto active on listing detail page style 2 */
jQuery(document).ready(function ($) {
    jQuery(".lp-detail-page-template-3 #reply-title2 ul li")
        .first()
        .addClass("active");
    jQuery(".lp-detail-page-template-3 .detail-page2-tab-content .tab-pane")
        .first()
        .addClass("active");

    /* app view search dumm loader */
    jQuery(document).on(
        "click",
        ".listing-app-view .app-view-filters .close",
        function () {
            var docHeight = jQuery(document).height();
            jQuery("body").prepend('<div id="full-overlay"></div>');
            jQuery("#full-overlay").css("height", docHeight + "px");
            jQuery("#full-overlay").addClass("content-loading");
            var timer = "";

            function lpcloseloadnow() {
                jQuery("#full-overlay").remove();
                jQuery("#full-overlay").removeClass("content-loading");
                clearTimeout(timer);
            }

            timer = setTimeout(lpcloseloadnow, 2000);
            if (jQuery("div.promoted-listings div.app-view-new-ads-slider").length) {
                jQuery("div.app-view-new-ads-slider").slick({
                    arrows: false,
                });
            }
            if (jQuery("div.promoted-listings div.app-view-new-ads-slider").length) {
                jQuery("div.app-view-new-ads-slider").slick({
                    arrows: false,
                });
            }
        }
    );

    /* multiselect for google location  */
    jQuery(document).on("click", ".city-autocomplete .help", function () {
        var $thisSelected = jQuery(this).text();
        var $thisSelecteds = $thisSelected.split(",");
        if (
            $thisSelecteds[1] == "undefined" ||
            $thisSelecteds[1] == "" ||
            $thisSelecteds[1] == null
        ) {
            $thisSelected = $thisSelecteds[0];
        } else {
            $thisSelected = $thisSelecteds[0] + "," + $thisSelecteds[1];
        }
        var $selectLocationData =
            '<div class="lpsinglelocselected ' +
            $thisSelected +
            '">' +
            $thisSelected +
            '<i class="fa fa-times lp-removethisloc"></i><input type="hidden" name="location[]" value="' +
            $thisSelected +
            '"></div>';
        jQuery($selectLocationData).appendTo(".lp-selected-locs");

        if (jQuery("div").hasClass("lp-selected-locs")) {
            jQuery("input#citiess").val("");
        }
    });

    jQuery(document).on("click", ".lp-removethisloc", function () {
        jQuery(this).closest(".lpsinglelocselected").remove();
    });

    jQuery(".top-search-form .lp-search-btn-header .lp-search-btn").on(
        "click",
        function () {
            var locvals = $.trim($("input#cities").val());
            if (locvals.length > 0) { } else {
                jQuery('input[name="lp_s_loc"]').val("");
            }
        }
    );

    /* when google location and user don't select the suggestions and hit enters */
    jQuery("input#cities").on("change", function () {
        jQuery("input[name=lp_s_loc]").val(jQuery(this).val());
    });

    jQuery(document).on("click", ".city-autocomplete .help", function () {
        //New update 2.7.0
        substrr = $(this).text();
        substrr = substrr.split(",");
        if (substrr[1] == "undefined" || substrr[1] == "" || substrr[1] == null) {
            substrr = substrr[0];
        } else {
            substrr = substrr[0] + "," + substrr[1];
        }
        //End New update 2.7.0
        jQuery("input[name=lp_s_loc]").val(substrr);
    });

    /* overlay close on cross click */
    jQuery(".md-close.widget-map-click").on("click", function (e) {
        jQuery("#full-overlay").css("height", "0px");
    });
});

function lpshowsidemap() {
    if (jQuery("#map").is(".mapSidebar")) {
        if (jQuery(".v2-map-load").length == 1) {
            jQuery("<div class='v2mapwrap'></div>").appendTo(jQuery(".v2-map-load"));
            jQuery(".v2-map-load .v2mapwrap").trigger("click");
        }
        jQuery("<div class='sidemarpInside'></div>").appendTo(
            jQuery(".sidemap-fixed")
        );
        jQuery(".sidemap-fixed .sidemarpInside").trigger("click");
    }
}

if (window.attachEvent) {
    window.attachEvent("onload", lpshowsidemap);
} else if (window.addEventListener) {
    window.addEventListener("load", lpshowsidemap, false);
} else {
    document.addEventListener("load", lpshowsidemap, false);
}

/* for 1.2.7 */
jQuery(document).ready(function ($) {
    if (jQuery("form#registertmp .check_policyy").is(".termpolicy")) {
        jQuery("input#lp-template-registerbtn").prop("disabled", true);
        jQuery(".check_policyy").on("click", function () {
            if (jQuery("#check_policyy").is(":checked")) {
                jQuery("input#lp-template-registerbtn").prop("disabled", false);
            } else {
                jQuery("input#lp-template-registerbtn").prop("disabled", true);
            }
        });
    }

    jQuery(".lp-qoute-butn a#freeQuoteForm").click(function (e) {
        e.preventDefault();
        jQuery("html, body").animate({
            scrollTop: jQuery("#freeQuoteFormWrap").offset().top,
        },
            1000
        );
    });
    jQuery(".contact-right #contactMSGForm").submit(function (e) {
        var uname = jQuery(this).find("input[name=uname]").val();
        var uemail = jQuery(this).find("input[name=uemail]").val();
        var umessage = jQuery(this).find("textarea[name=umessage]").val();

        if (uname == "" || uname == null) {
            jQuery(this).find("input[name=uname]").addClass("lp-required-field");
            e.preventDefault();
        }

        if (uemail == "" || uemail == null) {
            jQuery(this).find("input[name=uemail]").addClass("lp-required-field");
            e.preventDefault();
        }

        if (lpisValidEmailAddress(uemail)) { } else {
            jQuery(this).find("input[name=uemail]").addClass("lp-required-field");
            e.preventDefault();
        }

        if (umessage == "" || umessage == null) {
            jQuery(this)
                .find("textarea[name=umessage]")
                .addClass("lp-required-field");
            e.preventDefault();
        }
    });

    jQuery("input#lp-featuredimage").change(function () {
        lp_change_curerntImgUrl(this);
    });

    /* end preview image*/

    jQuery(
        ".app-view-header .lp-search-toggle .user-menu i, .app-view-popup-style, .event-by-going-wrap .app-view-popup-style"
    ).click(function () {
        jQuery("#app-view-login-popup").fadeIn(function () {
            jQuery("#app-view-login-popup").css({
                top: "20%",
                transform: "translateY(0%)",
                //'opacity': 1,
                overflow: "visible",
            });
        });
    });
    jQuery(".style2-popup-login .md-close").click(function (e) {
        jQuery("#app-view-login-popup").fadeOut(function () {
            jQuery("#app-view-login-popup").css({
                //'opacity': 1,
                display: "none",
            });
        });
    });
});

/* preview image on listing edit change url of current image */

function lp_change_curerntImgUrl(input) {
    if (input.files && input.files[0]) {
        jQuery(".submit_new_style-outer .lp-listing-featuredimage label").css({
            "max-width": "189px",
        });
        var reader = new FileReader();

        reader.onload = function (e) {
            jQuery(".lpchangeinstantimg").attr("src", e.target.result);
            jQuery(".lpchangeinstantimg").css({
                width: "63px",
                height: "63px",
            });
        };

        reader.readAsDataURL(input.files[0]);
    }
}

jQuery(window).scroll(function () {
    //if you hard code, then use console
    //.log to determine when you want the
    //nav bar to stick.

    if (jQuery(window).scrollTop() > 790) {
        jQuery(".profile-sticky-bar").addClass("navbar-fixed");
        jQuery(".profile-sticky-bar").fadeIn(500);
    }
    if (jQuery(window).scrollTop() < 790) {
        jQuery(".profile-sticky-bar").removeClass("navbar-fixed");
        jQuery(".profile-sticky-bar").fadeOut(500);
    }
});
jQuery(document).on("click", ".stickynavbar ul li a", function (e) {
    e.preventDefault();
    var targetID = jQuery(this).attr("href");
    jQuery("html,body").animate({
        scrollTop: jQuery(targetID).offset().top - 125,
    },
        500
    );
});

/* for email address */
function lpisValidEmailAddress(emailAddress) {
    var pattern = new RegExp(
        /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
    );
    return pattern.test(emailAddress);
}

/* for 1.2.15 */
jQuery(document).ready(function () {
    jQuery("#lp_delete_accountpopup input.lp_assign_data").on(
        "click",
        function () {
            jQuery(".lp_delte_user_confirm").removeAttr("disabled");
        }
    );

    jQuery(".lp_privacy_policy_Wrap input.lpprivacycheckboxopt").on(
        "click",
        function () {
            if (jQuery(this).closest("#claimform").hasClass("lp-form-planclaim-st")) {
                var claimuserlogin = false,
                    ppolicy = false;
                if (jQuery("body").hasClass("logged-in")) {
                    claimuserlogin = true;
                }
                if (jQuery("#claimform .lpprivacycheckboxopt").length > 0) {
                    ppolicy = true;
                }
                claimformvalidation(claimuserlogin, ppolicy);
            } else {
                if (jQuery(this).is(":checked")) {
                    jQuery(this)
                        .closest("form")
                        .find("input[type=submit]")
                        .removeAttr("disabled");
                } else {
                    jQuery(this)
                        .closest("form")
                        .find("input[type=submit]")
                        .attr("disabled", "disabled");
                }
            }
        }
    );
});
/* end for 1.2.15 */

/* for version 2.0 */

jQuery(document).ready(function () {
    /* for claim submit checkout form  */
    jQuery("#claim_payment_checkout").on("submit", function (e) {
        var $this = jQuery(this);
        claimerID = $this.find("input[name=claimerID]").val();
        claimPost = $this.find("input[name=claimPost]").val();
        claimPrice = $this.find("input[name=claimPrice]").val();
        currency = $this.find("input[name=currency]").val();
        claimPrice = parseFloat(claimPrice) * 100;
        claimPrice = parseFloat(claimPrice).toFixed();
        handler.open({
            name: "For Claim",
            description: "",
            zipCode: true,
            amount: claimPrice,
            currency: currency,
        });
        e.preventDefault();
    });
});

/* FOR ADDITIONAL FILTER */
/*-------------------------------------------------------------------------------------------------*/

// More Filter Tooltip

jQuery(document).ready(function () {
    jQuery(".lp_add_more_filter a").on("mouseover", function () {
        jQuery(".lp_more_filter_tooltip_outer").css("visibility", "visible");
    });

    jQuery(".lp_add_more_filter a").on("mouseout", function () {
        jQuery(".lp_more_filter_tooltip_outer").css("visibility", "hidden");
    });
});

// More Filter Button click and over lay on map

jQuery(document).ready(function () {
    jQuery(".lp_add_more_filter a").click(function (e) {
        e.preventDefault();
        e.stopPropagation();

        jQuery(".outer_all_page_overflow").toggleClass("hide-filters");
        jQuery(".outer_all_page_overflow").css("display", "block");
        // Map over lay display block
        if (jQuery(".overlay_on_map_for_filter").is(":hidden")) {
            jQuery(".overlay_on_map_for_filter").css("display", "block");
        } else {
            jQuery(".overlay_on_map_for_filter").css("display", "none");
        }
    });

    jQuery(".outer_all_page_overflow").click(function (e) {
        //e.stopPropagation();
    });

    // Hide on click out side div
    jQuery("body").click(function () {
        //jQuery('.outer_all_page_overflow').hide();
        // Map over lay display none
        jQuery(".overlay_on_map_for_filter").css("display", "none");
    });

    jQuery("#filter_cancel_all").on("click", function () {
        jQuery(".outer_all_page_overflow").slideUp();
        jQuery(".overlay_on_map_for_filter").css("display", "none");
        // Map overlay display none
    });
});

jQuery(document).on("click", "#filter_cancel_all", function () {
    jQuery(".outer_all_page_overflow").slideUp();
    jQuery(".overlay_on_map_for_filter").css("display", "none");
    jQuery(".outer_all_page_overflow").hide(500);
    // Map overlay display none
});

/* **************************For payment checkout script******************************* */

jQuery(document).ready(function () {
    jQuery("#listings_checkout_form input[name=listing_id]").click(function () {
        if (
            jQuery("#listings_checkout_form input[name=listing_id]").is(":checked")
        ) {
            if (jQuery("#listings_checkout_form input[name=plan]").is(":checked")) {
                //both are checked
                jQuery(".lp_payment_step_next.firstStep").addClass("active");
                lp_make_checkout_step_active("firstStep");
                jQuery(".lp_payment_step_next.firstStep").prop("disabled", false);
            } else {
                jQuery(".lp-checkout-steps .firstStep").removeClass("current");
                jQuery(".lp_payment_step_next.firstStep").removeClass("active");
                jQuery(".lp_payment_step_next.firstStep").prop("disabled", true);
            }
        }
    });

    jQuery("#listings_checkout_form input[name=plan]").click(function () {
        if (jQuery("#listings_checkout_form input[name=plan]").is(":checked")) {
            jQuery("input[name=method]").val(jQuery(this).val());
            if (
                jQuery("#listings_checkout_form input[name=listing_id]").is(":checked")
            ) {
                //both are checked
                jQuery(".lp_payment_step_next.firstStep").addClass("active");
                lp_make_checkout_step_active("firstStep");
                jQuery(".lp_payment_step_next.firstStep").prop("disabled", false);
            } else {
                jQuery(".lp-checkout-steps .firstStep").removeClass("current");
                jQuery(".lp_payment_step_next.firstStep").removeClass("active");
                jQuery(".lp_payment_step_next.firstStep").prop("disabled", true);
            }
        }
    });

    // add class for change border and background color lisitng section.
    jQuery(".lp-user-listings .radio-danger").click(function () {
        $this = jQuery(this);
        jQuery(".lp-user-listings").removeClass("active-checkout-listing");
        $this.closest(".lp-user-listings").addClass("active-checkout-listing");
    });

    /* first step */
    jQuery(document).on("click", "button.firstStep", function () {
        if (jQuery(".inactive-payment-mode").length) {
            jQuery(".inactive-payment-mode").hide();
        }
        jQuery("#listings_checkout_form input[name=listing_id]")
            .not(":checked")
            .closest(".lp-user-listings")
            .css("display", "none");
        jQuery("#listings_checkout_form input[name=plan]")
            .not(":checked")
            .closest(".lp-method-wrap")
            .css("display", "none");
        lp_show_mini_subtotal();
        //update values in hidden fields
        lp_reset_mincart_checkout_form_data();
        //display block selected lisiting details.
        lp_show_recurring_switch();
        // display terms and conditions
        jQuery(".lp-new-term-style").css("display", "block");
        jQuery("button.lp_payment_step_next.secondStep").css("display", "block");
        jQuery(this).addClass("secondStep");
        jQuery(this).removeClass("firstStep");
        if (jQuery(".terms-checkbox-container input[type=checkbox]").length) {
            jQuery(".lp_payment_step_next.secondStep").prop("disabled", true);
        } else {
            lp_make_checkout_step_active("secondStep");
        }
    });

    /* checkbox of terms and conditions */
    jQuery(".terms-checkbox-container input[type=checkbox]").on(
        "click",
        function () {
            if (jQuery(this).is(":checked")) {
                jQuery(".lp_payment_step_next.secondStep").prop("disabled", false);
                lp_make_checkout_step_active("secondStep");
                var urloftermcond = jQuery(".lpcheckouttac").attr("href");
                //window.open(urloftermcond, '_blank');
            } else {
                jQuery(".lp_payment_step_next.secondStep").prop("disabled", true);
                lp_make_checkout_step_passive("secondStep");
            }
        }
    );
    /* second step */
    jQuery(document).on(
        "click",
        "button.lp_payment_step_next.secondStep",
        function () {
            jQuery(".lp-checkout-steps .firstStep").addClass("completed");
            jQuery("button.lp_payment_step_next.thirdStep").css("display", "block");
            jQuery(this).addClass("thirdStep");
            jQuery(this).removeClass("secondStep");
            $planprice = jQuery("input[name=plan_price]").val();

            if (jQuery('input[name="lp-recurring-option"]').is(":checked")) {
                jQuery(this).prop("type", "submit");
            } else {
                if (parseFloat($planprice) == 0) {
                    /* price zero or 100% discount */
                    $listings_id = jQuery("input[name=listings_id]").val();
                    lp_make_this_listing_publish_withdiscount($listings_id);
                } else {
                    jQuery(this).prop("type", "submit");
                }
            }
        }
    );

    /* third step */
    jQuery(document).on(
        "click",
        "button.lp_payment_step_next.thirdStep",
        function () {
            jQuery(".lp-checkout-steps .secondStep").addClass("completed");
        }
    );

    // script on click to open print section print specific div
    jQuery("#print-section-receipt").click(function () {
        var printContents = document.getElementById("printarea").innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
        location.reload();
    });

    /* script for coupon switch on checkout page*/
    jQuery("input[name=lp_checkbox_coupon]").on("click", function () {
        jQuery(this).toggleClass("active");
        if (jQuery(this).hasClass("active")) {
            lp_make_couponsfields_active();
        } else {
            lp_make_couponsfields_passive();
            /* reset the minicart and checkout form data */
            lp_reset_mincart_checkout_form_data();
            jQuery("li.checkout_discount_val").remove();
        }
    });

    /* script for notification div */
    var $currHeight = jQuery(window).height();
    var $currDivHeight = jQuery(".lp_notification_wrapper").height();
    $currHeight = $currHeight - $currDivHeight;
    var $currHeight = $currHeight + "px";
    jQuery(".lp_notification_wrapper").css({
        top: $currHeight,
    });

    /* script for on resize */
    jQuery(window).resize(function () {
        var $currHeight = jQuery(window).height();
        var $currDivHeight = jQuery(".lp_notification_wrapper").height();
        $currHeight = $currHeight - $currDivHeight;
        var $currHeight = $currHeight + "px";
        jQuery(".lp_notification_wrapper").css({
            top: $currHeight,
        });
    });
    /* cancel notice */

    /* new dashborad menu */
    jQuery("#menu-toggle").click(function (e) {
        e.preventDefault();
        if (jQuery(window).width() > 767) {
            jQuery("#wrapper").toggleClass("active");
        }
    });

    jQuery("p#reply-title").on("click", function (event) {
        event.preventDefault();
        var thiss = jQuery(this);
        if (thiss.hasClass("active")) {
            jQuery(this).removeClass("active");
            jQuery(this).next("#lp-ad-click-inner").slideUp();
            jQuery(this).next("#lp-ad-click-innerm").slideUp();
        } else {
            jQuery(this).addClass("active");
            jQuery(this).next("#lp-ad-click-inner").slideDown();
            jQuery(this).next("#lp-ad-click-innerm").slideDown();
        }

        //jQuery(this).next('#rewies_form').toggleClass('open_review_form');
    });
    var TargetHeight = jQuery(".lp-inbox-outer").height();
    //jQuery('.user-recent-listings-inner .padding-0:last').height(TargetHeight+'px');
    jQuery(".user-recent-listings-inner .padding-0:first").height(
        TargetHeight + "px"
    );
    var TargetHeight = jQuery(".lp-left-panel-height").height(),
        TargetHeight = TargetHeight + 100;

    /* for header search new*/
    jQuery("#click-search-view").on("click", function () {
        $this = jQuery(this);
        jQuery(".lp-search-section-header-view").toggleClass(
            "active-section-header-view"
        );
        if (!$this.hasClass("alreadyInIt")) {
            $this.addClass("alreadyInIt");
            setTimeout(function () {
                jQuery("input#cities").cityAutocomplete();
            }, 3500);
        }
    });

    /* see more and see less activiey on user dashboard */
    jQuery("button.lp_see_more_activities").on("click", function () {
        $this = jQuery(this);
        $thisval = $this.text();
        $thisReplace = $this.data("replacetext");
        $this.toggleClass("active");
        jQuery("div.lp_hid_this_activity").slideToggle();
        $this.text($thisReplace);
        $this.data("replacetext", $thisval);
    });

    /* invoices preview */
    var foldSettings = {
        easing: "linear",
        duration: 1000,
        size: 5,
        horizFirst: false,
        /* complete: function () {
                 $(this).toggleClass("active");
                 } */
    };
    jQuery("a.lp_preview_this_invoice, .lp_right_preview_this_invoice").on(
        "click",
        function (e) {
            var $this = jQuery(this);
            $inoviceno = $this
                .closest(".lp-listing-outer-container")
                .data("inoviceno");
            $date = $this.closest(".lp-listing-outer-container").data("date");
            $amount = $this.closest(".lp-listing-outer-container").data("amount");
            $amountOnly = $this
                .closest(".lp-listing-outer-container")
                .data("orprice");
            $tax = $this.closest(".lp-listing-outer-container").data("tax");
            $method = $this.closest(".lp-listing-outer-container").data("method");
            $plan = $this.closest(".lp-listing-outer-container").data("plan");
            $duration = $this.closest(".lp-listing-outer-container").data("duration");
            $status = $this.closest(".lp-listing-outer-container").data("status");
            $listTitle = $this
                .closest(".lp-listing-outer-container")
                .data("listtitle");
            $fullAmount = $amount;
            if ($this.hasClass("lp_preview_this_invoice")) {
                jQuery("div.lp_popup_preview_invoice .lppopinvoice").text($inoviceno);
                jQuery("div.lp_popup_preview_invoice .lppopdate").text($date);
                jQuery("div.lp_popup_preview_invoice .lppopsubamount").text($amount);
                jQuery("div.lp_popup_preview_invoice .lppopamount").text($amount);
                jQuery("div.lp_popup_preview_invoice .lppoptaxprice").text($tax);
                jQuery("div.lp_popup_preview_invoice .lppopplanprice").text(
                    $amountOnly
                );
                jQuery("div.lp_popup_preview_invoice .lppoplist").text($listTitle);

                jQuery("#lpinvoiceforpdf .lppopinvoice").text($inoviceno);
                jQuery("#lpinvoiceforpdf .lppopdate").text($date);
                jQuery("#lpinvoiceforpdf .lppopamount").text($amount);
                jQuery("#lpinvoiceforpdf .lllistname").text($listTitle);

                jQuery("#lpinvoiceforpdf .lppopamountqqq").text($tax);
                jQuery("#lpinvoiceforpdf .lppopamountwww").text($fullAmount);

                if ($method == "wire") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcwire");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "stripe") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcstripe");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "paypal") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcpaypal");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "paystack") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcpaystack");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "razorpay") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcrazorpay");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "payfast") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcpayfast");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "payu") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcpayu");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "eway") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srceway");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "mollie") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcmollie");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "mercadopago") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcmercadopago");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "stripe_ideal") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcstripeideal");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "flutterwave") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcflutterwave");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                } else if ($method == "mtn_momo") {
                    $imgSrc = jQuery("p.lp-pay-with img").data("srcmtn_momo");
                    jQuery("p.lp-pay-with img").attr("src", $imgSrc);
                }
                jQuery("div.lp_popup_preview_invoice .lppopmethod").text($method);
                jQuery("div.lp_popup_preview_invoice .lppopplan").text($plan);
                jQuery("div.lp_popup_preview_invoice .lppopduration").text($duration);

                jQuery("#lpinvoiceforpdf .lppopmethod").text($method);
                jQuery("#lpinvoiceforpdf .lppopplan").text($plan);
                jQuery("#lpinvoiceforpdf .lppopduration").text($duration);

                jQuery("div.lp_popup_preview_invoice").toggle("fold", foldSettings);
                $this
                    .closest(".lp-listing-outer-container")
                    .find(".lp_right_preview_this_invoice input")
                    .prop("checked", true);
                e.preventDefault();
            }
            if (
                $this.hasClass("lp_right_preview_this_invoice") ||
                $this.hasClass("lp_preview_this_invoice")
            ) {
                jQuery("div.lp_right_preview_invoice .lppopinvoice").text($inoviceno);
                jQuery("div.lp_right_preview_invoice .lppopdate").text($date);
                jQuery("div.lp_right_preview_invoice .lppopamount").text($amount);
                jQuery("div.lp_right_preview_invoice .lppopplanprice").text(
                    $amountOnly
                );
                jQuery("div.lp_right_preview_invoice .lppoptaxprice").text($tax);
                jQuery("div.lp_right_preview_invoice .lppopmethod").text($method);
                jQuery("div.lp_right_preview_invoice .lppopplan").text($plan);
                jQuery("div.lp_right_preview_invoice .lppopduration").text($duration);
                jQuery("div.lp_right_preview_invoice .lppopstatus").text($status);

                jQuery("#lpinvoiceforpdf .lppopinvoice").text($inoviceno);
                jQuery("#lpinvoiceforpdf .lppopdate").text($date);
                jQuery("#lpinvoiceforpdf .lppopamount").text($amountOnly);

                jQuery("#lpinvoiceforpdf .lppopmethod").text($method);
                jQuery("#lpinvoiceforpdf .lppopplan").text($plan);
                jQuery("#lpinvoiceforpdf .lppopduration").text($duration);
            }

            //e.preventDefault();
        }
    );

    /* close invoices preview */
    jQuery(document).on("click", ".close_invoice_prev", function (e) {
        $this = jQuery(this);
        jQuery("div.lp_popup_preview_invoice").toggle("fold", foldSettings);
        e.preventDefault();
    });

    jQuery("button.lp-cancle-btn").on("click", function (e) {
        e.preventDefault();
        jQuery(".lp-ad-step-two").fadeOut(function () {
            jQuery(".lp_camp_invoice_wrp").fadeIn();
        });
    });

    /* show preview of currnt ad place */
    jQuery('input[name="lpadsoftype[]"]').on("click", function () {
        $this = jQuery(this);
        adsduration_pd = "";
        lp_make_campaign_paybutton_active();
        $newprice = 0;
        $campType = lp_get_camp_type();
        if ($campType == "adsperduration") {
            lp_set_camp_duration_price_in_preview(
                jQuery("input[name=adsduration_pd]").val()
            );
        } else if ($campType == "adsperclick") {
            lp_set_camp_budget_price_in_preview(
                jQuery("input[name=adsprice_pc]").val()
            );
        }

        if ($this.is(":checked")) {
            if ($this.val() == "lp_random_ads") {
                jQuery(
                    ".lp-invoices-all-stats li.spotlight span i.fa-check-circle"
                ).removeClass("lp-gray-this-ccircle");
                jQuery(".lpcampain-spotlight .greencheck").removeClass("graycheck");
            }
            if ($this.val() == "lp_top_in_search_page_ads") {
                jQuery(
                    ".lp-invoices-all-stats li.searchpage span i.fa-check-circle"
                ).removeClass("lp-gray-this-ccircle");
                jQuery(".lpcampain-topsearch .greencheck").removeClass("graycheck");
            }
            if ($this.val() == "lp_detail_page_ads") {
                jQuery(
                    ".lp-invoices-all-stats li.detailpage span i.fa-check-circle"
                ).removeClass("lp-gray-this-ccircle");
                jQuery(".lpcampain-sidebar .greencheck").removeClass("graycheck");
            }
        } else {
            if ($this.val() == "lp_random_ads") {
                jQuery(
                    ".lp-invoices-all-stats li.spotlight span i.fa-check-circle"
                ).addClass("lp-gray-this-ccircle");
                jQuery(".lpcampain-spotlight .greencheck").addClass("graycheck");
            }
            if ($this.val() == "lp_top_in_search_page_ads") {
                jQuery(
                    ".lp-invoices-all-stats li.searchpage span i.fa-check-circle"
                ).addClass("lp-gray-this-ccircle");
                jQuery(".lpcampain-topsearch .greencheck").addClass("graycheck");
            }
            if ($this.val() == "lp_detail_page_ads") {
                jQuery(
                    ".lp-invoices-all-stats li.detailpage span i.fa-check-circle"
                ).addClass("lp-gray-this-ccircle");
                jQuery(".lpcampain-sidebar .greencheck").addClass("graycheck");
            }
        }
    });

    /* on type in days */
    jQuery(document).on("input", "input[name=adsduration_pd]", function () {
        jQuery(this).val(
            jQuery(this)
                .val()
                .replace(/[^\d].+/, "")
        );
        $thisval = jQuery(this).val();
        lp_set_camp_duration_price_in_preview($thisval);
        lp_make_campaign_paybutton_active();
    });

    jQuery(document).on("click", ".lp-view-all-btn", function () {
        location.reload();
    });

    /* exit preview */
    jQuery("button.lp-exist-preview").on("click", function () {
        jQuery(".lp_campaign_preview").hide(300);
        jQuery(".lp_selected_active_ad").hide(300);
        jQuery(".lp_campaign_invoice_pmethod").show(300);
    });

    /* click on pay now btn */
    jQuery("button.lp_campaign_paynow").on("click", function () {
        //jQuery(this).attr('type', 'submit');
        jQuery(".lp_campaign_preview").hide(300);
        //jQuery('.lp_selected_active_ad').show(300);
        jQuery(".lp_campaign_invoice_pmethod").show(300);
        jQuery(this).addClass("startpayforcampaignsss");
    });

    /* campaign popup code ends */

    /* on type on ads price input */
    jQuery("input[name=adsprice_pc]").keyup(function () {
        $thisval = jQuery(this).val();
        lp_set_camp_budget_price_in_preview($thisval);
        lp_make_campaign_paybutton_active();
    });

    jQuery("input[name=adsduration_pd]").keyup(function () {
        lp_make_campaign_paybutton_active();
    });

    jQuery(".lp-search-listing-camp").on("change", function () {
        lp_make_campaign_paybutton_active();
    });

    jQuery(".lpadspreview").on("click", function () {
        packeg = "";
        jQuery(".lploading").fadeIn();
        clicks = jQuery(this).attr("data-clicks");
        mode = jQuery(this).attr("data-mode");
        budget = jQuery(this).attr("data-budget");
        credit = jQuery(this).attr("data-credit");
        duration = jQuery(this).attr("data-duration");
        method = jQuery(this).attr("data-method");
        currency = jQuery(this).attr("data-currency");
        transid = jQuery(this).attr("data-transid");
        packeg = jQuery(this).attr("data-packeg0");
        packeg1 = jQuery(this).attr("data-packeg1");
        if (packeg1) {
            packeg += packeg1;
        }
        packeg2 = jQuery(this).attr("data-packeg2");
        if (packeg2) {
            packeg += packeg2;
        }
        if (mode == "perclick") {
            jQuery("#lp-ad-click-inner").show();
            jQuery(".adsremaining").html(credit);
            jQuery("#lp-ad-click-inner")
                .find(".lp-total-clicks-inner")
                .find("h4")
                .text(clicks);

            taxPrice = jQuery(this).attr("data-taxPrice");
            budgetwithTax = jQuery(this).attr("data-budgetwithTax");
            jQuery(".lp-ad-payment-tax-price").html(taxPrice).show();
            jQuery(".lp-ad-payment-with-tax").html(budgetwithTax).show();
        } else {
            jQuery(".lp-ad-payment-tax-price").hide();
            jQuery(".lp-ad-payment-with-tax").hide();
            jQuery("#lp-ad-click-inner").hide();
            jQuery(".adsremaining").html(duration);
        }

        jQuery(".lp-ad-all-attached-packages").html(packeg);
        jQuery(".lp-ad-payment-price").html(budget);
        jQuery(".lp-ad-payment-method").html(method);
        jQuery(".adstransid").html(transid);

        jQuery(".lploading").fadeOut();
    });
});

jQuery(document).ready(function () {
    jQuery(".lp-claim-plan-btn").click(function () {
        $sPlanID = jQuery("input[name=plan_id]:checked").val();
        if (
            typeof $sPlanID !== "undefined" &&
            typeof $sPlanID !== undefined &&
            $sPlanID !== ""
        ) {
            jQuery("input[name=lp_claimed_plan]").val($sPlanID);
            jQuery(".lp-claim-plan-container").addClass("active");
            jQuery(".lp-claim-plans").addClass("active");
        }
    });
});

jQuery(document).ready(function () {
    jQuery(".lp-confi-bottom-bar").click(function () {
        jQuery(".lp_confirmation").slideToggle(700);
        jQuery(".unhidebar-section").slideToggle(700);
    });

    jQuery(".unhidebar-section").click(function () {
        jQuery(".lp_confirmation").slideToggle(700);
        jQuery(".unhidebar-section").slideToggle(700);
    });
    // dashboard search bar click to show
    jQuery(".lp-filter-search-listing").click(function () {
        jQuery(".lp-dash-search-stats-inner").slideToggle(400);
    });
});

// remove class dashboard menu width less then 768
jQuery(window).resize(function () {
    if (jQuery(window).width() < 768) {
        jQuery(".lp-dashboard-new").removeClass("active");
    }
});
/* aq on 31-7 */

/*----------------lead form customizer---*/
jQuery(document).ready(function () {
    /*-------Lead form success area remove------*/
    jQuery(".lp-cross-suces-layout").click(function () {
        jQuery(".lp-lead-success-msg-outer").fadeOut("700");
    });

    //lead form label color change on radio checked and unchecked
    jQuery(".lp-lead-radio-container input[type=radio]").click(function () {
        jQuery(".lp-lead-radio-container input[type=radio]:not(:checked)")
            .parent()
            .removeClass("active-radio");
        jQuery(".lp-lead-radio-container input[type=radio]:checked")
            .parent()
            .addClass("active-radio");
    });
    //lead form label color change on checkbox checked and unchecked
    jQuery(".lp-lead-check-container input[type=checkbox]").click(function () {
        jQuery(".lp-lead-check-container input[type=checkbox]:not(:checked)")
            .parent()
            .removeClass("active-checkbox");
        jQuery(".lp-lead-check-container input[type=checkbox]:checked")
            .parent()
            .addClass("active-checkbox");
    });
    // range slide color fill on move
    jQuery('input[type="range"].lp-range-slide').change(function () {
        var val =
            (jQuery(this).val() - jQuery(this).attr("min")) /
            (jQuery(this).attr("max") - jQuery(this).attr("min"));
        jQuery(this).css(
            "background-image",
            "-webkit-gradient(linear, left top, right top, " +
            "color-stop(" +
            val +
            ", #b3c0ce), " +
            "color-stop(" +
            val +
            ", #eef2f4)" +
            ")"
        );
    });
    // time picker
    if (jQuery(".datetimepicker1").length != 0) {
        var timeFormat = "LT";
        if (jQuery("#wp-timeformat").val() == "H:i") {
            timeFormat = "HH:mm";
        }

        jQuery(".datetimepicker1").datetimepicker({
            format: timeFormat,
        });
    }

    // calender picker
    if (jQuery(".datetimepicker2").length != 0) {
        jQuery(".datetimepicker2").datetimepicker({
            format: "L",
        });
    }

    // calender and time picker
    if (jQuery(".datetimepicker3").length != 0) {
        jQuery(".datetimepicker3").datetimepicker();
    }
});
/* on 4auguest by z */
jQuery(document).ready(function () {
    jQuery("#listings_checkout_form").on("submit", function (e) {
        var $this = jQuery(this);
        var method = $this.find('input[name="plan"]:checked').val();
        if (method === "paypal") {
            if (
                jQuery('input[name="lp-recurring-option"]:checked').length > 0 &&
                jQuery('input[name="plan_time"]').val() == ""
            ) {
                alert("Sorry! A plan should have a duration for recurring payment");
                return false;
            }
        }
    });

    /* for checkout stripe and 2checkout */
    jQuery("#listings_checkout_form").on("submit", function (e) {
        var $this = jQuery(this);

        method = $this.find('input[name="plan"]:checked').val();
        listing_id = $this.find('input[name="listing_id"]:checked').val();
        post_title = $this.find('input[name="listing_id"]:checked').data("title");
        errormsg = jQuery('input[name="errormsg"]').val();
        plan_price = jQuery("span.lp-subtotal-total-price").data("subtotal");
        currency = jQuery("input[name=currency]").val();
        if (method === "stripe") {
            if (
                jQuery('input[name="lp-recurring-option"]:checked').length > 0 &&
                jQuery('input[name="plan_time"]').val() == ""
            ) {
                alert("Sorry! A plan should have a duration for recurring payment");
                return false;
            } else {
                if (jQuery("#lp_stripe_sca").length == 0) {
                    plan_price = plan_price * 100;
                    //jQuery('#stripe-submit').trigger( "click" );
                    handler.open({
                        name: post_title,
                        description: "",
                        zipCode: true,
                        amount: plan_price,
                        currency: currency,
                    });
                    e.preventDefault();
                }
            }
        } else if (method === "2checkout") {
            plan_price = jQuery("span.lp-subtotal-total-price").data("subtotal");
            listing_id = $this.find('input[name="listing_id"]:checked').val();
            jQuery("#myCCForm input#tprice").val(plan_price);
            jQuery("#myCCForm input#listing_id").val(listing_id);
            jQuery("button.lp-2checkout-modal").trigger("click");
            e.preventDefault();
        }
    });

    jQuery(".lp_payment_methods_ads .lp-payement-images").on(
        "click",
        function (e) {
            $this = jQuery(this);
            lp_make_campaign_paybutton_active();
        }
    );

    jQuery("button.lp-add-new-btn").on("click", function () {
        jQuery(".lp_camp_invoice_wrp").fadeOut(function () {
            jQuery(".lp-ad-step-two").fadeIn();
        });
    });

    jQuery("a.lp-all-camp-bck").on("click", function (e) {
        jQuery(".lp-ad-step-two").hide(300);
        jQuery(".lp_camp_invoice_wrp").show(300);
        e.preventDefault();
    });
});
/* on 4auguest by z ends */
/* ends here */

/* =====================for mini sub-total================== */
function lp_show_mini_subtotal() {
    var $tax = jQuery(
        "#listings_checkout_form input[name=listing_id]:checked"
    ).data("taxenable");
    var $taxRate = jQuery(
        "#listings_checkout_form input[name=listing_id]:checked"
    ).data("taxrate");
    var $method = jQuery(
        "#listings_checkout_form input[name=plan]:checked"
    ).val();
    var $price = jQuery(
        "#listings_checkout_form input[name=listing_id]:checked"
    ).data("planprice");
    var $orgPrice = $price;
    var $orgPrice = parseFloat($orgPrice).toFixed(2);
    var $planID = jQuery(
        "#listings_checkout_form input[name=listing_id]:checked"
    ).data("planid");
    var $planTime = jQuery(
        "#listings_checkout_form input[name=listing_id]:checked"
    ).data("plantime");
    var $listingID = jQuery(
        "#listings_checkout_form input[name=listing_id]:checked"
    ).val();
    var $lpRecurring = jQuery(
        "#listings_checkout_form .lp-onoff-switch-checkbox .switch-checkbox-label .switch-checkbox-label input:checked"
    ).val();
    var $taxPrice = "";
    var $currencyPos = jQuery("#listings_checkout_form").data("currencypos");
    var $currencySym = jQuery("#listings_checkout_form").data("currencysymbol");
    if ($tax == "1") {
        $taxPrice = ($taxRate / 100) * $price;
        $price = parseFloat($price) + parseFloat($taxPrice);

        $taxPrice = parseFloat($taxPrice).toFixed(2);
    }
    $price = parseFloat($price).toFixed(2);
    jQuery("span.lp-subtotal-plan").text("");
    jQuery("span.lp-subtotal-price").text("");
    jQuery("span.lp-subtotal-taxamount").text("");
    jQuery("span.lp-subtotal-price").text("");
    jQuery("span.lp-subtotal-p-price").text("");
    jQuery("span.lp-subtotal-total-price").text("");
    jQuery("span.lp-subtotal-plan").text(
        jQuery("#listings_checkout_form input[name=listing_id]:checked").data(
            "title"
        )
    );
    //setting values in form
    lp_add_checkout_data_fields(
        $listingID,
        $planID,
        $price,
        $lpRecurring,
        $method,
        $planTime
    );
    switch ($currencyPos) {
        case "left":
            jQuery("span.lp-subtotal-p-price").text($currencySym + $orgPrice);
            jQuery("span.lp-subtotal-price").text($currencySym + $price);
            jQuery("span.lp-subtotal-taxamount").text($currencySym + $taxPrice);
            jQuery("span.lp-subtotal-total-price").text($currencySym + $price);
            jQuery("span.lp-subtotal-total-price").attr("data-subtotal", $price);
            break;
        case "right":
            jQuery("span.lp-subtotal-p-price").text($orgPrice + $currencySym);
            jQuery("span.lp-subtotal-price").text($price + $currencySym);
            jQuery("span.lp-subtotal-taxamount").text($taxPrice + $currencySym);
            jQuery("span.lp-subtotal-total-price").text($price + $currencySym);
            jQuery("span.lp-subtotal-total-price").attr("subtotal", $price);
            break;
        default:
            jQuery("span.lp-subtotal-p-price").text($currencySym + $orgPrice);
            jQuery("span.lp-subtotal-price").text($currencySym + $price);
            jQuery("span.lp-subtotal-taxamount").text($currencySym + $taxPrice);
            jQuery("span.lp-subtotal-total-price").text($currencySym + $price);
            jQuery("span.lp-subtotal-total-price").attr("datasubtotal", $price);
    }

    jQuery(".lp-checkout-coupon-outer").css("display", "block");
    jQuery(".active-checkout-listing").addClass(
        "lp-checkout-wrapper-new-without-radius"
    );
}

/* ====================function for recurring option====================== */

function lp_show_recurring_switch() {
    var $sPlan = jQuery("input[name=plan]:checked").val();
    if ($sPlan == "stripe" || $sPlan == "paypal") {
        jQuery(".lp-checkout-recurring-wrap").css("display", "block");
    } else if ($sPlan == "wire") {
        jQuery(
            '.lp-checkout-recurring-wrap input[name="lp-recurring-option"]'
        ).prop("checked", false);
        jQuery(".lp-checkout-recurring-wrap").css("display", "none");
    }
}

/* ====================function for recurring option====================== */

function lp_add_checkout_data_fields(
    listingID,
    planID,
    price,
    recurring,
    method,
    $planTime
) {
    var $tax = jQuery(
        "#listings_checkout_form input[name=listing_id]:checked"
    ).data("taxenable");
    jQuery("input[name=post_id]").val(listingID);
    jQuery("input[name=method]").val(method);
    if ($tax == "1") {
        jQuery("input[name=listings_tax_price]").val(price);
    }
    jQuery("input[name=prc_plan]").val(planID);
    jQuery("input[name=lprecurring]").val(recurring);
    jQuery("input[name=plan_time]").val($planTime);
}

/* ==================== function to show active fields of coupons============ */
function lp_make_couponsfields_active() {
    jQuery("input.coupon-text-field").prop("disabled", false);
    jQuery("button.coupon-apply-bt").prop("disabled", false);
}

/* ==================== function to show disable fields of coupons============ */
function lp_make_couponsfields_passive() {
    jQuery("input.coupon-text-field").prop("disabled", true);
    jQuery("button.coupon-apply-bt").prop("disabled", true);
}

/* ====================function for adding data in input hidden fields=========*/

function lp_add_checkout_data_fields_in_form(
    listingID,
    post_title,
    planID,
    price,
    $tax,
    $taxRate
) {
    jQuery("input[name=plan_price]").val(price);
    jQuery("input[name=post_title]").val(post_title);
    jQuery("input[name=listings_id]").val(listingID);
    jQuery("input[name=post_id]").val(listingID);
    jQuery("input[name=plan_id]").val(planID);
    if ($tax) {
        taxprice = ($taxRate / 100) * price;
        taxprice = taxprice.toFixed(2);
        jQuery('input[name="listings_tax_price"]').val(taxprice);
    }
    lp_update_date_in_mini_cart(price, $tax, $taxRate);
}

/* ====================function for update data in mini cart====================*/
function lp_update_date_in_mini_cart($price, $tax, $taxRate) {
    var $currencyPos = jQuery("#listings_checkout_form").data("currencypos");
    var $currencySym = jQuery("#listings_checkout_form").data("currencysymbol");
    var $orgPrice = $price;
    var $orgPrice = parseFloat($orgPrice).toFixed(2);
    var $taxPrice = "";
    var $currencyPos = jQuery("#listings_checkout_form").data("currencypos");
    var $currencySym = jQuery("#listings_checkout_form").data("currencysymbol");
    if ($tax == "1") {
        $taxPrice = ($taxRate / 100) * $price;
        $price = parseFloat($price) + parseFloat($taxPrice);
        $price = parseFloat($price).toFixed(2);

        $taxPrice = parseFloat($taxPrice).toFixed(2);
    }

    switch ($currencyPos) {
        case "left":
            //jQuery('span.lp-subtotal-p-price').text($currencySym+$orgPrice);
            jQuery("span.lp-subtotal-price").text($currencySym + $price);
            jQuery("span.lp-subtotal-taxamount").text($currencySym + $taxPrice);
            jQuery("span.lp-subtotal-total-price").text($currencySym + $price);
            jQuery("span.lp-subtotal-total-price").attr("data-subtotal", $price);
            break;
        case "right":
            //jQuery('span.lp-subtotal-p-price').text($orgPrice+$currencySym);
            jQuery("span.lp-subtotal-price").text($price + $currencySym);
            jQuery("span.lp-subtotal-taxamount").text($taxPrice + $currencySym);
            jQuery("span.lp-subtotal-total-price").text($price + $currencySym);
            jQuery("span.lp-subtotal-total-price").attr("data-subtotal", $price);
            break;
        default:
            jQuery("span.lp-subtotal-p-price").text($currencySym + $orgPrice);
            jQuery("span.lp-subtotal-price").text($currencySym + $price);
            jQuery("span.lp-subtotal-taxamount").text($currencySym + $taxPrice);
            jQuery("span.lp-subtotal-total-price").text($currencySym + $price);
            jQuery("span.lp-subtotal-total-price").attr("data-subtotal", $price);
    }
}

/* =====================reset mincart and checkout data  ======================== */
function lp_reset_mincart_checkout_form_data() {
    var $price = jQuery("input[name=listing_id]:checked").data("planprice");
    var $listingID = jQuery("input[name=listing_id]:checked").val();
    var $post_title = jQuery("input[name=listing_id]:checked").data("title");
    var $planID = jQuery("input[name=listing_id]:checked").data("planid");
    var $tax = jQuery("input[name=listing_id]:checked").data("taxenable");
    var $taxRate = jQuery("input[name=listing_id]:checked").data("taxrate");
    lp_add_checkout_data_fields_in_form(
        $listingID,
        $post_title,
        $planID,
        $price,
        $tax,
        $taxRate
    );
}

/* =====================active checkout steps bar  ======================== */
function lp_make_checkout_step_active($stepname) {
    jQuery(".lp_payment_steps_area li." + $stepname + "").addClass("current");
}

/* =====================active checkout steps bar  ======================== */
function lp_make_checkout_step_passive($stepname) {
    jQuery(".lp_payment_steps_area li." + $stepname + "").removeClass("current");
}

/* =====================active checkout steps button on all selections ======================== */
function lp_make_campaign_paybutton_active() {
    var selected_option = jQuery(".lp-search-listing-camp").val();
    var atLeastOnePlaceAd =
        jQuery('input[name="lpadsoftype[]"]:checked').length > 0;
    var atLeastOneMethodAd = jQuery('input[name="method"]:checked').length > 0;
    var adsterms = jQuery("#lp-campaignTerms:checked").length > 0;
    var listing_id = jQuery("select[name=lp_ads_for_listing]").val();

    var adPriceField = 1;
    var adDurationField = 1;

    if (jQuery('input[name="adsduration_pd"]').length > 0) {
        adDurationField = jQuery('input[name="adsduration_pd"]').val();
    }

    if (jQuery('input[name="adsprice_pc"]').length > 0) {
        adPriceField = jQuery('input[name="adsprice_pc"]').val();
    }

    if (
        selected_option != "" &&
        selected_option != "0" &&
        listing_id != "" &&
        listing_id != "0" &&
        atLeastOnePlaceAd != "" &&
        adsterms != "" &&
        adsterms != "0" &&
        atLeastOnePlaceAd != "0" &&
        atLeastOneMethodAd != "" &&
        atLeastOneMethodAd != "0" &&
        adDurationField != "" &&
        adDurationField != "0" &&
        adPriceField != "" &&
        adPriceField != "0"
    ) {
        jQuery("button.lp_campaign_paynow").attr("disabled", false);
        jQuery("button.lp_campaign_paynow").attr("type", "submit");
    } else {
        jQuery("button.lp_campaign_paynow").attr("disabled", true);
        jQuery("button.lp_campaign_paynow").attr("type", "button");
    }
}

jQuery(document).on("change", "select[name=lp_ads_for_listing]", function () {
    lp_make_campaign_paybutton_active();
});

jQuery(document).on("click", "#lp-campaignTerms", function () {
    lp_make_campaign_paybutton_active();
});

jQuery(document).on("click", ".show-loop-map-popup", function (e) {
    e.preventDefault();
    if (jQuery("#grid-show-popup").is(".md-show")) { } else {
        jQuery("#grid-show-popup").modal({
            show: "true",
        });
        jQuery("#grid-show-popup").addClass("md-show");
    }
    var $this = jQuery(this),
        LAT = $this.data("lat"),
        LNG = $this.data("lng"),
        LPpostID = $this.data("lid");
    jQuery.ajax({
        url: ajax_search_term_object.ajaxurl,
        data: {
            action: "show_map_pop_cb",
            LPpostID: LPpostID,
            lpNonce: jQuery("#lpNonce").val(),
        },
        success: function (data) {
            jQuery("#grid-show-popup .grid-show-popup").html(data);
            var markerSrc = jQuery(
                "#grid-show-popup .grid-show-popup .quickmap"
            ).attr("data-marker-src");
            var markerElement;
            if (markerSrc.startsWith("fa-")) {
                markerElement = '<i class="' + markerSrc + '"></i>';
            } else if (
                markerSrc.startsWith("http://") ||
                markerSrc.startsWith("https://")
            ) {
                markerElement = '<img src="' + markerSrc + '" alt="Marker">';
            } else if (markerSrc.startsWith("data:image/")) {
                markerElement = '<img src="' + markerSrc + '" alt="Marker">';
            }
            var markers = false;
            $mtoken = jQuery("#page").data("mtoken");
            $mtype = jQuery("#page").data("mtype");
            $siteURL = jQuery("#page").data("site-url");
            $lat = LAT;
            $lan = LNG;
            if ($mtoken != "" && $mtype == "mapbox") {
                L.mapbox.accessToken = $mtoken;
                map = L.mapbox.map("quickmap" + LPpostID);
                L.tileLayer(
                    "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", {
                    id: jQuery("#page").data("mstyle"),
                    accessToken: jQuery("#page").data("mtoken"),
                }
                ).addTo(map);
            } else {
                var map = new L.Map("quickmap" + LPpostID, {
                    center: new L.LatLng($lat, $lan),
                    zoom: 14,
                });
                if ($mtype == "google") {
                    var googleLayer = new L.Google("ROADMAP");
                    map.addLayer(googleLayer);
                } else {
                    L.tileLayer(
                        "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    ).addTo(map);
                }
            }
            map.setView([$lat, $lan], 14);
            markers = new L.MarkerClusterGroup();
            var markerLocation = new L.LatLng($lat, $lan); // London
            var CustomHtmlIcon = L.HtmlIcon.extend({
                options: {
                    html: "<div class='lpmap-icon-shape pin '><div class='lpmap-icon-contianer'>" +
                        markerElement +
                        "'</div></div>",
                },
            });
            var customHtmlIcon = new CustomHtmlIcon();
            var marker = new L.Marker(markerLocation, {
                icon: customHtmlIcon,
            })
                .bindPopup("")
                .addTo(map);
            markers.addLayer(marker);
            jQuery(".md-close.widget-map-click").click(function (e) {
                var loaderImg = jQuery("#grid-show-popup .grid-show-popup").data(
                    "loader"
                );
                jQuery("#full-overlay").remove();
                jQuery("#grid-show-popup .grid-show-popup").html(
                    '<img alt="image" src="' + loaderImg + '" />'
                );
            });
            //alert(data.cats_markup);
        },
        error: function (errorThrown) {
            alert(errorThrown);
        },
    });
});

jQuery(document).on("click", ".open-multi-rate-box", function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        targetBox = "#" + $this.data("rate-box");
    jQuery(targetBox).slideToggle(500);
});

jQuery("button.printthisinvoice").click(function (e) {
    var printContents = document.querySelector(
        "#listing-invoices-popup .modal-body"
    ).innerHTML;
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
    location.reload();
    e.preventDefault();
});

jQuery(document).ready(function () {
    if (jQuery(".lp-user-listings.active-checkout-listing").length) {
        jQuery(".lp-user-listings").each(function (index) {
            if (jQuery(this).hasClass("active-checkout-listing")) { } else {
                jQuery(this).remove();
            }
        });
    }
});

// App view menu in tabs
jQuery(document).ready(function () {
    jQuery(".lp-menu-type-heading").on("click", function () {
        //jQuery('.lp-menu-type-heading').removeClass('active');
        jQuery(this).toggleClass("active");
        jQuery(".active-menu-toggle").slideUp("slow", function () {
            jQuery(".active-menu-toggle").removeClass("active-menu-toggle");
        });
        var getmenutype = "." + jQuery(this).attr("data-target");
        jQuery(getmenutype).slideToggle("slow");
    });
    jQuery(".lp-appview-group-heading").on("click", function () {
        //jQuery('.lp-appview-group-heading').removeClass('active');
        jQuery(this).toggleClass("active");
        var getmenugroup = "." + jQuery(this).attr("data-target");
        //jQuery('.lp-appview-menu-items-bygroup').slideUp('slow');
        jQuery(this).next(getmenugroup).slideToggle("slow");
    });
});

jQuery(document).ready(function () {
    //dashboard weekly monthly active
    jQuery(".lp_stats_duration_filter li button").on("click", function () {
        jQuery(".lp_stats_duratonBtn").removeClass("active");

        jQuery(this).addClass("active");
    });

    //If width is less than 640
    if (jQuery(window).width() < 641) {
        jQuery("#main_icon").on("click", function () {
            jQuery("#main_icon").toggleClass("fa fa-times");
            jQuery("#sidebar").toggle(300);
        });
    }

    //New archive style grid switcher
    jQuery(".lp-grid-two").on("click", function () {
        jQuery(".lp-sidebar-filters-style").removeClass("lp-grid-width1");
        jQuery(".lp-sidebar-filters-style").removeClass("lp-grid-width3");

        jQuery(".lp-sidebar-filters-style").addClass("lp-grid-width2");
        jQuery(".lp-grid-two").addClass("active");
        jQuery(".lp-grid-one").removeClass("active");
        jQuery(".lp-grid-three").removeClass("active");
    });
    jQuery(".lp-grid-one").on("click", function () {
        jQuery(".lp-sidebar-filters-style").removeClass("lp-grid-width2");
        jQuery(".lp-sidebar-filters-style").removeClass("lp-grid-width3");

        jQuery(".lp-sidebar-filters-style").addClass("lp-grid-width1");
        jQuery(".lp-grid-one").addClass("active");
        jQuery(".lp-grid-two").removeClass("active");
        jQuery(".lp-grid-three").removeClass("active");
    });
    jQuery(".lp-grid-three").on("click", function () {
        jQuery(".lp-sidebar-filters-style").removeClass("lp-grid-width1");
        jQuery(".lp-sidebar-filters-style").removeClass("lp-grid-width2");

        jQuery(".lp-sidebar-filters-style").addClass("lp-grid-width3");
        jQuery(".lp-grid-three").addClass("active");
        jQuery(".lp-grid-two").removeClass("active");
        jQuery(".lp-grid-one").removeClass("active");
    });
});

jQuery(document).on("click", ".app-view-popup-style", function () {
    jQuery('<div id="full-overlay-lp"></div>').insertBefore(
        "#app-view-login-popup"
    );
    jQuery("#full-overlay-lp").css({
        width: "100vw",
        height: "100vh",
        position: "fixed",
        background: "#000000c7",
        "z-index": 3,
        top: 0,
        left: 0,
    });
    jQuery(".md-close i").click(function () {
        jQuery("#full-overlay-lp").remove();
        jQuery("#app-view-login-popup").fadeOut(function () {
            jQuery("#app-view-login-popup").css({
                //'opacity': 0,
                display: "none",
            });
        });
    });
});

/* ======function to get currency symbol===== */

function lp_get_currency_sysmbol() {
    $code = jQuery("#lp-new-ad-compaignForm").data("camp-currency");
    return $code;
}

/* ======function to get tax percent===== */

function lp_get_tax_percent() {
    $code = jQuery("#lp-new-ad-compaignForm").data("tax-percent");
    return $code;
}

/* ======function to get selected campaigns org price===== */

function lp_get_selected_camp_price() {
    $totalCamPrice = 0;
    jQuery('input[name="lpadsoftype[]"]:checked').each(function () {
        $thisAd = jQuery(this).data("orgprice");
        $totalCamPrice = parseFloat($totalCamPrice) + parseFloat($thisAd);
    });
    //console.log($totalCamPrice);
    return $totalCamPrice;
}

/* ======function to get selected campaigns with tax price===== */
function lp_get_selected_camp_withtax_price() {
    $totalCamPrice = 0;
    jQuery('input[name="lpadsoftype[]"]:checked').each(function () {
        $thisAd = jQuery(this).data("price");
        $totalCamPrice = parseFloat($totalCamPrice) + parseFloat($thisAd);
    });
    //console.log($totalCamPrice);
    return $totalCamPrice;
}

/* ======function to get tax price of campaigns===== */
function lp_get_selected_camp_onlytax_price() {
    $totalCamPrice = 0;
    jQuery('input[name="lpadsoftype[]"]:checked').each(function () {
        $thisAd = jQuery(this).data("taxprice");
        $totalCamPrice = parseFloat($totalCamPrice) + parseFloat($thisAd);
    });
    //console.log($totalCamPrice);
    return $totalCamPrice;
}

/* ======function to set camp duration price in preview===== */
function lp_set_camp_duration_price_in_preview($thisval) {
    $daysString = jQuery(".lp-cmp-duration").data("days-text");
    $taxPercent = lp_get_tax_percent();
    $taxtotalPrice = lp_get_selected_camp_onlytax_price();
    $taxtotalPrice = $thisval * $taxtotalPrice;
    $taxtotalPrice = $taxtotalPrice.toFixed(2);
    jQuery("input[name=taxprice]").val($taxtotalPrice);
    jQuery("input[name=ads_days]").val($thisval);
    $thisvalWithDays = $thisval + " " + $daysString;
    jQuery(".lp-cmp-duration h6").text($thisvalWithDays);
    $totalCamPrice = lp_get_selected_camp_price();
    $totalCamPrice = parseFloat($thisval) * parseFloat($totalCamPrice);
    console.log($totalCamPrice);
    $totalCamPrice = $totalCamPrice.toFixed(2);
    jQuery(".lp-cmp-subtotal h6").text(
        lp_get_currency_sysmbol() + "" + $totalCamPrice
    );
    $totalCamPriceWithTax = lp_get_selected_camp_withtax_price();
    $totalCamPriceWithTax =
        parseFloat($thisval) * parseFloat($totalCamPriceWithTax);
    $totalCamPriceWithTax = $totalCamPriceWithTax.toFixed(2);
    console.log($totalCamPriceWithTax);
    jQuery(".lp-cmp-alltotal h5").text(
        lp_get_currency_sysmbol() + "" + $totalCamPriceWithTax
    );
    jQuery("input[name=ads_price]").val($totalCamPriceWithTax);

    jQuery(".lp-cmp-taxtotal h6").text($taxtotalPrice);
}

/* ======function to set camp price in preview===== */
function lp_set_camp_budget_price_in_preview($thisval) {
    $taxPercent = lp_get_tax_percent();
    $thisvalWithCurr = lp_get_currency_sysmbol() + "" + $thisval;
    jQuery(".lp-cmp-budget h6").text($thisvalWithCurr);
    jQuery(".lp-cmp-subtotal h6").text($thisvalWithCurr);
    $taxPrice = 0;
    if ($taxPercent) {
        $taxPrice = ($taxPercent / 100) * $thisval;
        $taxPrice = $taxPrice.toFixed(2);
        jQuery("input[name=taxprice]").val($taxPrice);
        $taxPriceWithCurr = lp_get_currency_sysmbol() + "" + $taxPrice;
        jQuery(".lp-cmp-taxtotal h6").text($taxPriceWithCurr);
    }

    $totalAmount = parseFloat($thisval) + parseFloat($taxPrice);
    jQuery("input[name=ads_price]").val($totalAmount);
    jQuery(".lp-cmp-alltotal h5").text(
        lp_get_currency_sysmbol() + "" + $totalAmount
    );
}

/* ======function to set camp type===== */
function lp_get_camp_type() {
    $camptype = jQuery("#lp-new-ad-compaignForm").data("type");
    return $camptype;
}

// Add hours
jQuery(document).on("click", "button.add-hours", function (event) {
    event.preventDefault();
    var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    var $this = jQuery(this);
    var lp2times = $this
        .closest("#day-hours-BusinessHours")
        .data("lpenabletwotimes");
    var sorryMsg = jQuery(this).data("sorrymsg");
    var alreadyadded = jQuery(this).data("alreadyadded");
    var error = false;
    var fullday = "";
    var fullhoursclass = "";

    var lpdash = "~";

    if (lp2times == "disable") {
        var weekday = jQuery("select.weekday").val();
        if (jQuery(".fulldayopen").is(":checked")) {
            jQuery(".fulldayopen").attr("checked", false);
            jQuery("select.hours-start").prop("disabled", false);
            jQuery("select.hours-end").prop("disabled", false);
            var startVal = "";
            var endVal = "";
            var hrstart = "";
            var hrend = "";
            fullday = $this.data("fullday");
            fullhoursclass = "fullhours";
            lpdash = "";
        } else {
            var startVal = jQuery("select.hours-start").val();
            var endVal = jQuery("select.hours-end").val();
            var hrstart = jQuery("select.hours-start").find("option:selected").val();
            var hrend = jQuery("select.hours-end").find("option:selected").val();

            var startVal_digit = hrstart.replace(":", "");
            var endVal_digit = hrend.replace(":", "");

            if (startVal_digit.indexOf("am") > -1) {
                startVal_digit = startVal_digit.replace("am", "");
            } else if (startVal_digit.indexOf("pm") > -1) {
                startVal_digit = startVal_digit.replace("pm", "");
                if (startVal_digit != "1200" && startVal_digit != "1230") {
                    startVal_digit = parseInt(startVal_digit) + 1200;
                }
            }
            if (endVal_digit.indexOf("am") > -1) {
                endVal_digit = endVal_digit.replace("am", "");
                endVal_digit = parseInt(endVal_digit);
                if (endVal_digit >= 1200) {
                    endVal_digit = parseInt(endVal_digit) - 1200;
                }
            } else if (endVal_digit.indexOf("pm") > -1) {
                endVal_digit = endVal_digit.replace("pm", "");
                endVal_digit = parseInt(endVal_digit) + 1200;
            }

            if (startVal_digit > endVal_digit) {
                nextWeekday = jQuery("select.weekday option:selected+option").val();
                if (typeof nextWeekday === "undefined") {
                    nextWeekday = jQuery("select.weekday")
                        .find("option:first-child")
                        .val();
                }

                weekday = weekday + "~" + nextWeekday;
            }
        }

        if ($this.hasClass("lp-add-hours-st")) {
            var remove = '<i class="fa fa-times"></i>';
        } else {
            var remove = jQuery(this).data("remove");
        }
        jQuery(".hours-display .hours").each(function (index, element) {
            var weekdayTExt = jQuery(element).children(".weekday").text();
            if (weekdayTExt == weekday) {
                alert(sorryMsg + "! " + weekday + " " + alreadyadded);
                error = true;
            }
        });
        if (error != true) {
            jQuery(".hours-display").append(
                "<div class='hours " +
                fullhoursclass +
                "'><span class='weekday'>" +
                weekday +
                "</span><span class='start-end fullday'>" +
                fullday +
                "</span><span class='start'>" +
                hrstart +
                "</span><span>" +
                lpdash +
                "</span><span class='end'>" +
                hrend +
                "</span><a class='remove-hours' href='#'>" +
                remove +
                "</a><input name='business_hours[" +
                weekday +
                "][open]' value='" +
                startVal +
                "' type='hidden'><input name='business_hours[" +
                weekday +
                "][close]' value='" +
                endVal +
                "' type='hidden'></div>"
            );

            if (is_safari) { } else {
                var current = jQuery("select.weekday").find("option:selected");
                var nextval = current.next();
                current.removeAttr("selected");
                nextval.attr("selected", "selected");
                jQuery("select.weekday").trigger("change.select2");
            }
        }
    } else {
        var lptwentlyfourisopen = "";
        /* 2times */
        var weekday = jQuery("select.weekday").val();
        var weekday1 = weekday;
        var weekday2 = weekday;

        if (jQuery(".fulldayopen").is(":checked")) {
            lptwentlyfourisopen = "yes";

            jQuery(".fulldayopen").attr("checked", false);
            jQuery("select.hours-start").prop("disabled", false);
            jQuery("select.hours-end").prop("disabled", false);

            jQuery("select.hours-start2").prop("disabled", false);
            jQuery("select.hours-end2").prop("disabled", false);

            var startVal1 = "";
            var endVal1 = "";
            var hrstart1 = "";
            var hrend1 = "";

            var startVal2 = "";
            var endVal2 = "";
            var hrstart2 = "";
            var hrend2 = "";

            fullday = $this.data("fullday");
            fullhoursclass = "fullhours";

            lpdash = "";
        } else {
            var startVal1 = jQuery("select.hours-start").val();
            var endVal1 = jQuery("select.hours-end").val();
            var hrstart1 = jQuery("select.hours-start").find("option:selected").val();
            var hrend1 = jQuery("select.hours-end").find("option:selected").val();

            var startVal1_digit = hrstart1.replace(":", "");
            var endVal1_digit = hrend1.replace(":", "");

            if (startVal1_digit.indexOf("am") > -1) {
                startVal1_digit = startVal1_digit.replace("am", "");
            } else if (startVal1_digit.indexOf("pm") > -1) {
                startVal1_digit = startVal1_digit.replace("pm", "");
                if (startVal1_digit != "1200" && startVal1_digit != "1230") {
                    startVal1_digit = parseInt(startVal1_digit) + 1200;
                }
            }
            if (endVal1_digit.indexOf("am") > -1) {
                endVal1_digit = endVal1_digit.replace("am", "");
                endVal1_digit = parseInt(endVal1_digit);
                if (endVal1_digit >= 1200) {
                    endVal1_digit = parseInt(endVal1_digit) - 1200;
                }
            } else if (endVal1_digit.indexOf("pm") > -1) {
                endVal1_digit = endVal1_digit.replace("pm", "");
                endVal1_digit = parseInt(endVal1_digit) + 1200;
            }

            if (startVal1_digit > endVal1_digit) {
                nextWeekday = jQuery("select.weekday option:selected+option").val();
                if (typeof nextWeekday === "undefined") {
                    nextWeekday = jQuery("select.weekday")
                        .find("option:first-child")
                        .val();
                }

                weekday1 = weekday + "~" + nextWeekday;
                jQuery(".hours-display .hours").each(function (e) {
                    var $this = jQuery(this);
                    if (
                        $this.find('span.weekday:contains("' + weekday1 + '")').length > 0
                    ) {
                        alert(sorryMsg + "! " + weekday1 + " " + alreadyadded);
                        error = true;
                    }
                });
            }

            var startVal2 = jQuery("select.hours-start2").val();
            var endVal2 = jQuery("select.hours-end2").val();
            var hrstart2 = jQuery("select.hours-start2")
                .find("option:selected")
                .text();
            var hrend2 = jQuery("select.hours-end2").find("option:selected").text();

            var startVal2_digit = hrstart2.replace(":", "");
            var endVal2_digit = hrend2.replace(":", "");

            if (startVal2_digit.indexOf(" AM") > -1) {
                startVal2_digit = parseInt(startVal2_digit.replace(" AM", ""));
            } else if (startVal2_digit.indexOf(" PM") > -1) {
                startVal2_digit = parseInt(startVal2_digit.replace(" PM", ""));
                if (startVal2_digit != "1200" && startVal2_digit != "1230") {
                    startVal2_digit = parseInt(startVal2_digit) + 1200;
                }
            }
            if (endVal2_digit.indexOf(" AM") > -1) {
                endVal2_digit = endVal2_digit.replace(" AM", "");
                endVal2_digit = parseInt(endVal2_digit);
                if (endVal2_digit >= 1200) {
                    endVal2_digit = parseInt(endVal2_digit) - 1200;
                }
            } else if (endVal2_digit.indexOf(" PM") > -1) {
                endVal2_digit = endVal2_digit.replace(" PM", "");
                endVal2_digit = parseInt(endVal2_digit) + 1200;
            }
            nextWeekday = jQuery("select.weekday option:selected+option").val();
            if (typeof nextWeekday === "undefined") {
                nextWeekday = jQuery("select.weekday").find("option:first-child").val();
            }
            weekday2 = weekday;
            jQuery(".hours-display .hours").each(function (e) {
                var $this = jQuery(this);
                if (
                    $this.find('span.weekday:contains("' + weekday2 + '")').length > 0
                ) {
                    alert(sorryMsg + "! " + weekday2 + " " + alreadyadded);
                    error = true;
                }
            });
        }

        if ($this.hasClass("lp-add-hours-st")) {
            var remove = '<i class="fa fa-times"></i>';
        } else {
            var remove = jQuery(this).data("remove");
        }
        jQuery(".hours-display .hours").each(function (index, element) {
            var weekdayTExt = jQuery(element).children(".weekday").text();
            if (weekdayTExt == weekday) {
                alert(sorryMsg + "! " + weekday + " " + alreadyadded);
                error = true;
            }
        });
        if (error != true) {
            hrstart1 = hrstart1.replace(/am/i, ' AM').replace(/pm/i, ' PM');
            hrend1   = hrend1.replace(/am/i, ' AM').replace(/pm/i, ' PM');
            if (jQuery(".lp-check-doubletime .enable2ndday").is(":checked") && lptwentlyfourisopen === "") {
                jQuery(".hours-display").append(
                    "<div class='hours " +
                    fullhoursclass +
                    "'><span class='weekday'>" +
                    weekday +
                    "</span><span class='start-end fullday'>" +
                    fullday +
                    "</span><span class='start'>" +
                    hrstart1 +
                    "</span><span>" +
                    lpdash +
                    "</span><span class='end'>" +
                    hrend1 +
                    "</span><a class='remove-hours' href='#'>" +
                    remove +
                    "</a><br><span class='weekday'>&nbsp;</span><span class='start'>" +
                    hrstart2 +
                    "</span><span>" +
                    lpdash +
                    "</span><span class='end'>" +
                    hrend2 +
                    "</span><input name='business_hours[" +
                    weekday1 +
                    "][open][0]' value='" +
                    startVal1 +
                    "' type='hidden'><input name='business_hours[" +
                    weekday1 +
                    "][close][0]' value='" +
                    endVal1 +
                    "' type='hidden'><input name='business_hours[" +
                    weekday2 +
                    "][open][1]' value='" +
                    startVal2 +
                    "' type='hidden'><input name='business_hours[" +
                    weekday2 +
                    "][close][1]' value='" +
                    endVal2 +
                    "' type='hidden'></div>"
                );
            } else {
                jQuery(".hours-display").append(
                    "<div class='hours " +
                    fullhoursclass +
                    "'><span class='weekday'>" +
                    weekday1 +
                    "</span><span class='start-end fullday'>" +
                    fullday +
                    "</span><span class='start'>" +
                    hrstart1 +
                    "</span><span>" +
                    lpdash +
                    "</span><span class='end'>" +
                    hrend1 +
                    "</span><a class='remove-hours' href='#'>" +
                    remove +
                    "</a><input name='business_hours[" +
                    weekday1 +
                    "][open]' value='" +
                    startVal1 +
                    "' type='hidden'><input name='business_hours[" +
                    weekday1 +
                    "][close]' value='" +
                    endVal1 +
                    "' type='hidden'></div>"
                );
            }
            if (is_safari) { } else {
                var current = jQuery("select.weekday").find("option:selected");
                var nextval = current.next();
                current.removeAttr("selected");
                nextval.attr("selected", "selected");
                jQuery("select.weekday").trigger("change.select2");
            }
        }

        /* 2times */
    }
});

jQuery(document).on("click", ".lp-dot-extra-buttons", function (e) {
    jQuery(this).find(".lp-user-menu").toggleClass("main");
});

jQuery(document).ready(function () {
    jQuery(
        ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
    ).attr("disabled", true);
    jQuery(
        ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
    ).addClass("LPdisabled");
    if (jQuery(".form-group.lp-claim-form-check-circle input").is(":checked")) {
        jQuery(
            ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
        ).attr("disabled", false);
        jQuery(
            ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
        ).removeClass("LPdisabled");
    } else {
        jQuery(
            ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
        ).attr("disabled", true);

        jQuery(
            ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
        ).addClass("LPdisabled");
    }
    jQuery(".form-group.lp-claim-form-check-circle input").click(function () {
        if (jQuery(".form-group.lp-claim-form-check-circle input").is(":checked")) {
            jQuery(
                ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
            ).attr("disabled", false);
            jQuery(
                ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
            ).removeClass("LPdisabled");
        } else {
            jQuery(
                ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
            ).attr("disabled", true);
            jQuery(
                ".lp-secondary-btn.btn-second-hover.lp-secondary-choose.lp-claim-plan-btn"
            ).addClass("LPdisabled");
        }
    });
});
jQuery("#pop").on("click", function (e) {
    e.preventDefault();
    jQuery("#imagemodal").modal("show"); // imagemodal is the id attribute assigned to the bootstrap modal, then i use the show function
    var img_src = jQuery(this).data("imgsrc");
    jQuery("#imagemodal").find("img").attr("src", img_src);
});
jQuery("#my_file").change(function () {
    var i = jQuery(this).prev("label").clone();
    var file = jQuery("#my_file")[0].files[0].name;
    jQuery(this).prev("label").text(file);
});
jQuery(document).ready(function () {
    if (jQuery(".payment-recurring-message").length > 0) {
        jQuery(document).on("change", ".lp-checkout-recurring-wrap", function () {
            var checkboxVal = jQuery(
                '.lp-checkout-recurring-wrap input[name="lp-recurring-option"]'
            ).is(":checked");
            if (checkboxVal === false) {
                jQuery(".payment-recurring-message").fadeOut("slow");
            }
        });
        jQuery(".rec_alert_remove").click(function () {
            jQuery(".payment-recurring-message").fadeOut("slow");
        });
    }
});
jQuery(document).on("click", ".sidebar-filters-map-pop", function (e) {
    if (jQuery(".sidemap-container").hasClass("sidebar-filters-map-full")) {
        jQuery(".sidemap-container").removeClass("sidebar-filters-map-full");
        jQuery(this).text(jQuery(this).attr("data-full-map"));
    } else {
        jQuery(".sidemap-container").addClass("sidebar-filters-map-full");
        jQuery(this).text(jQuery(this).attr("data-close-map"));
        setTimeout(function () {
            jQuery(".all-list-map").trigger("click");
        }, 1000);
    }
});
/* new classic setting js  */
jQuery(document).ready(function () {
    jQuery(".classic-search .what-placeholder .down-search-q").click(function () {
        jQuery("#input-dropdown").toggleClass("active");
        jQuery(".classic-search .what-placeholder .down-search-q").toggleClass(
            "active"
        );
    });
    jQuery(
        ".classic-search .form-group.lp-suggested-search .lp-search-input.form-control.ui-autocomplete-input"
    ).click(function () {
        jQuery("#input-dropdown").addClass("active");
        jQuery(".classic-search .what-placeholder .down-search-q").addClass(
            "active"
        );
    });
    jQuery(function () {
        jQuery(document).click(function (e) {
            var target = e.target;
            if (
                !jQuery(target).is(".classic-search .what-placeholder") &&
                !jQuery(target).parents().is(".classic-search .what-placeholder")
            ) {
                jQuery(".classic-search .what-placeholder .down-search-q").removeClass(
                    "active"
                );
                jQuery(".classic-search #input-dropdown").removeClass("active");
            }
        });
    });
});

jQuery(window).on("load", function () {
    if (jQuery(".lp-theme-loader").length > 0) {
        jQuery(".lp-theme-loader").css({
            opacity: "0",
            visibility: "hidden",
        });
    }
    jQuery(
        ".lp-home-banner-contianer .lp-search-bar .chosen-container .chosen-results"
    ).niceScroll();
    jQuery(
        ".lp-customize-header-outer.lp-color-header-style.lp-header-style-classic .lp-search-bar.lp-search-bar-header .chosen-drop .chosen-results"
    ).niceScroll();
});
jQuery(document).ready(function ($) {
    if ($(".lp-activities-classic-slider").length > 0) {
        $(".lp-activities-classic-slider").slick({
            dots: true,
            infinite: false,
            speed: 300,
            slidesToShow: 3,
            arrows: false,
            slidesToScroll: 1,
            responsive: [{
                breakpoint: 1024,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 1,
                    infinite: true,
                    dots: true,
                },
            },
            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                },
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                },
            },
            ],
        });
    }
});
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/lib/countdown/flipclock.min.js?ver=4fca74de5e3fa981b9659807f09e9e55 
/*! flipclock 2015-08-31 */
var Base=function(){};Base.extend=function(a,b){"use strict";var c=Base.prototype.extend;Base._prototyping=!0;var d=new this;c.call(d,a),d.base=function(){},delete Base._prototyping;var e=d.constructor,f=d.constructor=function(){if(!Base._prototyping)if(this._constructing||this.constructor==f)this._constructing=!0,e.apply(this,arguments),delete this._constructing;else if(null!==arguments[0])return(arguments[0].extend||c).call(arguments[0],d)};return f.ancestor=this,f.extend=this.extend,f.forEach=this.forEach,f.implement=this.implement,f.prototype=d,f.toString=this.toString,f.valueOf=function(a){return"object"==a?f:e.valueOf()},c.call(f,b),"function"==typeof f.init&&f.init(),f},Base.prototype={extend:function(a,b){if(arguments.length>1){var c=this[a];if(c&&"function"==typeof b&&(!c.valueOf||c.valueOf()!=b.valueOf())&&/\bbase\b/.test(b)){var d=b.valueOf();b=function(){var a=this.base||Base.prototype.base;this.base=c;var b=d.apply(this,arguments);return this.base=a,b},b.valueOf=function(a){return"object"==a?b:d},b.toString=Base.toString}this[a]=b}else if(a){var e=Base.prototype.extend;Base._prototyping||"function"==typeof this||(e=this.extend||e);for(var f={toSource:null},g=["constructor","toString","valueOf"],h=Base._prototyping?0:1;i=g[h++];)a[i]!=f[i]&&e.call(this,i,a[i]);for(var i in a)f[i]||e.call(this,i,a[i])}return this}},Base=Base.extend({constructor:function(){this.extend(arguments[0])}},{ancestor:Object,version:"1.1",forEach:function(a,b,c){for(var d in a)void 0===this.prototype[d]&&b.call(c,a[d],d,a)},implement:function(){for(var a=0;a<arguments.length;a++)"function"==typeof arguments[a]?arguments[a](this.prototype):this.prototype.extend(arguments[a]);return this},toString:function(){return String(this.valueOf())}});var FlipClock;!function(a){"use strict";FlipClock=function(a,b,c){return b instanceof Object&&b instanceof Date==!1&&(c=b,b=0),new FlipClock.Factory(a,b,c)},FlipClock.Lang={},FlipClock.Base=Base.extend({buildDate:"2014-12-12",version:"0.7.7",constructor:function(b,c){"object"!=typeof b&&(b={}),"object"!=typeof c&&(c={}),this.setOptions(a.extend(!0,{},b,c))},callback:function(a){if("function"==typeof a){for(var b=[],c=1;c<=arguments.length;c++)arguments[c]&&b.push(arguments[c]);a.apply(this,b)}},log:function(a){window.console&&console.log&&console.log(a)},getOption:function(a){return this[a]?this[a]:!1},getOptions:function(){return this},setOption:function(a,b){this[a]=b},setOptions:function(a){for(var b in a)"undefined"!=typeof a[b]&&this.setOption(b,a[b])}})}(jQuery),function(a){"use strict";FlipClock.Face=FlipClock.Base.extend({autoStart:!0,dividers:[],factory:!1,lists:[],constructor:function(a,b){this.dividers=[],this.lists=[],this.base(b),this.factory=a},build:function(){this.autoStart&&this.start()},createDivider:function(b,c,d){"boolean"!=typeof c&&c||(d=c,c=b);var e=['<span class="'+this.factory.classes.dot+' top"></span>','<span class="'+this.factory.classes.dot+' bottom"></span>'].join("");d&&(e=""),b=this.factory.localize(b);var f=['<span class="'+this.factory.classes.divider+" "+(c?c:"").toLowerCase()+'">','<span class="'+this.factory.classes.label+'">'+(b?b:"")+"</span>",e,"</span>"],g=a(f.join(""));return this.dividers.push(g),g},createList:function(a,b){"object"==typeof a&&(b=a,a=0);var c=new FlipClock.List(this.factory,a,b);return this.lists.push(c),c},reset:function(){this.factory.time=new FlipClock.Time(this.factory,this.factory.original?Math.round(this.factory.original):0,{minimumDigits:this.factory.minimumDigits}),this.flip(this.factory.original,!1)},appendDigitToClock:function(a){a.$el.append(!1)},addDigit:function(a){var b=this.createList(a,{classes:{active:this.factory.classes.active,before:this.factory.classes.before,flip:this.factory.classes.flip}});this.appendDigitToClock(b)},start:function(){},stop:function(){},autoIncrement:function(){this.factory.countdown?this.decrement():this.increment()},increment:function(){this.factory.time.addSecond()},decrement:function(){0==this.factory.time.getTimeSeconds()?this.factory.stop():this.factory.time.subSecond()},flip:function(b,c){var d=this;a.each(b,function(a,b){var e=d.lists[a];e?(c||b==e.digit||e.play(),e.select(b)):d.addDigit(b)})}})}(jQuery),function(a){"use strict";FlipClock.Factory=FlipClock.Base.extend({animationRate:1e3,autoStart:!0,callbacks:{destroy:!1,create:!1,init:!1,interval:!1,start:!1,stop:!1,reset:!1},classes:{active:"flip-clock-active",before:"flip-clock-before",divider:"flip-clock-divider",dot:"flip-clock-dot",label:"flip-clock-label",flip:"flip",play:"play",wrapper:"flip-clock-wrapper"},clockFace:"HourlyCounter",countdown:!1,defaultClockFace:"HourlyCounter",defaultLanguage:"english",$el:!1,face:!0,lang:!1,language:"english",minimumDigits:0,original:!1,running:!1,time:!1,timer:!1,$wrapper:!1,constructor:function(b,c,d){d||(d={}),this.lists=[],this.running=!1,this.base(d),this.$el=a(b).addClass(this.classes.wrapper),this.$wrapper=this.$el,this.original=c instanceof Date?c:c?Math.round(c):0,this.time=new FlipClock.Time(this,this.original,{minimumDigits:this.minimumDigits,animationRate:this.animationRate}),this.timer=new FlipClock.Timer(this,d),this.loadLanguage(this.language),this.loadClockFace(this.clockFace,d),this.autoStart&&this.start()},loadClockFace:function(a,b){var c,d="Face",e=!1;return a=a.ucfirst()+d,this.face.stop&&(this.stop(),e=!0),this.$el.html(""),this.time.minimumDigits=this.minimumDigits,c=FlipClock[a]?new FlipClock[a](this,b):new FlipClock[this.defaultClockFace+d](this,b),c.build(),this.face=c,e&&this.start(),this.face},loadLanguage:function(a){var b;return b=FlipClock.Lang[a.ucfirst()]?FlipClock.Lang[a.ucfirst()]:FlipClock.Lang[a]?FlipClock.Lang[a]:FlipClock.Lang[this.defaultLanguage],this.lang=b},localize:function(a,b){var c=this.lang;if(!a)return null;var d=a.toLowerCase();return"object"==typeof b&&(c=b),c&&c[d]?c[d]:a},start:function(a){var b=this;b.running||b.countdown&&!(b.countdown&&b.time.time>0)?b.log("Trying to start timer when countdown already at 0"):(b.face.start(b.time),b.timer.start(function(){b.flip(),"function"==typeof a&&a()}))},stop:function(a){this.face.stop(),this.timer.stop(a);for(var b in this.lists)this.lists.hasOwnProperty(b)&&this.lists[b].stop()},reset:function(a){this.timer.reset(a),this.face.reset()},setTime:function(a){this.time.time=a,this.flip(!0)},getTime:function(a){return this.time},setCountdown:function(a){var b=this.running;this.countdown=a?!0:!1,b&&(this.stop(),this.start())},flip:function(a){this.face.flip(!1,a)}})}(jQuery),function(a){"use strict";FlipClock.List=FlipClock.Base.extend({digit:0,classes:{active:"flip-clock-active",before:"flip-clock-before",flip:"flip"},factory:!1,$el:!1,$obj:!1,items:[],lastDigit:0,constructor:function(a,b,c){this.factory=a,this.digit=b,this.lastDigit=b,this.$el=this.createList(),this.$obj=this.$el,b>0&&this.select(b),this.factory.$el.append(this.$el)},select:function(a){if("undefined"==typeof a?a=this.digit:this.digit=a,this.digit!=this.lastDigit){var b=this.$el.find("."+this.classes.before).removeClass(this.classes.before);this.$el.find("."+this.classes.active).removeClass(this.classes.active).addClass(this.classes.before),this.appendListItem(this.classes.active,this.digit),b.remove(),this.lastDigit=this.digit}},play:function(){this.$el.addClass(this.factory.classes.play)},stop:function(){var a=this;setTimeout(function(){a.$el.removeClass(a.factory.classes.play)},this.factory.timer.interval)},createListItem:function(a,b){return['<li class="'+(a?a:"")+'">','<a href="#">','<div class="up">','<div class="shadow"></div>','<div class="inn">'+(b?b:"")+"</div>","</div>",'<div class="down">','<div class="shadow"></div>','<div class="inn">'+(b?b:"")+"</div>","</div>","</a>","</li>"].join("")},appendListItem:function(a,b){var c=this.createListItem(a,b);this.$el.append(c)},createList:function(){var b=this.getPrevDigit()?this.getPrevDigit():this.digit,c=a(['<ul class="'+this.classes.flip+" "+(this.factory.running?this.factory.classes.play:"")+'">',this.createListItem(this.classes.before,b),this.createListItem(this.classes.active,this.digit),"</ul>"].join(""));return c},getNextDigit:function(){return 9==this.digit?0:this.digit+1},getPrevDigit:function(){return 0==this.digit?9:this.digit-1}})}(jQuery),function(a){"use strict";String.prototype.ucfirst=function(){return this.substr(0,1).toUpperCase()+this.substr(1)},a.fn.FlipClock=function(b,c){return new FlipClock(a(this),b,c)},a.fn.flipClock=function(b,c){return a.fn.FlipClock(b,c)}}(jQuery),function(a){"use strict";FlipClock.Time=FlipClock.Base.extend({time:0,factory:!1,minimumDigits:0,constructor:function(a,b,c){"object"!=typeof c&&(c={}),c.minimumDigits||(c.minimumDigits=a.minimumDigits),this.base(c),this.factory=a,b&&(this.time=b)},convertDigitsToArray:function(a){var b=[];a=a.toString();for(var c=0;c<a.length;c++)a[c].match(/^\d*$/g)&&b.push(a[c]);return b},digit:function(a){var b=this.toString(),c=b.length;return b[c-a]?b[c-a]:!1},digitize:function(b){var c=[];if(a.each(b,function(a,b){b=b.toString(),1==b.length&&(b="0"+b);for(var d=0;d<b.length;d++)c.push(b.charAt(d))}),c.length>this.minimumDigits&&(this.minimumDigits=c.length),this.minimumDigits>c.length)for(var d=c.length;d<this.minimumDigits;d++)c.unshift("0");return c},getDateObject:function(){return this.time instanceof Date?this.time:new Date((new Date).getTime()+1e3*this.getTimeSeconds())},getDayCounter:function(a){var b=[this.getDays(),this.getHours(!0),this.getMinutes(!0)];return a&&b.push(this.getSeconds(!0)),this.digitize(b)},getDays:function(a){var b=this.getTimeSeconds()/60/60/24;return a&&(b%=7),Math.floor(b)},getHourCounter:function(){var a=this.digitize([this.getHours(),this.getMinutes(!0),this.getSeconds(!0)]);return a},getHourly:function(){return this.getHourCounter()},getHours:function(a){var b=this.getTimeSeconds()/60/60;return a&&(b%=24),Math.floor(b)},getMilitaryTime:function(a,b){"undefined"==typeof b&&(b=!0),a||(a=this.getDateObject());var c=[a.getHours(),a.getMinutes()];return b===!0&&c.push(a.getSeconds()),this.digitize(c)},getMinutes:function(a){var b=this.getTimeSeconds()/60;return a&&(b%=60),Math.floor(b)},getMinuteCounter:function(){var a=this.digitize([this.getMinutes(),this.getSeconds(!0)]);return a},getTimeSeconds:function(a){return a||(a=new Date),this.time instanceof Date?this.factory.countdown?Math.max(this.time.getTime()/1e3-a.getTime()/1e3,0):a.getTime()/1e3-this.time.getTime()/1e3:this.time},getTime:function(a,b){"undefined"==typeof b&&(b=!0),a||(a=this.getDateObject()),console.log(a);var c=a.getHours(),d=[c>12?c-12:0===c?12:c,a.getMinutes()];return b===!0&&d.push(a.getSeconds()),this.digitize(d)},getSeconds:function(a){var b=this.getTimeSeconds();return a&&(60==b?b=0:b%=60),Math.ceil(b)},getWeeks:function(a){var b=this.getTimeSeconds()/60/60/24/7;return a&&(b%=52),Math.floor(b)},removeLeadingZeros:function(b,c){var d=0,e=[];return a.each(c,function(a,f){b>a?d+=parseInt(c[a],10):e.push(c[a])}),0===d?e:c},addSeconds:function(a){this.time instanceof Date?this.time.setSeconds(this.time.getSeconds()+a):this.time+=a},addSecond:function(){this.addSeconds(1)},subSeconds:function(a){this.time instanceof Date?this.time.setSeconds(this.time.getSeconds()-a):this.time-=a},subSecond:function(){this.subSeconds(1)},toString:function(){return this.getTimeSeconds().toString()}})}(jQuery),function(a){"use strict";FlipClock.Timer=FlipClock.Base.extend({callbacks:{destroy:!1,create:!1,init:!1,interval:!1,start:!1,stop:!1,reset:!1},count:0,factory:!1,interval:1e3,animationRate:1e3,constructor:function(a,b){this.base(b),this.factory=a,this.callback(this.callbacks.init),this.callback(this.callbacks.create)},getElapsed:function(){return this.count*this.interval},getElapsedTime:function(){return new Date(this.time+this.getElapsed())},reset:function(a){clearInterval(this.timer),this.count=0,this._setInterval(a),this.callback(this.callbacks.reset)},start:function(a){this.factory.running=!0,this._createTimer(a),this.callback(this.callbacks.start)},stop:function(a){this.factory.running=!1,this._clearInterval(a),this.callback(this.callbacks.stop),this.callback(a)},_clearInterval:function(){clearInterval(this.timer)},_createTimer:function(a){this._setInterval(a)},_destroyTimer:function(a){this._clearInterval(),this.timer=!1,this.callback(a),this.callback(this.callbacks.destroy)},_interval:function(a){this.callback(this.callbacks.interval),this.callback(a),this.count++},_setInterval:function(a){var b=this;b._interval(a),b.timer=setInterval(function(){b._interval(a)},this.interval)}})}(jQuery),function(a){FlipClock.TwentyFourHourClockFace=FlipClock.Face.extend({constructor:function(a,b){this.base(a,b)},build:function(b){var c=this,d=this.factory.$el.find("ul");this.factory.time.time||(this.factory.original=new Date,this.factory.time=new FlipClock.Time(this.factory,this.factory.original));var b=b?b:this.factory.time.getMilitaryTime(!1,this.showSeconds);b.length>d.length&&a.each(b,function(a,b){c.createList(b)}),this.createDivider(),this.createDivider(),a(this.dividers[0]).insertBefore(this.lists[this.lists.length-2].$el),a(this.dividers[1]).insertBefore(this.lists[this.lists.length-4].$el),this.base()},flip:function(a,b){this.autoIncrement(),a=a?a:this.factory.time.getMilitaryTime(!1,this.showSeconds),this.base(a,b)}})}(jQuery),function(a){FlipClock.CounterFace=FlipClock.Face.extend({shouldAutoIncrement:!1,constructor:function(a,b){"object"!=typeof b&&(b={}),a.autoStart=b.autoStart?!0:!1,b.autoStart&&(this.shouldAutoIncrement=!0),a.increment=function(){a.countdown=!1,a.setTime(a.getTime().getTimeSeconds()+1)},a.decrement=function(){a.countdown=!0;var b=a.getTime().getTimeSeconds();b>0&&a.setTime(b-1)},a.setValue=function(b){a.setTime(b)},a.setCounter=function(b){a.setTime(b)},this.base(a,b)},build:function(){var b=this,c=this.factory.$el.find("ul"),d=this.factory.getTime().digitize([this.factory.getTime().time]);d.length>c.length&&a.each(d,function(a,c){var d=b.createList(c);d.select(c)}),a.each(this.lists,function(a,b){b.play()}),this.base()},flip:function(a,b){this.shouldAutoIncrement&&this.autoIncrement(),a||(a=this.factory.getTime().digitize([this.factory.getTime().time])),this.base(a,b)},reset:function(){this.factory.time=new FlipClock.Time(this.factory,this.factory.original?Math.round(this.factory.original):0),this.flip()}})}(jQuery),function(a){FlipClock.DailyCounterFace=FlipClock.Face.extend({showSeconds:!0,constructor:function(a,b){this.base(a,b)},build:function(b){var c=this,d=this.factory.$el.find("ul"),e=0;b=b?b:this.factory.time.getDayCounter(this.showSeconds),b.length>d.length&&a.each(b,function(a,b){c.createList(b)}),this.showSeconds?a(this.createDivider("Seconds")).insertBefore(this.lists[this.lists.length-2].$el):e=2,a(this.createDivider("Minutes")).insertBefore(this.lists[this.lists.length-4+e].$el),a(this.createDivider("Hours")).insertBefore(this.lists[this.lists.length-6+e].$el),a(this.createDivider("Days",!0)).insertBefore(this.lists[0].$el),this.base()},flip:function(a,b){a||(a=this.factory.time.getDayCounter(this.showSeconds)),this.autoIncrement(),this.base(a,b)}})}(jQuery),function(a){FlipClock.HourlyCounterFace=FlipClock.Face.extend({constructor:function(a,b){this.base(a,b)},build:function(b,c){var d=this,e=this.factory.$el.find("ul");c=c?c:this.factory.time.getHourCounter(),c.length>e.length&&a.each(c,function(a,b){d.createList(b)}),a(this.createDivider("Seconds")).insertBefore(this.lists[this.lists.length-2].$el),a(this.createDivider("Minutes")).insertBefore(this.lists[this.lists.length-4].$el),b||a(this.createDivider("Hours",!0)).insertBefore(this.lists[0].$el),this.base()},flip:function(a,b){a||(a=this.factory.time.getHourCounter()),this.autoIncrement(),this.base(a,b)},appendDigitToClock:function(a){this.base(a),this.dividers[0].insertAfter(this.dividers[0].next())}})}(jQuery),function(a){FlipClock.MinuteCounterFace=FlipClock.HourlyCounterFace.extend({clearExcessDigits:!1,constructor:function(a,b){this.base(a,b)},build:function(){this.base(!0,this.factory.time.getMinuteCounter())},flip:function(a,b){a||(a=this.factory.time.getMinuteCounter()),this.base(a,b)}})}(jQuery),function(a){FlipClock.TwelveHourClockFace=FlipClock.TwentyFourHourClockFace.extend({meridium:!1,meridiumText:"AM",build:function(){var b=this.factory.time.getTime(!1,this.showSeconds);this.base(b),this.meridiumText=this.getMeridium(),this.meridium=a(['<ul class="flip-clock-meridium">',"<li>",'<a href="#">'+this.meridiumText+"</a>","</li>","</ul>"].join("")),this.meridium.insertAfter(this.lists[this.lists.length-1].$el)},flip:function(a,b){this.meridiumText!=this.getMeridium()&&(this.meridiumText=this.getMeridium(),this.meridium.find("a").html(this.meridiumText)),this.base(this.factory.time.getTime(!1,this.showSeconds),b)},getMeridium:function(){return(new Date).getHours()>=12?"PM":"AM"},isPM:function(){return"PM"==this.getMeridium()?!0:!1},isAM:function(){return"AM"==this.getMeridium()?!0:!1}})}(jQuery),function(a){FlipClock.Lang.Arabic={years:"سنوات",months:"شهور",days:"أيام",hours:"ساعات",minutes:"دقائق",seconds:"ثواني"},FlipClock.Lang.ar=FlipClock.Lang.Arabic,FlipClock.Lang["ar-ar"]=FlipClock.Lang.Arabic,FlipClock.Lang.arabic=FlipClock.Lang.Arabic}(jQuery),function(a){FlipClock.Lang.Danish={years:"År",months:"Måneder",days:"Dage",hours:"Timer",minutes:"Minutter",seconds:"Sekunder"},FlipClock.Lang.da=FlipClock.Lang.Danish,FlipClock.Lang["da-dk"]=FlipClock.Lang.Danish,FlipClock.Lang.danish=FlipClock.Lang.Danish}(jQuery),function(a){FlipClock.Lang.German={years:"Jahre",months:"Monate",days:"Tage",hours:"Stunden",minutes:"Minuten",seconds:"Sekunden"},FlipClock.Lang.de=FlipClock.Lang.German,FlipClock.Lang["de-de"]=FlipClock.Lang.German,FlipClock.Lang.german=FlipClock.Lang.German}(jQuery),function(a){FlipClock.Lang.English={years:"Years",months:"Months",days:"Days",hours:"Hours",minutes:"Minutes",seconds:"Seconds"},FlipClock.Lang.en=FlipClock.Lang.English,FlipClock.Lang["en-us"]=FlipClock.Lang.English,FlipClock.Lang.english=FlipClock.Lang.English}(jQuery),function(a){FlipClock.Lang.Spanish={years:"Años",months:"Meses",days:"Días",hours:"Horas",minutes:"Minutos",seconds:"Segundos"},FlipClock.Lang.es=FlipClock.Lang.Spanish,FlipClock.Lang["es-es"]=FlipClock.Lang.Spanish,FlipClock.Lang.spanish=FlipClock.Lang.Spanish}(jQuery),function(a){FlipClock.Lang.Finnish={years:"Vuotta",months:"Kuukautta",days:"Päivää",hours:"Tuntia",minutes:"Minuuttia",seconds:"Sekuntia"},FlipClock.Lang.fi=FlipClock.Lang.Finnish,FlipClock.Lang["fi-fi"]=FlipClock.Lang.Finnish,FlipClock.Lang.finnish=FlipClock.Lang.Finnish}(jQuery),function(a){FlipClock.Lang.French={years:"Ans",months:"Mois",days:"Jours",hours:"Heures",minutes:"Minutes",seconds:"Secondes"},FlipClock.Lang.fr=FlipClock.Lang.French,FlipClock.Lang["fr-ca"]=FlipClock.Lang.French,FlipClock.Lang.french=FlipClock.Lang.French}(jQuery),function(a){FlipClock.Lang.Italian={years:"Anni",months:"Mesi",days:"Giorni",hours:"Ore",minutes:"Minuti",seconds:"Secondi"},FlipClock.Lang.it=FlipClock.Lang.Italian,FlipClock.Lang["it-it"]=FlipClock.Lang.Italian,FlipClock.Lang.italian=FlipClock.Lang.Italian}(jQuery),function(a){FlipClock.Lang.Latvian={years:"Gadi",months:"Mēneši",days:"Dienas",hours:"Stundas",minutes:"Minūtes",seconds:"Sekundes"},FlipClock.Lang.lv=FlipClock.Lang.Latvian,FlipClock.Lang["lv-lv"]=FlipClock.Lang.Latvian,FlipClock.Lang.latvian=FlipClock.Lang.Latvian}(jQuery),function(a){FlipClock.Lang.Dutch={years:"Jaren",months:"Maanden",days:"Dagen",hours:"Uren",minutes:"Minuten",seconds:"Seconden"},FlipClock.Lang.nl=FlipClock.Lang.Dutch,FlipClock.Lang["nl-be"]=FlipClock.Lang.Dutch,FlipClock.Lang.dutch=FlipClock.Lang.Dutch}(jQuery),function(a){FlipClock.Lang.Norwegian={years:"År",months:"Måneder",days:"Dager",hours:"Timer",minutes:"Minutter",seconds:"Sekunder"},FlipClock.Lang.no=FlipClock.Lang.Norwegian,FlipClock.Lang.nb=FlipClock.Lang.Norwegian,FlipClock.Lang["no-nb"]=FlipClock.Lang.Norwegian,FlipClock.Lang.norwegian=FlipClock.Lang.Norwegian}(jQuery),function(a){FlipClock.Lang.Portuguese={years:"Anos",months:"Meses",days:"Dias",hours:"Horas",minutes:"Minutos",seconds:"Segundos"},FlipClock.Lang.pt=FlipClock.Lang.Portuguese,FlipClock.Lang["pt-br"]=FlipClock.Lang.Portuguese,FlipClock.Lang.portuguese=FlipClock.Lang.Portuguese}(jQuery),function(a){FlipClock.Lang.Russian={years:"лет",months:"месяцев",days:"дней",hours:"часов",minutes:"минут",seconds:"секунд"},FlipClock.Lang.ru=FlipClock.Lang.Russian,FlipClock.Lang["ru-ru"]=FlipClock.Lang.Russian,FlipClock.Lang.russian=FlipClock.Lang.Russian}(jQuery),function(a){FlipClock.Lang.Swedish={years:"År",months:"Månader",days:"Dagar",hours:"Timmar",minutes:"Minuter",seconds:"Sekunder"},FlipClock.Lang.sv=FlipClock.Lang.Swedish,FlipClock.Lang["sv-se"]=FlipClock.Lang.Swedish,FlipClock.Lang.swedish=FlipClock.Lang.Swedish}(jQuery),function(a){FlipClock.Lang.Chinese={years:"年",months:"月",days:"日",hours:"时",minutes:"分",seconds:"秒"},FlipClock.Lang.zh=FlipClock.Lang.Chinese,FlipClock.Lang["zh-cn"]=FlipClock.Lang.Chinese,FlipClock.Lang.chinese=FlipClock.Lang.Chinese}(jQuery);
// source --> https://classified.maalz.com/wp-content/themes/listingpro/assets/js/main-new.js?ver=4fca74de5e3fa981b9659807f09e9e55 
jQuery.noConflict();

setTimeout(function () {
    if (jQuery('body').hasClass('home')) {
        var currentTOP = jQuery('.header-container header').height();
        jQuery('.lp-header-search-wrap').css('top', '-' + currentTOP + 'px');
    }


    jQuery(".lp-header-search .lp-header-search-form form, .lp-header-search .lp-header-search-cats ul").show()

}, 600);

jQuery(function () {
    var sidebarHeight = jQuery('.sidebar-top0').height(),
        DesHeight = sidebarHeight - 200,
        topHeader = jQuery('.lp-listing-top-title-header').height(),
        minHeight = jQuery('.min-height-class').height(),
        desHeightT = topHeader + minHeight,
        minHeightT = sidebarHeight - DesHeight;

    if (DesHeight >= sidebarHeight) {

        jQuery('.min-height-class').css('min-height', minHeightT);

    } else {
        minHeightT = sidebarHeight - topHeader + 140;
        jQuery('.min-height-class').css('min-height', minHeightT);

    }
});
jQuery(document).ready(function (e) {
    if (jQuery('.list').hasClass('active')) {
        jQuery('.list').trigger('click');
    }
    if (jQuery('.lp-listing-top-title-header').length) {
        var top_title_header_height = jQuery('.lp-listing-top-title-header').height();
        jQuery('.sidebar-top0').css('top', '-' + parseInt(top_title_header_height + 40) + 'px');
    }

    if (jQuery('#menu-placeholder-image').length) {
        var menu_placeholder_image = jQuery('#menu-placeholder-image').val();
        var menu_chili_image = jQuery('#menu-chili-image').val();

        if (menu_placeholder_image != '') {
            jQuery('.lp-listing-menu-top').css('background', 'url(' + menu_placeholder_image + ')');
        }
        jQuery('.lp-listing-menuu-slide').each(function (index) {
            var $thisSlide = jQuery(this),
                targetImg = $thisSlide.find('img'),
                topImgSrc = '';
            jQuery(targetImg).each(function (imgIndex) {
                var loopImg = jQuery(this),
                    targetSrc = loopImg.attr('src');

                if (targetSrc != menu_placeholder_image && targetSrc != menu_chili_image) {
                    topImgSrc = targetSrc;


                }
            });
            if (topImgSrc != '') {
                $thisSlide.find('.lp-listing-menu-top').css('background', 'url(' + topImgSrc + ')');
            }
        });
    }

    if (jQuery('#datepicker-lang').length) {
        var datepicker_lang = jQuery('#datepicker-lang').val();
        jQuery.datepicker.regional[datepicker_lang];
    }

    if (jQuery('.loop-grid-clearfix').length > 0) {
        jQuery('.loop-grid-clearfix:nth-child(4)').after('<div class="clearfix"></div>');
    }

    jQuery('.claimformtrigger2').click(function () {
        jQuery('.planclaim-page-popup').show();
    })

    jQuery('.lp-review-form-top-multi .lp-review-stars i').click(function (e) {
        if (jQuery('.lp-review-stars').hasClass('do-not-proceed')) {

        } else {
            e.preventDefault();
            jQuery('.lp-review-form-bottom').slideDown(500);
            var ratingNum = jQuery(this).data('rating'),
                colorCode = '#de9147';

            jQuery(this).closest('.lp-review-stars').addClass('do-not-proceed active-rating-avg' + ratingNum);
            jQuery(this).removeClass('fa-star-o').addClass('fa-star');

            jQuery(this).prevAll('.fa-star-o').removeClass('fa-star-o').addClass('fa-star');
            jQuery(this).nextAll('.fa-star').removeClass('fa-star-o').addClass('fa-star-o');

            if (ratingNum == 2) {
                colorCode = '#de9147';
            } else if (ratingNum == 3 || ratingNum == 4) {
                colorCode = '#c5de35';
            } else if (ratingNum == 5) {
                colorCode = '#73cf42';
            }

            jQuery('.lp-multi-rating-ui-wrap > .padding-left-0').each(function () {
                jQuery(this).find('.lp-multi-rating-val').val(ratingNum);
                jQuery(this).find('span:first').each(function () {

                    jQuery(this).addClass('active-stars-wrap');
                    jQuery(this).find('.rating-symbol').each(function (index) {

                        if (index < ratingNum) {
                            jQuery(this).find('.rating-symbol-foreground span').css('color', colorCode);
                            jQuery(this).find('.rating-symbol-foreground span').addClass('fa fa-star fa-2x');
                            jQuery(this).find('.rating-symbol-foreground').css('width', 'auto');
                        }
                    });
                });
            });
        }

    });

    jQuery('.manage-group-types').click(function (e) {
        e.preventDefault();
        window.location.replace(jQuery(this).data('url'));
    });

    jQuery('.show-more-event-content').click(function (e) {

        var showMore = jQuery(this).data('more'),

            showLess = jQuery(this).data('less');
        if (jQuery(this).hasClass('expanded')) {
            jQuery('.lp-evnt-content-container p').css('height', '31px');
            jQuery(this).text(showMore);
            jQuery(this).removeClass('expanded');
        } else {
            jQuery('.lp-evnt-content-container p').height('auto');
            jQuery(this).addClass('expanded');
            jQuery(this).text(showLess);
        }
    });

    jQuery(".header-cat-menu").hover(
        function () {
            jQuery(this).find('#menu-category').addClass("show-cat-nav");
        },
        function () {
            jQuery(this).find('#menu-category').removeClass("show-cat-nav");
        }
    );

    if (jQuery('#lp-submit-form').length != 0) {

        var lp_custom_title = '';
        if (jQuery('#lp_custom_title').length != 0) {
            lp_custom_title = jQuery('#lp_custom_title').offset().top;
        }
        var inputAddress = '';
        if (jQuery('#inputAddress').length != 0) {
            inputAddress = jQuery('#inputAddress').offset().top;
        }
        var inputTagline = '';
        if (jQuery('#lptagline').length != 0) {
            inputTagline = jQuery('#lptagline').offset().top;
        }
        var inputCity = '';
        if (jQuery('#inputCity').length != 0) {
            inputCity = jQuery('#inputCity').offset().top;
        }
        if (jQuery('#citiess').length != 0) {
            inputCity = jQuery('#citiess').offset().top;
        }
        var inputPhone = '';
        if (jQuery('#inputPhone').length != 0) {
            inputPhone = jQuery('label[for="inputPhone"]').offset().top;
        }
        var inputWhatsapp = '';
        if (jQuery('#inputWhatsapp').length != 0) {
            inputWhatsapp = jQuery('label[for="inputWhatsapp"]').offset().top;
        }
        var inputWebsite = '';
        if (jQuery('#inputWebsite').length != 0) {
            inputWebsite = jQuery('#inputWebsite').offset().top;
        }
        var inputCategory = '';
        if (jQuery('label[for="inputCategory"]').length != 0) {
            inputCategory = jQuery('label[for="inputCategory"]').offset().top;
        }
        var price_status = '';
        if (jQuery('label[for="price_status"]').length != 0) {
            price_status = jQuery('label[for="price_status"]').offset().top;
        }
        var bussinTop = '';
        if (jQuery('.bussin-top').length != 0) {
            bussinTop = jQuery('.bussin-top').offset().top;
        }
        var socialMedia = '';
        if (jQuery('#socialMedia').length != 0) {
            socialMedia = jQuery('#socialMedia').offset().top;
        }
        if (jQuery('#get_media').length != 0) {
            socialMedia = jQuery('#get_media').offset().top;
        }
        var get_media_url = '';
        if (jQuery('#get_media_url').length != 0) {
            get_media_url = jQuery('#get_media_url').offset().top;
        }
        var inpuFaqsLp = '';
        if (jQuery('label[for="inpuFaqsLp"]').length != 0) {
            inpuFaqsLp = jQuery('label[for="inpuFaqsLp"]').offset().top;
        }
        var descTop = '';
        if (jQuery('.description-tip').length != 0) {
            descTop = jQuery('.description-tip').offset().top;
        }
        if (jQuery('label[for="inputDescription"]').length != 0) {
            descTop = jQuery('label[for="inputDescription"]').offset().top;
        }
        var postVideo = '';
        if (jQuery('#postVideo').length != 0) {
            postVideo = jQuery('#postVideo').offset().top;
        }
        var gallTop = '';
        if (jQuery('.lp-img-gall-upload-section').length != 0) {
            var gallTop = jQuery('.lp-img-gall-upload-section').offset().top;
        }
        var bLogoTop = '';
        if (jQuery('.b-logo-img-label').length != 0) {
            var bLogoTop = jQuery('.b-logo-img-label').offset().top;
        }
        var featTop = '';
        if (jQuery('.featured-img-label').length != 0) {
            featTop = jQuery('.featured-img-label').offset().top;
        }
        var quicktags = '';
        if (jQuery('#inputtagsquicktip').length > 0) {
            quicktags = jQuery('#inputtagsquicktip').offset().top;
        }
        if (jQuery('#inputTags').length > 0) {
            quicktags = jQuery('#inputTags').offset().top;
        }
        jQuery(window).scroll(function (e) {
            /*if (inputTagline < 400 ) {
             inputTagline = inputTagline+400;
             }*/
            var scrollPos = jQuery(window).scrollTop() + 400;
            if (scrollPos > lp_custom_title) {
                if (jQuery('#lptitle').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#lptitle').data('quick-tip') + '<img alt="image" src="' + jQuery('#lptitle').data('img_src') + '" />');
                }
            }
            /*if (scrollPos > inputTagline) {
             jQuery('.quick-tip-inner').html(jQuery('#lptagline').data('quick-tip'));
             }*/
            if (scrollPos > inputAddress) {
                if (jQuery('#inputAddress').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#inputAddress').data('quick-tip') + '<img alt="image" src="' + jQuery('#inputAddress').data('img_addresssrc') + '" />');
                }
            }
            if (scrollPos > inputCity) {
                if (jQuery('#inputCity').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#inputCity').data('quick-tip') + '<img alt="image" src="' + jQuery('#inputCity').data('cityimg') + '" />');
                } else {
                    jQuery('.quick-tip-inner').html(jQuery('#citiess').data('quick-tip'));
                }
            }
            if (scrollPos > inputPhone) {
                if (jQuery('#inputPhone').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#inputPhone').data('quick-tip') + '<img alt="image" src="' + jQuery('#inputPhone').data('phoneimg') + '" />');
                }
            }
            if (scrollPos > inputWebsite) {
                if (jQuery('#inputWebsite').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#inputWebsite').data('quick-tip') + '<img alt="image" src="' + jQuery('#inputWebsite').data('webimg') + '" />');
                }
            }
            if (scrollPos > inputWhatsapp) {
                if (jQuery('#inputWhatsapp').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#inputWhatsapp').data('quick-tip') + '<img alt="image" src="' + jQuery('#inputWhatsapp').data('whatsappimg') + '" />');
                }
            }
            if (scrollPos > inputCategory) {
                if (jQuery('#inputCategory').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#inputCategory').data('quick-tip') + '<img alt="image" src="' + jQuery('#inputCategory').data('catimg') + '" />');
                }
            }
            if (scrollPos > price_status) {
                if (jQuery('#price_status').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#price_status').data('quick-tip') + '<img alt="image" src="' + jQuery('#price_status').data('priceimg') + '" />');
                }
            }
            if (scrollPos > bussinTop) {
                if (jQuery('.bussin-top').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('.bussin-top').data('quick-tip') + '<img alt="image" src="' + jQuery('.bussin-top').data('hoursimg') + '" />');
                }
            }
            if (scrollPos > socialMedia) {
                if (jQuery('#socialMedia').length != 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#get_media').data('quick-tip') + '<img alt="image" src="' + jQuery('#socialMedia').data('socialimg') + '" />');
                }
            }
            if (scrollPos > inpuFaqsLp) {
                if (jQuery('#inpuFaqsLp').data('quick-tip')) {
                    jQuery('.quick-tip-inner').html(jQuery('#inpuFaqsLp').data('quick-tip') + '<img alt="image" src="' + jQuery('#inpuFaqsLp').data('faqimg') + '" />');
                }
            }
            if (scrollPos > descTop) {
                if (jQuery('.description-tip').length > 0) {
                    jQuery('.quick-tip-inner').html(jQuery('.description-tip').data('quick-tip') + '<img alt="image" src="' + jQuery('.description-tip').data('desimg') + '" />');
                }
            }
            if (scrollPos > quicktags) {
                if (jQuery('#inputTags').length > 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#inputTags').data('quick-tip'));
                } else {
                    jQuery('.quick-tip-inner').html(jQuery('#inputtagsquicktip').data('quick-tip'));
                }
            }
            if (scrollPos > postVideo) {
                if (jQuery('#postVideo').length > 0) {
                    jQuery('.quick-tip-inner').html(jQuery('#postVideo').data('quick-tip') + '<img alt="image" src="' + jQuery('#postVideo').data('videoimg') + '" />');
                }
            }
            if (scrollPos > gallTop) {
                if (jQuery('.lp-img-gall-upload-section').length > 0) {
                    jQuery('.quick-tip-inner').html(jQuery('.lp-img-gall-upload-section').data('quick-tip') + '<img alt="image" src="' + jQuery('.lp-img-gall-upload-section').data('featureimg') + '" />');
                }
            }
            if (scrollPos > bLogoTop) {
                if (jQuery('.b-logo-img-label').length > 0) {
                    jQuery('.quick-tip-inner').html(jQuery('.b-logo-img-label').data('quick-tip') + '<img alt="image" src="' + jQuery('.b-logo-img-label').data('blogoimg') + '" />');
                }
            }
            if (scrollPos > featTop) {
                if (jQuery('.featured-img-label').length > 0) {
                    jQuery('.quick-tip-inner').html(jQuery('.featured-img-label').data('quick-tip') + '<img alt="image" src="' + jQuery('.featured-img-label').data('featureimg') + '" />');
                }
            }
        });

        jQuery('#lp-submit-form input, #lp-submit-form textarea').on('focus', function (e) {
            var quickTip,
                $this = jQuery(this);

            if ($this.attr('id') == 'lptitle') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#lptitle').data('img_src') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'inputAddress') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#inputAddress').data('img_addresssrc') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'inputCity') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#inputCity').data('cityimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'inputPhone') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#inputPhone').data('phoneimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'inputWhatsapp') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#inputWhatsapp').data('whatsappimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'inputWebsite') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#inputWebsite').data('webimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'listingprice') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#price_status').data('priceimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'listingptext') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#price_status').data('priceimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'inpuFaqsLp') {
                quickTip = $this.data('quick-tip');

                if (quickTip == 'undefined' || quickTip == '' || quickTip == null) {
                    jQuery('.quick-tip-inner').html('');
                } else {
                    quickTip = quickTip + '<img alt="image" src="' + jQuery('#inpuFaqsLp').data('faqimg') + '" />';
                    jQuery('.quick-tip-inner').html(quickTip);
                }
            }

            if ($this.attr('id') == 'inputDescriptionFaq') {
                quickTip = $this.data('quick-tip');
                if (quickTip == 'undefined' || quickTip == '' || quickTip == null) {
                    jQuery('.quick-tip-inner').html('');
                } else {
                    quickTip = quickTip + '<img alt="image" src="' + jQuery('#inpuFaqsLp').data('faqimg') + '" />';
                    jQuery('.quick-tip-inner').html(quickTip);
                }
            }

            if ($this.attr('id') == 'postVideo') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#postVideo').data('videoimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }


        });

        jQuery('#price_status').on('chosen:showing_dropdown', function () {
            var quickTip = jQuery(this).data('quick-tip') + '<img alt="image" src="' + jQuery('#price_status').data('priceimg') + '" />';
            jQuery('.quick-tip-inner').html(quickTip);
        });

        jQuery('.b-logo-img-label, .featured-img-label, .lplistgallery').on('click', function () {
            var $this = jQuery(this);

            if ($this.hasClass('lplistgallery')) {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('.lp-img-gall-upload-section').data('featureimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.hasClass('b-logo-img-label')) {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('.b-logo-img-label').data('blogoimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.hasClass('featured-img-label')) {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('.featured-img-label').data('featureimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

        });
        jQuery('select.select2').on('select2:open', function (e) {

            var $this = jQuery(this);

            if ($this.attr('id') == 'inputCategory') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#inputCategory').data('catimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'get_media') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#get_media').data('socialimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

            if ($this.attr('id') == 'socialMedia') {
                quickTip = $this.data('quick-tip') + '<img alt="image" src="' + jQuery('#socialMedia').data('socialimg') + '" />';
                jQuery('.quick-tip-inner').html(quickTip);
            }

        });

    }

    if (jQuery('.page-style2-sidebar').length != 0) {

        var scrollState = '';

        var offset = jQuery('.page-style2-sidebar').offset().top - 50;

        jQuery(window).scroll(function (event) {

            var scroll = jQuery(window).scrollTop();

            if (offset >= scroll) {

                jQuery('.page-style2-sidebar').css({

                    'position': 'static',

                    'width': 'auto'

                });

                jQuery('.page-style2-sidebar').removeClass('style2-sidebar-fixed');
                scrollState = 'scrolled';
            } else {
                var topMAr = 10;
                if (jQuery('.page-style2-sidebar').hasClass('logged-in')) {
                    topMAr = 50;
                }
                if (scrollState == 'scrolled') {

                    // jQuery('.page-style2-sidebar').css({

                    //     'position':'fixed',

                    //     'top' : topMAr+'px',

                    //     'width': '338px'

                    // });

                    // jQuery('.page-style2-sidebar').css({
                    //
                    //     'position':'fixed',
                    //
                    //     'top' : 0,
                    //
                    //     'width': '338px'
                    //
                    // }).animate({
                    //
                    //     top: -150
                    //
                    // }, 250, function () {
                    //
                    //     jQuery('.page-style2-sidebar').animate({
                    //
                    //         top: 200
                    //
                    //     }, 250, function () {
                    //
                    //         jQuery('.page-style2-sidebar').animate({
                    //
                    //             top: -100
                    //
                    //         }, 300, function () {
                    //
                    //             jQuery('.page-style2-sidebar').animate({
                    //
                    //                 top: 100
                    //
                    //             }, 300, function () {
                    //
                    //                 jQuery('.page-style2-sidebar').animate({
                    //
                    //                     top: -50
                    //
                    //                 }, 350, function () {
                    //
                    //                     jQuery('.page-style2-sidebar').animate({
                    //
                    //                         top: topMAr
                    //
                    //                     }, 400)
                    //
                    //                 })
                    //
                    //             })
                    //
                    //         });
                    //
                    //     })
                    //
                    // })

                    jQuery('.page-style2-sidebar').addClass('style2-sidebar-fixed testClass');
                    scrollState = '';
                }

            }

        });

    }
    var firstDay = jQuery('#start_of_weekk').val();
    if (jQuery('#event-date-s').length) {
        var dateTodayy = new Date();
        jQuery('#event-date-s').datepicker({
            firstDay: firstDay,
            minDate: dateTodayy,
            dateFormat: 'mm/dd/yy',
            onSelect: function (dateText, inst) {
                // Get the selected date
                var inDate = new Date(jQuery(this).val());
                // Set the minimum date for the check out option to the selected date
                jQuery("#event-date-e").datepicker('option', 'minDate', inDate);
            }
        });
        jQuery('#event-date-e').datepicker({
            firstDay: firstDay,
            minDate: dateTodayy,
            dateFormat: 'mm/dd/yy'
        });
    }

    var dateToday = new Date();
    jQuery('.discount-date').datepicker({
        firstDay: firstDay,
        minDate: dateToday,
        dateFormat: 'mm/dd/yy'
    });


    jQuery('.mobile-toggle-filters').click(function (e) {

        e.preventDefault();

        jQuery('.filters-wrap-for-mobile').slideToggle(500);

    });


    jQuery('#lp-review-listing').on('select2:select', function (e) {

        var reviewStyle = jQuery('#reviews-nav-li').data('style'),
            listID = jQuery('#lp-review-listing option:selected').val(),
            authorID = jQuery('.lp-author-nav').data('author');

        jQuery('#reviews').find('.author-inner-content-wrap').addClass('content-loading');
        jQuery.ajax({
            type: 'POST',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'author_review_tab_cb',
                'reviewStyle': reviewStyle,
                'listID': listID,
                'authorID': authorID,
                'lpNonce': jQuery('#lpNonce').val()
            },

            success: function (data) {
                jQuery('#reviews').find('.author-inner-content-wrap').removeClass('content-loading');
                jQuery('#reviews').find('.author-inner-content-wrap').html(data);

                //$this.addClass('data-available');

            }

        });

    })

    jQuery('.lp-author-nav li a').click(function (e) {

        e.preventDefault();

        var $this = jQuery(this),
            targetID = $this.attr('href'),
            authorID = jQuery('.lp-author-nav').data('author'),
            tabType = '',
            reviewStyle = '',
            listingLayout = '';


        if (targetID == '#reviews') {
            tabType = 'reviews';
            var reviewStyle = $this.data('style');
        } else if (targetID == '#photos') {
            tabType = 'photos';
        } else if (targetID == '#aboutme') {
            tabType = 'aboutme';
        } else if (targetID == '#contact') {
            tabType = 'contact';
        } else if (targetID == '#mylistings') {
            tabType = 'mylistings';
            listingLayout = $this.data('listing-layout');
        }

        jQuery('.lp-author-nav li a.active').removeClass('active');
        $this.addClass('active');

        jQuery('.author-tab-content .active').removeClass('active').hide();
        jQuery(targetID).addClass('active').show();

        if ($this.hasClass('data-available')) {
            return false;
        } else {
            jQuery(targetID).find('.author-inner-content-wrap').addClass('content-loading');

            jQuery.ajax({
                type: 'POST',
                url: ajax_search_term_object.ajaxurl,
                data: {
                    'action': 'author_archive_tabs_cb',
                    'tabType': tabType,
                    'reviewStyle': reviewStyle,
                    'authorID': authorID,
                    'listingLayout': listingLayout,
                    'lpNonce': jQuery('#lpNonce').val()
                },
                success: function (data) {
                    jQuery(targetID).find('.author-inner-content-wrap').removeClass('content-loading');
                    jQuery(targetID).find('.author-inner-content-wrap').html(data);
                    $this.addClass('data-available');
                    jQuery('.author-contact-wrap').find('.lp-review-btn').attr('disabled', 'disabled');
                    jQuery('.author-contact-wrap input, .author-contact-wrap textarea').keyup(function () {
                        var name = jQuery('.author-contact-wrap input#name7').val();
                        var email = jQuery('.author-contact-wrap input#email7').val();
                        var phone = jQuery('.author-contact-wrap input#phone7').val();
                        var message = jQuery('.author-contact-wrap textarea#message7').val();
                        if (name.length > 0 && email.length > 0 && phone.length > 0 && message.length > 0) {
                            jQuery('.author-contact-wrap').find('.lp-review-btn').removeAttr('disabled');
                        } else {
                            jQuery('.author-contact-wrap').find('.lp-review-btn').attr('disabled', 'disabled');
                        }
                    });
                    jQuery('.author-contact-wrap .lp-review-btn').click(function (event) {
                        event.preventDefault();
                        var $this = jQuery(this),
                            name = jQuery('.author-contact-wrap input#name7').val(),
                            email = jQuery('.author-contact-wrap input#email7').val(),
                            phone = jQuery('.author-contact-wrap input#phone7').val(),
                            message = jQuery('.author-contact-wrap textarea#message7').val(),
                            target_user_mail = jQuery('.mail_target_author').val();
                        jQuery('.author-contact-wrap').find('.lp-review-btn').attr('disabled', 'disabled');
                        jQuery('.author-contact-wrap').find('.lp-review-btn').closest('.form-group').find('.lp-search-icon').removeClass('fa-send');
                        jQuery('.author-contact-wrap').find('.lp-review-btn').closest('.form-group').find('.lp-search-icon').addClass('fa-spinner fa-spin');
                        jQuery('.author-contact-wrap input, .author-contact-wrap textarea').attr('disabled', 'disabled');
                        jQuery.ajax({
                            type: 'POST',
                            url: ajax_search_term_object.ajaxurl,
                            data: {
                                'action': 'send_author_mail',
                                'field-name': name,
                                'field-email': email,
                                'field-phone': phone,
                                'field-message': message,
                                'data-userMail': target_user_mail,
                                'lpNonce': jQuery('#lpNonce').val()
                            },
                            success: function (data) {
                                jQuery('.author-contact-wrap').find('.lp-review-btn').closest('.form-group').find('.lp-search-icon').addClass('fa-check');
                                jQuery('.author-contact-wrap').find('.lp-review-btn').closest('.form-group').find('.lp-search-icon').removeClass('fa-spinner fa-spin');
                                setTimeout(function () {
                                    jQuery('.author-contact-wrap').find('.lp-review-btn').removeAttr('disabled');
                                    jQuery('.author-contact-wrap input, .author-contact-wrap textarea').removeAttr('disabled');
                                    jQuery('.author-contact-wrap input#name7').val('');
                                    jQuery('.author-contact-wrap input#email7').val('');
                                    jQuery('.author-contact-wrap input#phone7').val('');
                                    jQuery('.author-contact-wrap textarea#message7').val('');
                                    jQuery('.author-contact-wrap').find('.lp-review-btn').closest('.form-group').find('.lp-search-icon').addClass('fa-send');
                                    jQuery('.author-contact-wrap').find('.lp-review-btn').closest('.form-group').find('.lp-search-icon').removeClass('fa-check');
                                }, 2000);
                            },
                        });
                        return false;
                    });
                }
            });
        }
    });


    jQuery('.author-inner-content-wrap .lp-pagination span').click(function (e) {

        var $this = jQuery(this);
        var pageNum = jQuery(this).data('pageurl');

        jQuery('span.current').removeClass('current');
        jQuery('#content-grids').html('').addClass('content-loading');


        jQuery.ajax({
            type: 'POST',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'author_archive_listings_cb',
                'pageNum': pageNum,
                'lpNonce': jQuery('#lpNonce').val()

            },
            success: function (data) {
                $this.addClass('current');
                jQuery('#content-grids').removeClass('content-loading').html(data);
            }
        });


    });

    jQuery('.lp-header-nav-btn button').click(function (e) {

        if (jQuery('.lp-header-nav-btn').hasClass('active-can-menu')) {

            jQuery('.lp-header-nav-btn').removeClass('active-can-menu');

            jQuery('#menu-categories-menu').css('opacity', '0');

            jQuery('#menu-categories-menu').css('transform', 'scale(0)');

        } else {

            jQuery('#menu-categories-menu').css('opacity', '1');

            jQuery('#menu-categories-menu').css('transform', 'scale(1)');

            jQuery('.lp-header-nav-btn').addClass('active-can-menu');

        }

    });


    jQuery('.browse-imgs').click(function (e) {

        e.preventDefault();
        jQuery('#filer_input2').trigger('click');

    });


    jQuery('.search-filter-response .loop-switch-class').last().find('.lp-listing').addClass('last');

    jQuery('.lp-author-listings-wrap .loop-switch-class').last().find('.lp-listing').addClass('last');

    jQuery('.lp-listing-announcement .announcement-wrap').last().addClass('last');


    jQuery('.lp-review-form-top-multi .lp-listing-stars, .lp-review-images .browse-imgs, .lp-review-form-top-multi .lp-review-stars').click(function (e) {
        if (jQuery('.lp-review-form-bottom').hasClass('review-form-opened')) {
        } else {
            jQuery('.lp-review-form-bottom').slideDown(500);
            jQuery('.lp-review-form-bottom').addClass('review-form-opened');
        }

    });

    // jQuery('.lp-listing-stars').click(function(e){

    //     jQuery('.lp-review-form-bottom').slideToggle(500);

    // })

    var topWidgetWrap = jQuery('.lp-widget-inner-wrap').first();

    var lastWidgetWrap = jQuery('.lp-widget-inner-wrap').last();


    if (topWidgetWrap.hasClass('lp-listing-timings')) {

        topWidgetWrap.find('.lp-today-timing').addClass('top-border-radius');

    } else {

        topWidgetWrap.addClass('top-border-radius');

    }

    if (lastWidgetWrap.hasClass('lp-listing-timings')) {

        lastWidgetWrap.find('.lp-today-timing').addClass('bottom-border-radius');

    } else if (lastWidgetWrap.hasClass('singlemap')) {

        jQuery('.lp-widget-social-links').addClass('bottom-border-radius');

    } else {

        lastWidgetWrap.addClass('bottom-border-radius');

    }

    // if( jQuery('.dis-code-copy-pop').length != 0 )
    //
    // {
    //     jQuery('.dis-code-copy-pop').each(function (e) {
    //
    //         var minusBottom =   0;
    //         if( jQuery(this).hasClass('extra-bottom') )
    //         {
    //             minusBottom =   49;
    //         }
    //         var $this       =   jQuery(this),
    //             popHeight   =   $this.height()-minusBottom;
    //
    //
    //         $this.css('bottom', '-'+popHeight+'px');
    //
    //         $this.attr('bottom', popHeight);
    //     });
    //
    // }


    jQuery('.lp-dis-code-copy span').click(function (e) {

        var targetCodeEL = jQuery(this).data('target-code'),

            targetCodeELC = '.' + targetCodeEL;


        var copyCode = jQuery(targetCodeELC).find('strong.copycode').text();


        jQuery(targetCodeELC).find('input.codtopcopy').val(copyCode).select();

        document.execCommand("copy");

        jQuery(this).html('<i class="fa fa-files-o" aria-hidden="true"></i> copied').delay(1000).show(500, function (e) {

            jQuery(targetCodeELC).fadeOut();

            jQuery('.code-overlay').fadeOut();

        });


    });


    jQuery('.close-copy-code').click(function (e) {

        e.preventDefault();

        var targetCodeEL = jQuery(this).data('target-code'),

            targetCodeELC = '.' + targetCodeEL;


        jQuery(targetCodeELC).fadeOut();

        jQuery('.code-overlay').fadeOut();

    });

    jQuery(document).on('click', '.header-more-filters .lp_all_page_overflow_after', function () {
        jQuery('.lp-header-search-filters .header-more-filters').removeClass('hide-filters');
    });
    jQuery(document).on('click', '.more-filters', function () {
        jQuery('.lp-header-search-filters .header-more-filters').toggleClass('hide-filters');
    });


    function toggleIcon(e) {


        jQuery(e.target)

            .prev('.faq-heading')

            .find(".more-less")

            .toggleClass('glyphicon-plus glyphicon-minus');


    }

    // jQuery('.faq-heading a').on('click',function(e){

    //     jQuery( '.collapse.in.faq-answer' ).collapse('hide');

    // });

    slickINIT();

    if (jQuery('.listing-slider').length != 0) {

        jQuery('.listing-slider').slick({

            infinite: true,

            slidesToShow: 3,

            slidesToScroll: 3,

            prevArrow: "<i class=\"fa fa-angle-right arrow-left\" aria-hidden=\"true\"></i>",

            nextArrow: "<i class=\"fa fa-angle-left arrow-right\" aria-hidden=\"true\"></i>",

            responsive: [

                {

                    breakpoint: 768,

                    settings: {

                        slidesToShow: 1,

                        slidesToScroll: 1,

                        infinite: true

                    }

                }

            ]

        });

        jQuery('.lp-listings .listing-slider').show();

    }


    // slickINIT();

    // jQuery('.single-tabber2 ul li a').click(function (e) {
    //
    //     var menuCheck   =   jQuery(this).attr('href');
    //     if( menuCheck == '#menu_tab' )
    //     {
    //         slickINIT();
    //     }
    //
    // });


    if (jQuery('.lp-child-cats-tax-slider').length != 0) {

        var chilCatsLoc = jQuery('.lp-child-cats-tax-slider').data('child-loc'),

            childCatNum = 3;

        if (chilCatsLoc == 'fullwidth') {

            childCatNum = 5;

        }

        if (jQuery('.lp-child-cats-tax-wrap').length > childCatNum) {
            jQuery('.lp-child-cats-tax-slider').slick({

                infinite: true,

                slidesToShow: childCatNum,

                slidesToScroll: 1,

                prevArrow: "<i class=\"fa fa-angle-right arrow-left\" aria-hidden=\"true\"></i>",

                nextArrow: "<i class=\"fa fa-angle-left arrow-right\" aria-hidden=\"true\"></i>"

            });
        }

    }

    if (jQuery('.events-sidebar-wrap').length) {
        var eventsNum = jQuery('.events-sidebar-wrap').data('num');

        if (eventsNum > 1) {
            jQuery('.events-sidebar-wrap').slick({
                infinite: true,
                slidesToShow: 1,
                slidesToScroll: 1,
                prevArrow: "<i class=\"fa fa-angle-right arrow-left\" aria-hidden=\"true\"></i>",
                nextArrow: "<i class=\"fa fa-angle-left arrow-right\" aria-hidden=\"true\"></i>",
                adaptiveHeight: true
            });
        }
    }
    if (jQuery('.events-content-area-wrap').length) {
        function listingdetailpageevenslider() {
            var eventsNum = jQuery('.events-content-area-wrap').data('num');
            if (eventsNum > 2) {
                jQuery('.events-content-area-wrap').slick({
                    infinite: true,
                    slidesToShow: 2,
                    slidesToScroll: 1,
                    prevArrow: "<i class=\"fa fa-angle-right arrow-left\" aria-hidden=\"true\"></i>",
                    nextArrow: "<i class=\"fa fa-angle-left arrow-right\" aria-hidden=\"true\"></i>"
                });
            }
        }

        listingdetailpageevenslider();
        jQuery(document).on('click', '.lp-detailpage2-events-tab:not(.worked)', function () {
            if (jQuery('.events-content-area-wrap').hasClass('slick-initialized')) {
                jQuery('.events-content-area-wrap').slick('destroy');
                listingdetailpageevenslider();
            } else {
                listingdetailpageevenslider();
            }
            jQuery(this).addClass('worked');
        });
    }
    if (jQuery('.events-element-content-area-wrap').length) {
        var eventsNum = jQuery('.events-element-content-area-wrap').data('num');

        if (eventsNum > 3) {
            jQuery('.events-content-area-wrap').slick({
                infinite: true,
                slidesToShow: 3,
                slidesToScroll: 1,
                prevArrow: "<i class=\"fa fa-angle-right arrow-left\" aria-hidden=\"true\"></i>",
                nextArrow: "<i class=\"fa fa-angle-left arrow-right\" aria-hidden=\"true\"></i>"
            });
        }
    }

    if (jQuery('.app-view-new-ads-slider').length) {
        jQuery('.app-view-new-ads-slider').slick({
            infinite: true,
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: false,
            autoplay: true
        });
    }
    if (jQuery('.app-view2-banner-cat-slider').length) {
        jQuery('.app-view2-banner-cat-slider').slick({
            infinite: true,
            slidesToShow: 4,
            slidesToScroll: 1,
            arrows: false,
            dots: false,
        });
    }
    if (jQuery('.app-view2-location-container').length) {
        jQuery('.app-view2-location-container').slick({
            infinite: true,
            slidesToShow: 3,
            slidesToScroll: 1,
            arrows: false,
            dots: false
        });
    }

    if (jQuery('.lp-locations-slider').length != 0 && jQuery('.lp-locations-slider .lp-location-box').length > 6) {
        jQuery('.lp-locations-slider').slick({

            infinite: true,

            slidesToShow: 6,

            slidesToScroll: 1,

            nextArrow: "<i class=\"fa fa-angle-right arrow-left\" aria-hidden=\"true\"></i>",

            prevArrow: "<i class=\"fa fa-angle-left arrow-right\" aria-hidden=\"true\"></i>",
            responsive: [

                {
                    breakpoint: 480,
                    settings: {
                        arrows: true,
                        centerMode: false,
                        centerPadding: '0px',
                        slidesToShow: 2
                    }
                }
            ]

        });

    }
    jQuery('.sort-by-filter').hover(function (e) {

        e.preventDefault();


        if (jQuery(this).hasClass('active-tooltip-filter')) {

            return false;

        }

        jQuery('.active-tooltip-filter').find('.sort-filter-inner').fadeOut(200);

        jQuery('.active-tooltip-filter').removeClass('active-tooltip-filter');

        jQuery(this).addClass('active-tooltip-filter');

        jQuery(this).find('.sort-filter-inner').fadeIn(200);

    })

    jQuery('body').click(function (e) {


        if (e.target.id == "header-rated-filter" || e.target.id == "header-reviewed-filter" || e.target.id == "header-viewed-filter")

            return;

        if (jQuery('.sort-filter-inner').is(":visible")) {

            jQuery('.sort-filter-inner').fadeOut(200);

        }

        jQuery('.active-tooltip-filter').removeClass('active-tooltip-filter');

    });

    // jQuery('.listing-toggle-btn').click(function(e)

    // {

    //     e.preventDefault();

    //     if( !jQuery(this).hasClass('active') )

    //     {

    //         var targetView  =   jQuery(this).data('view');

    //         jQuery('.listing-toggle-btn').removeClass('active');

    //         jQuery(this).addClass('active');

    //

    //

    //         if( targetView == 'grid-style' )

    //         {

    //             jQuery('.loop-switch-class').removeClass('col-md-12');

    //             jQuery('.loop-switch-class').addClass('col-md-6');

    //             jQuery('.lp-listings.active-view').removeClass('list-style');

    //             jQuery('.lp-listings.active-view').addClass('grid-style');

    //         }

    //         if( targetView == 'list-style' )

    //         {

    //             jQuery('.loop-switch-class').removeClass('col-md-6');

    //             jQuery('.loop-switch-class').addClass('col-md-12');

    //             jQuery('.lp-listings.active-view').addClass('list-style');

    //             jQuery('.lp-listings.active-view').removeClass('grid-style');

    //

    //         }

    //

    //     }

    //

    // });

    jQuery('.listing-view-layout ul li a').click(function (e) {

        e.preventDefault();

        var $this = jQuery(this),

            targetView = '';

        if ($this.hasClass('list')) {

            targetView = 'list-style';

        }

        if ($this.hasClass('grid')) {

            targetView = 'grid-style';

        }

        if (targetView == 'grid-style') {

            jQuery('.loop-switch-class').removeClass('col-md-12');

            jQuery('.loop-switch-class').addClass('col-md-6');
            jQuery('.loop-switch-class.listing-style-1').removeClass('col-md-6');
            jQuery('.loop-switch-class.listing-style-1').addClass('col-md-4');

            jQuery('.lp-listings.active-view').removeClass('list-style');

            jQuery('.lp-listings.active-view').addClass('grid-style');

        }

        if (targetView == 'list-style') {

            jQuery('.loop-switch-class').removeClass('col-md-6');
            jQuery('.loop-switch-class.listing-style-1').removeClass('col-md-4');

            jQuery('.loop-switch-class').addClass('col-md-12');

            jQuery('.lp-listings.active-view').addClass('list-style');

            jQuery('.lp-listings.active-view').removeClass('grid-style');


        }


    });


    if (jQuery('.lp-listing-slider').length != 0) {

        var totalSlides = jQuery('.lp-listing-slider').attr('data-totalSlides'),

            slidesToShow = 3;

        if (totalSlides == 1) {

            slidesToShow = 1;

        }

        if (totalSlides == 2) {

            slidesToShow = 2;

        }

        jQuery('.lp-listing-slider').slick({

            infinite: true,

            slidesToShow: slidesToShow,

            slidesToScroll: 1,

            //new code 2.6.15
            prevArrow: "<i class=\"fa fa-angle-left arrow-right\" aria-hidden=\"true\"></i>",

            nextArrow: "<i class=\"fa fa-angle-right arrow-left\" aria-hidden=\"true\"></i>",

            //end new code 2.6.15
            responsive: [{
                breakpoint: 480,
                settings: {
                    arrows: true,
                    centerMode: false,
                    centerPadding: '0px',
                    slidesToShow: 2
                }
            }]

        });


        jQuery('.lp-listing-slider').show();

    }

    if (jQuery('.listing-review-slider').length != 0) {
        var totalSlieds = jQuery('.listing-review-slider').attr('data-review-thumbs');
        jQuery('.listing-review-slider').slick({
            infinite: true,
            slidesToShow: 4,
            slidesToScroll: 1,
            prevArrow: "<i class=\"fa fa-angle-right arrow-left\" aria-hidden=\"true\"></i>",
            nextArrow: "<i class=\"fa fa-angle-left arrow-right\" aria-hidden=\"true\"></i>"

        });
    }


    jQuery('.btn-link-field-toggle').click(function (e) {

        var dataTargetLink = jQuery(this).data('target-link');


        jQuery('.btn-link-target').slideToggle(300);

        jQuery(this).toggleClass('link-active');


        var targetSwitch = 'input#' + dataTargetLink;

        jQuery(targetSwitch).val('');

    });


    jQuery('.review-form-toggle, .lp-listing-review-form h2').click(function (e) {
        e.preventDefault();
        jQuery('.lp-listing-review-form .lp-form-opener').hide();

        jQuery('.lp-listing-review-form').find('i.fa-chevron-down, i.fa-chevron-up').toggleClass('fa-chevron-down fa-chevron-up');
        jQuery('.lp-review-form-bottom').slideToggle(500);
        jQuery('html,body').animate(
            {

                scrollTop: jQuery(".lp-listing-review-form").offset().top - 100

            },

            'slow');

    });

    jQuery('.lp-see-menu-btn').click(function (e) {

        e.preventDefault();

        jQuery('html,body').animate(
            {

                scrollTop: jQuery(".lp-listing-menuu-wrap").offset().top - 120

            },

            'slow');

    })


    jQuery('.toggle-all-days').click(function (e) {
        e.preventDefault();
        var leftColHeight = jQuery('.min-height-class').height(),
            timingsIH = jQuery('.lp-listing-timings').height();

        jQuery('.lp-today-timing.all-days-timings').slideToggle(200).toggleClass('days-opened');
        var lessText = jQuery(this).data('contract');
        var moreText = jQuery(this).data('expand');
        setTimeout(function () {
            var isOpened = jQuery('.lp-today-timing.all-days-timings').is('.days-opened');

            if (isOpened === true) {
                var timingsOH = jQuery('.lp-listing-timings').height(),
                    leftColHeightN = leftColHeight + timingsOH;
                jQuery('.min-height-class').css('min-height', leftColHeightN + 'px');
                jQuery('.toggle-all-days').html('<i class="fa fa-minus" aria-hidden="true"></i> ' + lessText);
            } else {
                var leftColHeightN = leftColHeight - timingsIH;
                jQuery('.min-height-class').css('min-height', leftColHeightN + 'px');
                jQuery('.toggle-all-days').html('<i class="fa fa-plus" aria-hidden="true"></i> ' + moreText);
            }
        }, 150);

    });


    jQuery('.toggle-all-days2').click(function (e) {
        e.preventDefault();
        var leftColHeight = jQuery('.min-height-class').height(),
            timingsIH = jQuery('.lp-listing-timings').height();
        jQuery('.lp-today-timing.all-days-timings').slideToggle(200).toggleClass('days-opened');
        setTimeout(function () {
            var isOpened = jQuery('.lp-today-timing.all-days-timings').is('.days-opened');
            if (isOpened === true) {
                var timingsOH = jQuery('.lp-listing-timings').height(),
                    leftColHeightN = leftColHeight + timingsOH;
                jQuery('.min-height-class').css('min-height', leftColHeightN + 'px');
            } else {
                var leftColHeightN = leftColHeight - timingsIH;
                jQuery('.min-height-class').css('min-height', leftColHeightN + 'px');
            }
        }, 150);
    });

    jQuery('.toggle-additional-details').click(function (e) {
        e.preventDefault();
        jQuery('.additional-detail-hidden').slideToggle(200).toggleClass('details-opened');

        var lessText = jQuery(this).data('contract');
        var moreText = jQuery(this).data('expand');

        var leftColHeight = jQuery('.min-height-class').height(),
            additoinalIH = jQuery('.lp-listing-additional-details').height();

        setTimeout(function () {
            var isOpened = jQuery('.additional-detail-hidden').is('.details-opened');
            if (isOpened === true) {
                var additoinalOH = jQuery('.lp-listing-additional-details').height(),
                    leftColHeightN = (leftColHeight + additoinalOH) - 360;

                jQuery('.min-height-class').css('min-height', leftColHeightN + 'px');
                jQuery('.toggle-additional-details').html('<i class="fa fa-minus" aria-hidden="true"></i> ' + lessText);
            } else {
                var leftColHeightN = (leftColHeight - additoinalIH) + 360;
                jQuery('.min-height-class').css('min-height', leftColHeightN + 'px');

                jQuery('.toggle-additional-details').html('<i class="fa fa-plus" aria-hidden="true"></i> ' + moreText);
            }
        }, 150);

    });


    jQuery('.lp-listing-faqs').on('hidden.bs.collapse', toggleIcon);

    jQuery('.lp-listing-faqs').on('shown.bs.collapse', toggleIcon);


    jQuery(document).on('click', '.add-to-fav-v2', function (e) {

        e.preventDefault()

        $this = jQuery(this);

        $this.find('i').addClass('fa-spin fa-spinner');

        var val = jQuery(this).data('post-id');

        var type = jQuery(this).data('post-type');


        jQuery.ajax({

            type: 'POST',

            dataType: 'json',

            url: ajax_search_term_object.ajaxurl,

            data: {

                'action': 'listingpro_add_favorite_v2',

                'post-id': val,

                'type': type,
                'lpNonce': jQuery('#lpNonce').val()

            },

            success: function (data) {

                if (data) {

                    if (data.active == 'yes') {

                        $this.find('i').removeClass('fa-spin fa-spinner');

                        if (data.type == 'grid' || data.type == 'list') {

                            $this.find('i').removeClass('fa-heart-o');

                            $this.find('i').addClass('fa-heart');

                        } else {

                            var successText = $this.data('success-text');

                            $this.find('span').text(successText);

                            $this.html('<i class="fa fa-bookmark" aria-hidden="true"></i> ' + data.text);

                        }

                        $this.removeClass('add-to-fav-v2');

                        $this.addClass('remove-fav-v2');

                    }

                }

            }

        });

    });


    jQuery(document).on('click', '.remove-fav-v2', function (e) {

        e.preventDefault();

        var val = jQuery(this).data('post-id');

        var type = jQuery(this).data('post-type');

        jQuery(this).find('i').removeClass('fa-close');

        jQuery(this).find('i').addClass('fa-spinner fa-spin');


        $this = jQuery(this);

        jQuery.ajax({

            type: 'POST',

            dataType: 'json',

            url: ajax_search_term_object.ajaxurl,

            data: {

                'action': 'listingpro_remove_favorite_v2',

                'post-id': val,

                'type': type,
                'lpNonce': jQuery('#lpNonce').val()

            },

            success: function (data) {

                if (data) {

                    if (data.remove == 'yes') {
                        $this.find('i').removeClass('fa-spin fa-spinner');

                        if (data.type == 'grid' || data.type == 'list') {
                            $this.find('i').addClass('fa-heart-o');
                        } else {
                            $this.html('<i class="fa-regular fa-bookmark-o" aria-hidden="true"></i> ' + data.text);
                        }
                        if (jQuery('.page-template-template-favourites').length != 0) {
                            $this.closest(".lp-grid-box-contianer").fadeOut();
                        }
                        $this.removeClass('remove-fav-v2');

                        $this.addClass('add-to-fav-v2');

                    }

                }

            }

        });


    });


    /* Social Share */

    var social = jQuery('.lp-listing-action-btns ul li div.social-icons.post-socials');

    var socialOvrly = jQuery('.lp-listing-action-btns ul li .md-overlay');


    jQuery('.lp-single-sharing').on('click', function (event) {

        event.preventDefault();

        social.fadeIn(400);


        if (socialOvrly.hasClass('hide')) {

            jQuery(socialOvrly).removeClass('hide');

            jQuery(socialOvrly).addClass('show');

        } else {

            jQuery(socialOvrly).removeClass('show');

            jQuery(socialOvrly).addClass('hide');


        }

    });


    socialOvrly.on('click', function (event) {


        event.preventDefault();

        social.hide();


        if (socialOvrly.hasClass('show')) {

            jQuery(socialOvrly).removeClass('show');

            jQuery(socialOvrly).addClass('hide');

        } else {

            jQuery(socialOvrly).removeClass('hide');

            jQuery(socialOvrly).addClass('show');

        }

    });


    jQuery(document).on('click', '.lp-review-right-bottom .review-reaction, .lp-activity-description .review-reaction', function (e) {
        e.preventDefault();
        if (jQuery(this).hasClass('active-now')) {
            return false;
        }
        reviewID = '';

        ajaxResErr = '';

        var $this = jQuery(this);

        $this.addClass('active-now');

        reviewID = $this.data('id'),

            currentVal = $this.data('score'),

            restype = $this.data('restype');


        $this.find('span.react-count').html('<i class="fa fa-spinner fa-spin"></i>');

        jQuery.ajax({

            type: 'POST',

            dataType: 'json',

            url: ajax_review_object.ajaxurl,

            data: {

                action: 'lp_reviews_interests',

                interest: currentVal,

                restype: restype,

                id: reviewID,
                'lpNonce': jQuery('#lpNonce').val()

            },


            success: function (res) {


                if (res.errors == "no") {

                    ajaxResErr = 'no';

                    var newscore = res.newScore;

                    $this.data('score', newscore);

                    $this.find('span.react-count').html(newscore);

                    $this.find('span.react-msg').text(res.statuss).fadeIn(500).delay(2000).fadeOut(500);


                    if (restype == 'interesting') {

                        $this.css({
                            'background-color': '#417cdf',

                            'color': '#fff'
                        });

                        $this.find('span.react-count').css({ 'color': '#fff' });

                    } else if (restype == 'lol') {

                        $this.css({
                            'background-color': '#ff8e29',

                            'color': '#fff'
                        });

                        $this.find('span.react-count').css({ 'color': '#fff' });

                    } else if (restype == 'love') {

                        $this.css({
                            'background-color': '#ff2357',

                            'color': '#fff'
                        });

                        $this.find('span.react-count').css({ 'color': '#fff' });

                    }

                    currentVal = false;

                } else {

                    ajaxResErr = 'yes';

                    var newscore = res.newScore;

                    $this.find('span.react-count').text(newscore);

                    $this.find('span.react-msg').text(res.statuss).fadeIn(500).delay(2000).fadeOut(500);

                }

                $this.removeClass('active-now');

            },

            error: function (request, error) {

                alert(error);

            }

        });


        e.preventDefault();

    });

    jQuery(document).on('click', '#add-menu-image_btn', function (e) {
        e.preventDefault();
        var $this = jQuery(this);
        var userID = $this.data('uid'),
            img_Url = jQuery(this).closest('.add-menu_image').find('#selected_image_menu_url').val(),
            selected_list_Id = jQuery('#add_image_menu').val();

        if ((selected_list_Id == '0') || (img_Url == '')) {
            $this.closest('.add-menu_image').append('<p class="add_img_menu_error">Something Went Wrong</p>');
            return false;
        }
        jQuery('#add-menu-img-spinner').show();
        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'add_image_menu',
                'userID': userID,
                'img_Url': img_Url,
                'selected_list_Id': selected_list_Id,
                'lpNonce': jQuery('#lpNonce').val()
            },
            success: function (res) {
                jQuery('.add_img_menu_error').remove();
                $this.closest('.ordering-service-wrap').find('ul.listing_append_img_menu').append('<li class="clearfix"><a class="pull-left online_ordring_list_title" target="_blank" href="' + res.selected_list_Link + '">' + res.selected_list_Title + '</a><span data-uid="' + userID + '" data-target="' + selected_list_Id + '" class="pull-right del_img_menu"><i class="fa fa-trash fa-spinner"></i></span></li>');
                jQuery('.add-new-service_img_menu .jFiler-input-choose-btn').text('Browse File');
                jQuery('#add-menu-img-spinner').hide();
                $this.closest('.add-menu_image').find('#selected_image_menu_url').val('');
                $this.closest('.add-menu_image').find('#selected_image_menu_url').text('Select Listing');
                jQuery('#add_image_menu').val('');
                jQuery('.no-img_menu').hide();
            },

            error: function (err) {
                alert(err);
                jQuery('#add-menu-img-spinner').hide();
            }
        });
    });
    jQuery(document).on('click', '.add-menu_image .jFiler-input-choose-btn', function () {
        jQuery('#selected_image_menu_url').val('');
    });
    jQuery(document).on('click', '.del_img_menu', function (e) {
        e.preventDefault();
        var $this = jQuery(this);
        var userID = $this.data('uid'),
            target = $this.data('target');
        $this.find('i.fa-spinner').removeClass('fa-trash');
        $this.find('i.fa-spinner').addClass('fa-spin');
        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'del_add_image_menu',
                'userID': userID,
                'target': target,
                'lpNonce': jQuery('#lpNonce').val()
            },
            success: function (res) {
                console.log(res);
                $this.closest("li").remove();
                // jQuery('#add-menu-img-spinner').hide();
            },

            error: function (err) {
                alert(err);
                // jQuery('#add-menu-img-spinner').hide();
            }
        });
    });


    jQuery(document).on('click', '.lp-edit-menu', function (e) {

        e.preventDefault();

        var $this = jQuery(this),
            userID = $this.data('uid'),
            LID = $this.data('lid'),
            menuID = $this.data('menuid'),
            mTitle = jQuery('#menu-title-' + menuID).val(),
            mDetail = jQuery('#menu-detail-' + menuID).val(),
            mOldPrice = jQuery('#menu-old-price-' + menuID).val(),
            mNewPrice = jQuery('#menu-new-price-' + menuID).val(),
            mQuoteT = jQuery('#menu-quote-text-' + menuID).val(),
            mQuoteL = jQuery('#menu-quote-link-' + menuID).val(),
            mLink = jQuery('#menu-link-' + menuID).val(),
            mGroup = jQuery('#menu-group-' + menuID).val(),
            mType = jQuery('#menu-type-' + menuID).val(),
            mImage = jQuery('.edit-upload-' + menuID + ' .frontend-input').val(),
            multipleImage = jQuery('.upload-field.dashboard-upload-field.edit-upload-' + menuID).data('multiple');
        sItem = jQuery('#lp-menus').data('sitem');
        sPrice = jQuery('#lp-menus').data('sprice');

        if (jQuery('.frontend-input-multiple').length > 0 && multipleImage === true) {
            mImage = jQuery('.edit-upload-' + menuID + ' .frontend-input-multiple').val();
        }
        popularItem = '';

        if (jQuery('.menu_Popular_Item-' + menuID).is(':checked')) {
            popularItem = 'mItemPopularTrue';
        } else {
            popularItem = 'mItemPopularfalse';
        }
        var spiceLVL = jQuery('.menuSpice-control-' + menuID + ' option:selected').data('level');
        if (spiceLVL == '1') {
            spiceLVL = 'spicelvl1';
        } else if (spiceLVL == '2') {
            spiceLVL = 'spicelvl2';
        } else if (spiceLVL == '3') {
            spiceLVL = 'spicelvl3';
        } else if (spiceLVL == '4') {
            spiceLVL = 'spicelvl4';
        } else {
            spiceLVL = 'spicelvlunset';
        }

        $this.append('<i class="fa fa-spin fa-spinner"></i>');

        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'add_menu_cb',
                'user_id': userID,
                'LID': LID,
                'menuID': menuID,
                'mTitle': mTitle,
                'mDetail': mDetail,
                'mOldPrice': mOldPrice,
                'mNewPrice': mNewPrice,
                'mQuoteT': mQuoteT,
                'mQuoteL': mQuoteL,
                'mLink': mLink,
                'mImage': mImage,
                'mType': mType,
                'mGroup': mGroup,
                'popularItem': popularItem,
                'spiceLVL': spiceLVL,
                'menuUp': 'yes',
                'lpNonce': jQuery('#lpNonce').val()
            },
            success: function (res) {
                var menu_id = $this.data('menuid');
                // alert(menu_id);
                // ajax_success_popup( res, $this );
                console.log(res);
                jQuery('.active-update-formm').slideUp();
                $this.find('i').remove();
                jQuery('#menu-update-' + menuID).closest('.lp-menu-close-outer').find('.lp-menu-closed').find('h4.lp-right-side-title').html('<span>' + sItem + '</span><br>' + mTitle);
                jQuery('#menu-update-' + menuID).closest('.lp-menu-close-outer').find('.lp-menu-closed').find('.col-md-2.price').html('<span>' + sPrice + '</span><br>' + mOldPrice);
            },

            error: function (err) {
                alert(err);
                $this.find('i').remove();
            }
        });
    });
    if (jQuery('#selected_image_menu_url').length != 0) {
        jQuery(document).on('click', function (e) {
            var jqhiddeninputfeild = jQuery('#selected_image_menu_url').val();
            var jqtriggerforcheck = jQuery('#selected_image_menu_url').hasClass('.frontend-input-multiple');
            if (jqtriggerforcheck = true) {
                var asd = jQuery('.add-new-service_img_menu .jFiler-input-choose-btn').text();
                if (jqhiddeninputfeild != '') {
                    var lastFive = jqhiddeninputfeild.substr(jqhiddeninputfeild.length - 13);
                    var finalcom = '...' + lastFive;
                    if (asd != finalcom) {
                        var string = finalcom.substr(0, 15);
                        jQuery('.add-new-service_img_menu .jFiler-input-choose-btn').text(string);
                        return false;
                    }
                }
            }
        });
    }

    jQuery(function () {
        jQuery(document).on('change', '.coupons-fields-switch input[type="checkbox"]', function (e) {
            var targetID = jQuery(this).data('target');
            if (targetID == 'quote-button') {
                if (jQuery(this).is(':checked')) {
                    jQuery('#menu-old-price').val('');
                    jQuery('#menu-new-price').val('');
                    jQuery('#menu-quote-text').val('');
                    jQuery('#menu-quote-link').val('');
                }
            }
        });
    });
    jQuery(document).on('click', '#lp-save-menu', function (e) {
        e.preventDefault();
        var $this = jQuery(this),
            userID = $this.data('uid'),
            mTitle = jQuery('#menu-title').val(),
            mDetail = jQuery('#menu-detail').val(),
            mOldPrice = jQuery('#menu-old-price').val(),
            mNewPrice = jQuery('#menu-new-price').val(),
            mQuoteT = jQuery('#menu-quote-text').val(),
            mQuoteL = jQuery('#menu-quote-link').val(),
            mListing = jQuery('#menu-listing').val(),
            mLink = jQuery('#menu-link').val(),
            mImage = jQuery('.new-file-upload .frontend-input').val(),
            mType = jQuery('#lp-menus .panel-heading li.active').text(),
            mGroup = jQuery('#menu-group').val(),
            orderP = '',
            orderU = '',
            calcPrice = '',
            popularItem = '';

        sItem = jQuery('#lp-menus').data('sitem');
        sGroup = jQuery('#lp-menus').data('sgroup');
        sPrice = jQuery('#lp-menus').data('sprice');
        sEdit = jQuery('#lp-menus').data('sedit');
        sDelete = jQuery('#lp-menus').data('sdelete');
        sQuote = jQuery('#lp-menus').data('squote');
        sLink = jQuery('#lp-menus').data('slink');
        sRprice = jQuery('#lp-menus').data('srprice');
        sSprice = jQuery('#lp-menus').data('ssprice');
        sMitem = jQuery('#lp-menus').data('smitem');
        sDesc = jQuery('#lp-menus').data('sdesc');
        sPop = jQuery('#lp-menus').data('spop');
        sSpice = jQuery('#lp-menus').data('sspice');
        sCancel = jQuery('#lp-menus').data('scancel');
        sSave = jQuery('#lp-menus').data('ssave');
        sPexquote = jQuery('#lp-menus').data('spexquote');
        sPprice = jQuery('#lp-menus').data('spprice');
        sPtitle = jQuery('#lp-menus').data('sptitle');
        sUrl = jQuery('#lp-menus').data('surl');

        if (jQuery('.menu_Popular_Item').is(':checked')) {
            popularItem = 'mItemPopularTrue';
        } else {
            popularItem = 'mItemPopularfalse';
        }

        if (jQuery('.menu_Popular_Item').is(':checked')) {
            popularItem = 'mItemPopularTrue';
        } else {
            popularItem = 'mItemPopularfalse';
        }
        var spiceLVL = jQuery('.menuSpice-control option:selected').data('level');
        if (spiceLVL == '1') {
            spiceLVL = 'spicelvl1';
        } else if (spiceLVL == '2') {
            spiceLVL = 'spicelvl2';
        } else if (spiceLVL == '3') {
            spiceLVL = 'spicelvl3';
        } else if (spiceLVL == '4') {
            spiceLVL = 'spicelvl4';
        } else {
            spiceLVL = 'spicelvlunset';
        }

        if (mNewPrice.length > 0) {
            calcPrice = mNewPrice;
        } else {
            calcPrice = mOldPrice;
        }
        if (mImage == '' && jQuery('.new-file-upload .frontend-input-multiple').length != 0) {
            mImage = jQuery('.new-file-upload .frontend-input-multiple').val();
        }

        if (mListing == '' || mListing == null || mListing == 0) {
            jQuery('#select2-menu-listing-container').addClass('error');
            jQuery('#menu-listing').addClass('error');
        } else {
            jQuery('#select2-menu-listing-container').removeClass('error');
            jQuery('#menu-listing').removeClass('error');
        }
        if (mTitle == '') {
            jQuery('#menu-title').addClass('error');
        } else {
            jQuery('#menu-title').removeClass('error');
        }
        if (mDetail == '') {
            jQuery('#menu-detail').addClass('error');
        } else {
            jQuery('#menu-detail').removeClass('error');
        }
        if (mType == '' || mType == 0 || mType == null) {
            jQuery('select#menu-type').next('.select2-container').addClass('error');
        } else {
            jQuery('select#menu-type').next('.select2-container').removeClass('error');
        }
        if (mGroup == '' || mGroup == 0 || mGroup == null) {
            jQuery('select#menu-group').next('.select2-container').addClass('error');
        } else {
            jQuery('select#menu-group').next('.select2-container').removeClass('error');
        }
        if (mDetail == '' || mTitle == '' || (mType == '' && mType == 0 || mType == null) || (mGroup == '' && mGroup == 0 || mGroup == null) || mListing == '' || mListing == null || mListing == 0) {
            var dataError = [];
            dataError.status = 'error';
            dataError.msg = jQuery('.lp-notifaction-area').data('error-msg');
            ajax_success_popup(dataError, $this);
            return false;
        }
        var QpriceTog = false;
        if (jQuery('.coupons-fields-switch input[type="checkbox"]').is(':checked')) {
            QpriceTog = true;
        }
        $this.append('<i class="fa fa-spin fa-spinner"></i>');
        $this.attr('disabled', 'disabled');
        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'add_menu_cb',
                'user_id': userID,
                'mTitle': mTitle,
                'mDetail': mDetail,
                'mOldPrice': mOldPrice,
                'mNewPrice': mNewPrice,
                'mQuoteT': mQuoteT,
                'mQuoteL': mQuoteL,
                'mListing': mListing,
                'mLink': mLink,
                'mImage': mImage,
                'mType': mType,
                'mGroup': mGroup,
                'orderP': orderP,
                'orderU': orderU,
                'popularItem': popularItem,
                'spiceLVL': spiceLVL,
                'showQute': QpriceTog,
                'lpNonce': jQuery('#lpNonce').val()
            },
            success: function (res) {
                jQuery('.lp-menu-close-outer').prepend('<input type="hidden" id="lp-showQOrP" value="' + QpriceTog + '">');
                if (res.menu_after_update[mType][mGroup]) {
                    var menuLength = parseInt(res.menu_after_update[mType][mGroup].length - 1);
                } else {
                    location.reload(true);
                }
                jQuery('#menu-group').val(null).trigger('change');
                var type_rep = mType.replace(/ /g, '-');
                var grp_rep = mGroup[0].replace(/ /g, '-');
                var listid = mListing;
                var menu_id = type_rep + '_' + grp_rep + '_' + menuLength + '_' + listid;
                var regmQuoteT = '';
                var mQuoteLinK = '';
                var $menu_price_check = '';
                if (jQuery('#lp-showQOrP').val() == 'true') {
                    regmQuoteT = '<div class="col-sm-6">' +
                        '<label class="lp-dashboard-top-label" for="menu-quote-text-' + menu_id + '">Quote Text</label>' +
                        '<input id="menu-quote-text-' + menu_id + '"     type="text"   class="form-control lp-dashboard-text-field"    value="' + mQuoteT + '"    placeholder="Ex: Quote">' +
                        '</div>';
                    mQuoteLinK = '<div class="col-sm-6">' +
                        '<label class="lp-dashboard-top-label" for="menu-quote-link-' + menu_id + '">Quote Link</label>' +
                        '<input id="menu-quote-link-' + menu_id + '"           type="text"          class="form-control lp-dashboard-text-field"            value="' + mQuoteL + '"              placeholder="Ex: hht://yourweb.com/page">' +
                        '</div>';
                }
                if (jQuery('#lp-showQOrP').val() == 'false') {
                    $menu_price_check = '<div class="menu-price-wrap">' +
                        '<div class="col-sm-2 padding-left-0">' +
                        '<label class="lp-dashboard-top-label" for="menu-old-price-' + menu_id + '">Reg. Price</label>' +
                        '<input name="menu-old-price-' + menu_id + '"  id="menu-old-price-' + menu_id + '"  type="text" class="form-control lp-dashboard-text-field" placeholder="Ex: $10" value="' + mOldPrice + '">' +
                        '</div>' +
                        '<div class="col-sm-2 padding-left-0">' +
                        '<label class="lp-dashboard-top-label" for="menu-new-price-' + menu_id + '">Sale Price</label>' +
                        '<input id="menu-new-price-' + menu_id + '"  name="menu-new-price-' + menu_id + '"  type="text"  class="form-control lp-dashboard-text-field"  placeholder="Ex: $10"  value="' + mNewPrice + '">' +
                        '</div>' +
                        '</div>';
                }
                var checkedpoP = '';
                if (popularItem == 'mItemPopularTrue') {
                    checkedpoP = 'checked';
                }
                var selected_spicelvl1 = '';
                var selected_spicelvl2 = '';
                var selected_spicelvl3 = '';
                var selected_spicelvl4 = '';

                if (spiceLVL == 'spicelvl1') {
                    selected_spicelvl1 = 'selected';
                } else if (spiceLVL == 'spicelvl2') {
                    selected_spicelvl2 = 'selected';
                } else if (spiceLVL == 'spicelvl3') {
                    selected_spicelvl3 = 'selected';
                } else if (spiceLVL == 'spicelvl4') {
                    selected_spicelvl4 = 'selected';
                }
                var imagedivvar = '';
                if (mImage != '') {
                    imagedivvar = '<div class="menu-edit-img-wrap gal-img-count-single">' +
                        '<span data-src="' + mImage + '" data-target="dis-old-img-' + menu_id + '" class="remove-menu-img"><i class="fa fa-close"></i></span>' +
                        '<img class="gal-img-count-single lp-uploaded-img event-old-img-' + menu_id + '" src="' + mImage + '" alt="image">' +
                        '</div>';
                }

                var html = '<div class="lp-menu-close-outer">' +
                    '<div class="lp-menu-closed clearfix ">' +
                    '<div class="row">' +
                    '<div class="col-md-6"><i class="fa fa-check-circle fa-check-circle2" aria-hidden="true"></i><h4 class="lp-right-side-title"><span>' + sItem + '</span><br>' + mTitle + '</h4></div>' +
                    '<div class="col-md-2"><span>' + sGroup + '</span><br>' + mGroup + '</div>' +
                    '<div class="col-md-2 price"><span>' + sPrice + '</span><br>' + calcPrice + '</div>' +
                    '<div class="col-md-2"><span class="lp-dot-extra-buttons"><i class="fa fa-ellipsis-v" aria-hidden="true"></i>' +
                    '<ul class="lp-user-menu list-style-none">' +
                    '<li><a class="edit-menu-item" data-menuID="' + menu_id + '" data-uid="' + userID + '" href=""><i class="fa fa-pencil" aria-hidden="true"></i><span>' + sEdit + '</span></a></li>' +
                    '<li><a href="" class="menu-del del-this" data-LID="' + mListing + '" data-targetid="' + menu_id + '" data-uid="' + userID + '"><i class="fa fa-trash" aria-hidden="true"></i><span>' + sDelete + '</span></a></li>' +
                    '</ul>' +
                    '</span></div>' +
                    '</div>' +
                    '</div>' +
                    '<div id="menu-update-' + menu_id + '" class="lp-menu-form-outer background-white" style="display: none">' +
                    '<div class="lp-menu-form-inner">' +
                    '<form class="row">' +
                    '<input value="' + mType + '" type="hidden" id="menu-type-' + menu_id + '" name="menu-type-' + menu_id + '">' +
                    '<input type="hidden" value="' + mGroup + '" id="menu-group-' + menu_id + '" name="menu-group-' + menu_id + '">' +
                    '<div class="col-sm-12 margin-top-10">' +
                    '<div class="lp-menu-form-feilds">' +
                    '<div class="row clearfix">' +
                    '<div class="col-md-12">' +
                    '<div class="row">' +
                    '<div class="margin-bottom-10 col-md-8">' +
                    '<label class="lp-dashboard-top-label" for="menu-title-' + menu_id + '">' + sMitem + '</label>' +
                    '<input name="menu-title-' + menu_id + '"  id="menu-title-' + menu_id + '"  type="text"  class="form-control lp-dashboard-text-field" placeholder="' + sPtitle + '" value="' + mTitle + '">' +
                    '</div>' + $menu_price_check +
                    '<div class="menu-quote-wrap clearfix margin-bottom-20">' +
                    regmQuoteT +
                    mQuoteLinK +
                    '</div>' +
                    '</div>' +
                    '<div class="margin-bottom-30">' +
                    '<label class="lp-dashboard-top-label" for="menu-detail-' + menu_id + '">' + sDesc + '</label>' +
                    '<textarea name="menu-detail-' + menu_id + '" id="menu-detail-' + menu_id + '" type="text" class="form-control lp-dashboard-des-field" rows="3" placeholder="' + sPtitle + '">' + mDetail + '</textarea>' +
                    '</div>' +
                    '</div>' +


                    '<div class="lp-invoices-all-stats-on-off clearfix margin-bottom-10 Popular_item_container">' +
                    '<label class="switch">' +
                    '<input ' + checkedpoP + ' value="Yes" class="form-control switch-checkbox menu_Popular_Item-' + menu_id + '" type="checkbox" name="lp_form_fields_inn[235]">' +
                    '<div class="slider round"></div>' +
                    '</label>' +
                    '<span class="margin-left-10" style="font-size: 16px!important;font-weight: normal!important;">' + sPop + '</span>' +
                    '</div>' +
                    '<div class="clearfix margin-bottom-10 menuSpice-control_containter">' +
                    '<select style="width: 100%!important;margin-left: 0;" id="menuSpice-control" class="form-control menuSpice-control-' + menu_id + '">' +
                    '<option>' + sSpice + '</option>' +


                    '<option data-level="1" ' + selected_spicelvl1 + ' >🌶</option>' +
                    '<option data-level="2" ' + selected_spicelvl2 + ' >🌶🌶</option>' +
                    '<option data-level="3" ' + selected_spicelvl3 + ' >🌶🌶🌶</option>' +

                    '</select>' +
                    '</div>' +

                    '<div class="col-md-12">' +
                    '<div class="jFiler-input-dragDrop pos-relative event-featured-image-wrap-dash">' +
                    '<div class="upload-field dashboard-upload-field edit-upload-' + menu_id + '">' +
                    '<input class="frontend-input-multiple" type="hidden" id="dis-old-img-' + menu_id + '" value="' + mImage + '">' +
                    '<input type="hidden" value="' + mImage + '" class="frontend-input" name="frontend_input"><label><a class="jFiler-input-choose-btn blue">Browse File</a><input class="frontend-button" type="button" value="" style="position: relative; z-index: 1;"> </label><div class="clearfix"></div><img class="frontend-image" alt="image">    ' +
                    '<div class= "menu-edit-imgs-wrap" >' +
                    imagedivvar +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +

                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div class="clearfix"></div>' +
                    '<div class="lp-menu-save-btns clearfix col-md-12 margin-bottom-20">' +
                    '<button class="lp-cancle-btn cancel-update-menu">' + sCancel + '</button>' +
                    '<button data-LID="' + mListing + '" data-menuID="' + menu_id + '"  data-uid="' + userID + '"  class="lp-save-btn lp-edit-menu">' + sSave + '</button>' +
                    '</div>' +
                    '</form>' +
                    '</div>' +
                    '</div>' +
                    '<div>';
                jQuery('.panel-body.lp-panel-body-outer.lp-menu-panel-body-outer .tab-content.lp-tab-content-outer .tab-pane.fade.in.active').append(html);
                $this.find('i.fa.fa-spin.fa-spinner').remove();
                $this.removeAttr('disabled');


                jQuery('.menu-edit-imgs-wrap .frontend-input-multiple').val('');
                $this.closest('#menu-form-toggle').find('.lp-menu-close-outer.lp-menu-open').slideUp();
                $this.attr('id', 'lp-save-menu-reopen');
                jQuery('#menu-title').val('');
                jQuery('#menu-detail').val('');
                jQuery('#menu-old-price').val('');
                jQuery('#menu-new-price').val('');
                jQuery('#menu-quote-text').val('');
                jQuery('#menu-quote-link').val('');
                jQuery('#menu-link').val('');
                jQuery('.new-file-upload .frontend-input').val('');
                jQuery('.new-file-upload .frontend-image').hide('slow');
            },
            error: function (err) {
                console.log(err);
                $this.find('i').remove();
                $this.removeAttr('disabled');
                var dataError = [];
                dataError.status = 'error';
                dataError.msg = jQuery('.lp-notifaction-area').data('error-msg');
                ajax_success_popup(dataError, $this);
            }
        });
    });

    jQuery('.add-new-open-form').click(function (e) {
        e.preventDefault();
        var targetForm = '#' + jQuery(this).data('form') + '-form-toggle';
        jQuery('div.panel.with-nav-tabs.panel-default.lp-dashboard-tabs.col-md-11').fadeOut("fast", function () {
            jQuery(targetForm).fadeIn("fast", function () {
                jQuery(".lp-blank-section").fadeOut();
            });
        });
    });
    jQuery('.lp-blank-section .add-new-open-form').click(function (e) {
        e.preventDefault();
        var targetForm = '#' + jQuery(this).data('form') + '-form-toggle';
        jQuery(targetForm).fadeIn("fast", function () {
            jQuery(".lp-blank-section").fadeOut();
        });
    });
    var targetPlanMetaKey = 'menu';
    if (jQuery('.select2-ajax').length != 0) {
        targetPlanMetaKey = jQuery('.select2-ajax').data('metakey');

        var noResultsText = jQuery('#select2-ajax-noresutls').val(),
            inputShortText = jQuery('#select2-ajax-tooshort').val(),
            searchingText = jQuery('#select2-ajax-searching').val();
    }

    jQuery('.select2-ajax').select2({
        ajax: {
            url: ajax_search_term_object.ajaxurl,
            dataType: 'json',
            type: 'GET',
            data: function (params) {
                return {
                    q: params.term, // search query
                    targetPlanMetaKey: targetPlanMetaKey,
                    action: 'select2_ajax_dashbaord_listing' // AJAX action for admin-ajax.php
                };
            },
            processResults: function (data) {
                var options = [];
                var disabled_opts = false;
                if (data) {

                    // data is the array of arrays, and each of them contains ID and the Label of the option
                    jQuery.each(data, function (index, text) { // do not forget that "index" is just auto incremented value
                        var disabled_opts = false;
                        if (text[2] == 'yes') {
                            disabled_opts = true;
                        }
                        options.push({ id: text[0], text: text[1], disabled: disabled_opts });
                    });

                }
                return {
                    results: options
                };
            },
            cache: true
        },
        minimumInputLength: 3,
        language: {
            inputTooShort: function () {
                return inputShortText;
            },
            noResults: function () {
                return noResultsText;
            },
            searching: function () {
                return searchingText;
            }
        }
    });


    /* for campaigns */
    if (jQuery('.select2-ajaxx').length != 0) {
        var noResultsText = jQuery('#select2-ajax-noresutls').val(),
            inputShortText = jQuery('#select2-ajax-tooshort').val(),
            searchingText = jQuery('#select2-ajax-searching').val();
    }
    jQuery('.lp-search-listing-camp').select2({
        ajax: {
            url: ajax_search_term_object.ajaxurl,
            dataType: 'json',
            type: 'GET',
            data: function (params) {
                return {
                    q: params.term, // search query
                    action: 'select2_ajax_dashbaord_listing_camp' // AJAX action for admin-ajax.php
                };
                console.log(params);
            },
            processResults: function (data) {
                var options = [];
                if (data) {

                    // data is the array of arrays, and each of them contains ID and the Label of the option
                    jQuery.each(data, function (index, text) { // do not forget that "index" is just auto incremented value
                        options.push({ id: text[0], text: text[1] });
                    });

                }
                return {
                    results: options
                };
            },
            cache: true
        },
        minimumInputLength: 3,
        language: {
            inputTooShort: function () {
                return inputShortText;
            },
            noResults: function () {
                return noResultsText;
            },
            searching: function () {
                return searchingText;
            }
        }
    });
    /* end for camp */

    var uniqueMetaKey = 'event_id';
    var planmetakey = 'events';
    if (jQuery('.select2-ajax-unique').length != 0) {
        uniqueMetaKey = jQuery('.select2-ajax-unique').data('metakey');
        planmetakey = jQuery('.select2-ajax-unique').data('planmetakey');

        var noResultsText = jQuery('#select2-ajax-noresutls').val(),
            inputShortText = jQuery('#select2-ajax-tooshort').val(),
            searchingText = jQuery('#select2-ajax-searching').val();
    }

    jQuery('.select2-ajax-unique').select2({
        ajax: {
            url: ajax_search_term_object.ajaxurl,
            dataType: 'json',
            type: 'GET',
            data: function (params) {
                return {
                    q: params.term, // search query
                    uniqueMetaKey: uniqueMetaKey,
                    planmetakey: planmetakey,
                    action: 'select2_ajax_dashbaord_listing_unique' // AJAX action for admin-ajax.php
                };
            },
            processResults: function (data) {
                var options = [];
                if (data) {

                    // data is the array of arrays, and each of them contains ID and the Label of the option
                    jQuery.each(data, function (index, text) { // do not forget that "index" is just auto incremented value
                        var disabled_opts = false;
                        if (text[2] == 'yes') {
                            disabled_opts = true;
                        }

                        options.push({ id: text[0], text: text[1], disabled: disabled_opts });
                    });

                }
                return {
                    results: options
                };
            },
            cache: true
        },
        minimumInputLength: 3,
        language: {
            inputTooShort: function () {
                return inputShortText;
            },
            noResults: function () {
                return noResultsText;
            },
            searching: function () {
                return searchingText;
            }
        }
    });

    jQuery('#ad-announcement-btn').on('click', function (e) {
        e.preventDefault();
        var $this = jQuery(this),
            userID = $this.data('uid'),
            annMsg = jQuery('#announcements-message').val(),
            annBT = jQuery('#announcements-btn-text').val(),
            annBL = jQuery('#announcements-btn-link').val(),
            annLI = jQuery('#announcements-listing').val(),
            annSt = jQuery('#ann-style').find(':selected').val(),
            annIC = jQuery('#announcements-icon').val(),
            annType = '',
            annTI = jQuery('#announcements-title').val();

        if (annIC != '') {
            var annType = jQuery('#announcements-icon').attr('icon-type');
        }

        if (annLI == 0 || annLI == '' || annLI == null) {
            jQuery('#select2-announcements-listing-container').addClass('error');
            jQuery('#announcements-listing').addClass('error');
        } else {
            jQuery('#select2-announcements-listing-container').removeClass('error');
            jQuery('#announcements-listing').removeClass('error');
        }
        if (annMsg == '') {
            jQuery('#announcements-message').addClass('error');
        } else {
            jQuery('#announcements-message').removeClass('error');
        }
        if (annTI == '') {
            jQuery('#announcements-title').addClass('error');
        } else {
            jQuery('#announcements-title').removeClass('error');
        }

        if (annLI == 0 || annLI == '' || annTI == '' || annMsg == '' || annLI == 0 || annLI == '' || annLI == null) {
            var dataError = [];
            dataError.status = 'error';
            dataError.msg = jQuery('.lp-notifaction-area').data('error-msg');
            ajax_success_popup(dataError, $this);
            $this.find('i').remove();
            return false;
        }
        if ($this.hasClass('processing-ann')) {
        } else {
            $this.append('<i class="fa fa-spin fa-spinner"></i>');
            $this.addClass('processing-ann');

            jQuery.ajax({
                type: 'POST',
                dataType: 'json',
                url: ajax_search_term_object.ajaxurl,
                data: {
                    'action': 'add_announcements_cb',
                    'user_id': userID,
                    'annSt': annSt,
                    'annMsg': annMsg,
                    'annBT': annBT,
                    'annBL': annBL,
                    'annLI': annLI,
                    'annTI': annTI,
                    'annIC': annIC,
                    'annType': annType,
                    'lpNonce': jQuery('#lpNonce').val()
                },
                success: function (res) {
                    ajax_success_popup(res, $this);
                },

                error: function (err) {
                    $this.find('i').remove();
                }
            });
        }


    });


    jQuery('#ann-style').on('change', function (e) {

        var $this = jQuery(this),

            $thisDes = $this.find(':selected').attr('data-des'),

            $thisTI = $this.find(':selected').attr('data-title'),

            $thisIC = $this.find(':selected').attr('data-icon'),

            $thisBT = $this.find(':selected').text(),

            $thisST = $this.find(':selected').attr('data-st');


        jQuery('.announcement-wrap span').text($thisDes);
        jQuery('#announcements-message').attr('placeholder', $thisDes);
        jQuery('.announcement-wrap a').text($thisBT);
        jQuery('.announcement-wrap strong').text($thisTI);
        jQuery('#announcements-btn-text').attr('placeholder', $thisBT);
        jQuery('#announcements-title').attr('placeholder', $thisTI);

        jQuery('.announcement-wrap i').removeClass();

        jQuery('.announcement-wrap i').addClass($thisIC);


        jQuery('.field-desc strong').text($thisDes.length);


    })

    jQuery('.ann-style-wrap span').click(function (e) {

        var $this = jQuery(this),

            $thisWrap = $this.closest('.ann-style-wrap'),

            $thislabel = $this.closest('label'),

            $thisDes = $this.data('des'),

            $thisBT = $this.data('bt');


        $thisWrap.find('input[name="ann-style"]:checked').removeAttr('checked');

        $thisWrap.find('.ann-style-val').val($thislabel.find('input').val());

        $thislabel.find('input').attr('checked', true);


        jQuery('.announcement-wrap span, #announcements-message').text($thisDes);

        jQuery('.announcement-wrap a').text($thisBT);

        jQuery('#announcements-btn-text').val($thisBT);


    });


    jQuery(document).on('click', '#lp-save-dis', function (e) {
        e.preventDefault();

        var $this = jQuery(this),
            userID = $this.data('uid'),
            disHea = jQuery('#dis-heading').val(),
            disCod = jQuery('#dis-code').val(),
            disExpE = jQuery('#dis-expiry-e').val(),
            disExpS = jQuery('#dis-expiry-s').val(),
            disTimeE = jQuery('#dis-time-e').val(),
            disTimeS = jQuery('#dis-time-s').val(),
            disBT = jQuery('#dis-btn-text').val(),
            disBL = jQuery('#dis-btn-link').val(),
            disLI = jQuery('#dis-listing').val(),
            disImg = jQuery('.new-file-upload .frontend-input').val(),
            disOff = jQuery('#dis-off').val(),
            disDes = jQuery('#dis-description').val();

        if (disOff == '' || disOff == null) {
            disOff = jQuery('div#lp-percent #dis-off').val();
        }
        if (disLI == 0 || disLI == '' || disLI == null) {
            jQuery('#select2-dis-listing-container').addClass('error');
            jQuery('#dis-listing').addClass('error');
        } else {
            jQuery('#select2-dis-listing-container').removeClass('error');
            jQuery('#dis-listing').removeClass('error');
        }
        if (disHea == '') {
            jQuery('#dis-heading').addClass('error');
        } else {
            jQuery('#dis-heading').removeClass('error');
        }
        if (disExpS == '') {
            jQuery('#dis-expiry-s').addClass('error');
        } else {
            jQuery('#dis-expiry-s').removeClass('error');
        }
        if (disTimeS == '') {
            jQuery('#dis-time-s').addClass('error');
        } else {
            jQuery('#dis-time-s').removeClass('error');
        }

        if (disLI == 0 || disLI == '' || disLI == null || disHea == '' || disExpS == '' || disTimeS == '') {
            var dataError = [];
            dataError.status = 'error';
            dataError.msg = jQuery('.lp-notifaction-area').data('error-msg');
            ajax_success_popup(dataError, $this);
            $this.find('i').removeClass('fa-spin fa-spinner');
            return false;
        }
        if ($this.hasClass('processing-dis')) {
        } else {
            $this.addClass('processing-dis');
            $this.append('<i class="fa fa-spin fa-spinner"></i>');
            jQuery.ajax({
                type: 'POST',
                dataType: 'json',
                url: ajax_search_term_object.ajaxurl,
                data: {
                    'action': 'add_discount_cb',
                    'user_id': userID,
                    'disHea': disHea,
                    'disCod': disCod,
                    'disExpE': disExpE,
                    'disExpS': disExpS,
                    'disTimeE': disTimeE,
                    'disTimeS': disTimeS,
                    'disBT': disBT,
                    'disBL': disBL,
                    'disLI': disLI,
                    'disDes': disDes,
                    'disOff': disOff,
                    'disImg': disImg,
                    'disSta': 'active',
                    'lpNonce': jQuery('#lpNonce').val()
                },
                success: function (res) {
                    ajax_success_popup(res, $this);
                },

                error: function (err) {
                    alert(err);
                    $this.find('i').remove();
                }
            });
        }
    });

    jQuery(document).on('click', '#lp-save-offer', function (e) {

        e.preventDefault();


        var $this = jQuery(this),

            userID = $this.data('uid'),

            offerTitle = jQuery('#offer-title').val(),

            offerDes = jQuery('#offer-description').val(),

            offerExp = jQuery('#offer-expriry').val(),

            offerBT = jQuery('#offer-btn-text').val(),

            offerBL = jQuery('#offer-btn-link').val(),

            offerImg = jQuery('#frontend-input').val(),

            offerLI = jQuery('#offer-listing').val();


        if (!jQuery('.btn-link-field-toggle').hasClass('link-active')) {

            offerBL = '';

        }


        $this.append('<i class="fa fa-spin fa-spinner"></i>');


        if (offerLI == null || offerLI == '' || offerTitle == '' || offerExp == '') {

            jQuery('.ann-err-msg').fadeIn(500).delay(1500).fadeOut(500);

            $this.find('i').remove();

            return false;

        }


        jQuery.ajax({

            type: 'POST',

            dataType: 'json',

            url: ajax_search_term_object.ajaxurl,

            data: {

                'action': 'add_offer_cb',

                'user_id': userID,

                'offerTitle': offerTitle,

                'offerDes': offerDes,

                'offerExp': offerExp,

                'offerBT': offerBT,

                'offerBL': offerBL,

                'offerLI': offerLI,

                'offerImg': offerImg,
                'lpNonce': jQuery('#lpNonce').val()

            },

            success: function (res) {

                console.log(res);

                $this.find('i').removeClass('fa-spin fa-spinner');

                $this.find('i').addClass('fa fa-check');

                location.reload();

            },

            error: function (err) {

                alert(err);

                $this.find('i').remove();

            }

        });

    });

    jQuery(document).on('click', '.del-this', function (e) {
        e.preventDefault();
        jQuery('.remove-active').removeClass('remove-active');
        jQuery(this).addClass('remove-active');
        jQuery('#dashboard-delete-modal').modal('show');
        jQuery('.modal-backdrop').hide();
    });

    jQuery(document).on('click', '.dashboard-confirm-del-btn', function (e) {
        var $this = jQuery('.remove-active');
        if ($this.hasClass('del-all-menu')) {
            var lid = $this.data('lid'),
                user_id = $this.data('uid');


            jQuery(this).append('<i class="fa fa-spin fa-spinner" style="margin-left: 5px;"></i>');

            jQuery.ajax({
                type: 'POST',
                dataType: 'json',
                url: ajax_search_term_object.ajaxurl,
                data: {
                    'action': 'del_all_menu_cb',
                    'user_id': user_id,
                    'lid': lid,
                    'lpNonce': jQuery('#lpNonce').val()
                },
                success: function (res) {
                    if (res.status == 'success') {
                        location.reload();
                    }
                    $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-trash-o');
                },
                error: function (err) {
                    console.log(err);
                    $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-trash-o');
                }
            });
        } else {
            var targetID = $this.data('targetid'),
                userID = $this.data('uid'),
                delType = '',
                delIDS = '',
                dellAll = '';

            if ($this.hasClass('dis-del')) {
                delType = 'dis';
            }
            if ($this.hasClass('event-del')) {
                delType = 'event';
            }
            if ($this.hasClass('ann-del')) {
                delType = 'ann';
            }
            if ($this.hasClass('offer-del')) {
                delType = 'offer';
                delIDS = $this.data('del-ids');
            }
            if ($this.hasClass('menu-del')) {
                delType = 'menu';
                delIDS = $this.data('lid');
            }
            if ($this.hasClass('del-type')) {
                delType = 'type';
                dellAll = jQuery('input[name="delete-group-type"]:checked').val();
            }
            if ($this.hasClass('del-group')) {
                delType = 'group';
                dellAll = jQuery('input[name="delete-group-type"]:checked').val();
            }
            jQuery(this).append('<i class="fa fa-spin fa-spinner" style="margin-left: 5px;"></i>');
            jQuery.ajax({
                type: 'POST',
                dataType: 'json',
                url: ajax_search_term_object.ajaxurl,
                data: {
                    'action': 'del_ann_dis_menu_cb',
                    'user_id': userID,
                    'delType': delType,
                    'targetID': targetID,
                    'delIDS': delIDS,
                    'dellAll': dellAll,
                    'lpNonce': jQuery('#lpNonce').val()
                },
                success: function (res) {
                    if (res.status == 'success') {
                        if (delType == 'menu') {
                            jQuery('.menu-del[data-targetid="' + targetID + '"]').closest('.lp-menu-close-outer').remove();
                            jQuery('#dashboard-delete-modal').modal('hide');
                            jQuery('.dashboard-confirm-del-btn').find('i').remove();
                        } else {
                            jQuery('#dashboard-delete-modal').modal('hide');
                            location.reload();
                        }

                    }
                    $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-trash-o');
                },
                error: function (err) {
                    console.log(err);
                    $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-trash-o');
                }
            });
        }
    });
    jQuery(document).on('click', 'a.event-edit, a.menu-edit, a.ann-edit, a.dis-edit, a.offer-edit', function (e) {
        e.preventDefault();
        var $this = jQuery(this),
            targetID = $this.data('targetid'),
            updateWrap = '#update-wrap-' + targetID;

        if (jQuery('.active-update-form').length != 0) {
            jQuery('.active-update-form').slideUp(500, function (e) {
                jQuery('.active-update-form').removeClass('active-ann-form');
                jQuery(updateWrap).slideToggle('500', function (e) {
                    jQuery(updateWrap).addClass('active-update-form');
                    jQuery('.cancel-update').click(function (e) {
                        e.preventDefault();
                        jQuery('.active-update-form').slideUp(500, function (e) {
                            jQuery('.active-update-form').removeClass('active-update-form');
                        })
                    })
                });
            });
        } else {
            jQuery(updateWrap).slideToggle('500', function (e) {
                jQuery(updateWrap).addClass('active-update-form');
                jQuery('.cancel-update').click(function (e) {
                    e.preventDefault();
                    jQuery('.active-update-form').slideUp(500, function (e) {
                        jQuery('.active-update-form').removeClass('active-update-form');
                    })
                })
            });
        }
    });
    jQuery(document).on('click', '.edit-menu-item', function (e) {
        e.preventDefault();
        var $this = jQuery(this),
            targetID = $this.data('menuid'),
            updateWrap = '#menu-update-' + targetID;

        if (jQuery('.active-update-formm').length != 0) {
            jQuery('.active-update-formm').slideUp(500, function (e) {
                jQuery('.active-update-formm').removeClass('active-ann-form');
                jQuery(updateWrap).slideToggle('500', function (e) {
                    jQuery(updateWrap).addClass('active-update-formm');
                    jQuery('.cancel-update-menu').click(function (e) {
                        e.preventDefault();
                        jQuery('.active-update-formm').slideUp(500, function (e) {
                            jQuery('.active-update-formm').removeClass('active-update-formm');
                        })
                    })
                });
            });
        } else {
            jQuery(updateWrap).slideToggle('500', function (e) {
                jQuery(updateWrap).addClass('active-update-formm');
                jQuery('.cancel-update-menu').click(function (e) {
                    e.preventDefault();
                    jQuery('.active-update-formm').slideUp(500, function (e) {
                        jQuery('.active-update-formm').removeClass('active-update-formm');
                    })
                })
            });
        }
    });

    if (jQuery('.lp-countdown').length != 0) {
        jQuery('.lp-countdown').each(function (i, obj) {
            var selector = '#' + jQuery(this).attr('id');
            init_countdown(selector);
        });
    }
});

jQuery(document).on('change', '#discount_displayin', function (e) {

    e.preventDefault();

    var $this = jQuery(this),

        thisval = $this.val(),

        userID = $this.data('udi');


    jQuery($this).after('<i class="fa fa-spinner fa-spin" aria-hidden="true"></i>');

    jQuery.ajax({

        type: 'POST',

        dataType: 'json',

        url: ajax_search_term_object.ajaxurl,

        data: {

            'action': 'discount_display_area',

            'userID': userID,

            'thisval': thisval,
            'lpNonce': jQuery('#lpNonce').val()

        },

        success: function (res) {

            jQuery('#discount_displayin').next('i').remove();

        },

        error: function (err) {

            alert(err);

            $this.find('i').remove();

        }

    });

})

jQuery(document).on('change', '#event_displayin', function (e) {

    e.preventDefault();

    var $this = jQuery(this),

        thisval = $this.val(),

        userID = $this.data('udi');

    jQuery($this).after('<i class="fa fa-spinner fa-spin" aria-hidden="true"></i>');

    jQuery.ajax({

        type: 'POST',

        dataType: 'json',

        url: ajax_search_term_object.ajaxurl,

        data: {

            'action': 'event_display_area',

            'userID': userID,

            'thisval': thisval,
            'lpNonce': jQuery('#lpNonce').val()

        },

        success: function (res) {

            jQuery('#event_displayin').next('i').remove();

        },

        error: function (err) {

            alert(err);

            $this.find('i').remove();

        }

    });

});


jQuery(document).on('click', '.lp-edit-offer', function (e) {

    e.preventDefault();

    var $this = jQuery(this),

        userID = $this.data('uid'),

        offerID = $this.data('offerid'),

        offerTitle = jQuery('#offer-title-' + offerID).val(),

        offerDes = jQuery('#offer-description-' + offerID).val(),

        offerExp = jQuery('#offer-expriry-' + offerID).val(),

        offerBT = jQuery('#offer-btn-text-' + offerID).val(),

        offerBL = jQuery('#offer-btn-link-' + offerID).val(),

        offerLI = jQuery('#offer-listing-' + offerID).val();


    if (!jQuery('.btn-link-field-toggle').hasClass('link-active')) {

        offerBL = '';

    }


    $this.append('<i class="fa fa-spin fa-spinner"></i>');


    if (offerLI == null || offerLI == '' || offerTitle == '' || offerExp == '') {

        jQuery('.ann-err-msg').fadeIn(500).delay(1500).fadeOut(500);

        $this.find('i').remove();

        return false;

    }


    jQuery.ajax({

        type: 'POST',

        dataType: 'json',

        url: ajax_search_term_object.ajaxurl,

        data: {

            'action': 'add_offer_cb',

            'user_id': userID,

            'offerTitle': offerTitle,

            'offerDes': offerDes,

            'offerExp': offerExp,

            'offerBT': offerBT,

            'offerBL': offerBL,

            'offerLI': offerLI,

            'offerUP': 'yes',

            'offerID': offerID,
            'lpNonce': jQuery('#lpNonce').val()

        },

        success: function (res) {

            // console.log(res);

            $this.find('i').removeClass('fa-spin fa-spinner');

            $this.find('i').addClass('fa fa-check');

            location.reload();

        },

        error: function (err) {

            alert(err);

            $this.find('i').remove();

        }

    });

});


jQuery(document).on('click', '.lp-edit-dis', function (e) {
    e.preventDefault();
    var $this = jQuery(this),

        disID = $this.data('disid'),
        userID = $this.data('uid'),
        disHea = jQuery('#dis-heading-' + disID).val(),
        disCod = jQuery('#dis-code-' + disID).val(),
        disExpE = jQuery('#dis-expiry-e-' + disID).val(),
        disExpS = jQuery('#dis-expiry-s-' + disID).val(),
        disTimeE = jQuery('#dis-time-e-' + disID).val(),
        disTimeS = jQuery('#dis-time-s-' + disID).val(),
        disBT = jQuery('#dis-btn-text-' + disID).val(),
        disBL = jQuery('#dis-btn-link-' + disID).val(),
        disLI = $this.data('listid'),
        disOff = jQuery('#dis-off-' + disID).val(),
        disImg = jQuery('.edit-upload-' + disID + ' .frontend-input').val();
    disDes = jQuery('#dis-description-' + disID).val();

    $this.append('<i class="fa fa-spin fa-spinner"></i>');
    if (disLI == 0 || disLI == '') {
        jQuery('.ann-err-msg').fadeIn(500).delay(1500).fadeOut(500);
        $this.find('i').remove();
        return false;
    }
    if (disImg == '') {
        disImg = jQuery('#dis-old-img-' + disID).val();
    }
    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'add_discount_cb',
            'user_id': userID,
            'disID': disID,
            'disHea': disHea,
            'disCod': disCod,
            'disExpE': disExpE,
            'disExpS': disExpS,
            'disTimeE': disTimeE,
            'disTimeS': disTimeS,
            'disBT': disBT,
            'disBL': disBL,
            'disLI': disLI,
            'disDes': disDes,
            'disOff': disOff,
            'disImg': disImg,
            'disUp': 'yes',
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (res) {
            ajax_success_popup(res, $this);
        },
        error: function (err) {
            // alert( err );
            // $this.find('i').remove();
        }
    });
});


jQuery(document).on('click', '.lp-edit-announcements', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        annID = $this.data('annid'),
        userID = $this.data('uid'),
        annMsg = jQuery('#announcements-message-' + annID).val(),
        annBT = jQuery('#announcements-btn-text-' + annID).val(),
        annBL = jQuery('#announcements-btn-link-' + annID).val(),
        annSt = jQuery('#ann-style-val-' + annID).val(),
        annTI = jQuery('#announcements-title-' + annID).val(),
        annIC = jQuery('#announcements-icon-' + annID).val(),
        annLI = jQuery(this).data('lid');

    $this.append('<i class="fa fa-spin fa-spinner"></i>');
    if (annLI == 0 || annLI == '' || annMsg == '') {
        jQuery('.ann-err-msg-' + annID).fadeIn(500).delay(1500).fadeOut(500);
        $this.find('i').remove();
        return false;
    }

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'add_announcements_cb',
            'user_id': userID,
            'annMsg': annMsg,
            'annSt': annSt,
            'annBT': annBT,
            'annBL': annBL,
            'annLI': annLI,
            'annTI': annTI,
            'annIC': annIC,
            'annUP': 'yes',
            'annID': annID,
            'lpNonce': jQuery('#lpNonce').val()
        },

        success: function (res) {
            ajax_success_popup(res, $this);

        },

        error: function (err) {

        }
    });
});

function init_countdown(selector) {
    var $this = jQuery(selector);
    if (!$this.length) return false;

    var clock;
    var daysLabel = jQuery(selector).data('label-days'),
        hoursLabel = jQuery(selector).data('label-hours'),
        minsLabel = jQuery(selector).data('label-mints'),
        cHour = jQuery(selector).data('hour'),
        cMinute = jQuery(selector).data('minute'),
        cDay = jQuery(selector).data('day'),
        cMonth = jQuery(selector).data('month'),
        cYear = jQuery(selector).data('year');

    FlipClock.Lang.Custom = { days: daysLabel, hours: hoursLabel, minutes: minsLabel };

    var startDate = new Date(cYear, cMonth, cDay, cHour, cMinute); //year, month, day
    var now = Math.floor(Date.now() / 1000); //Current timestamp in seconds
    var clockStart = startDate.getTime() / 1000 - now; //What to set the clock at when page loads
    var numDays = Math.floor(clockStart / 86400);

    var minDigits = 6;
    if (numDays > 99) {
        minDigits = 7;
    }

    clock = jQuery(selector).FlipClock({
        clockFace: 'DailyCounter',
        autoStart: true,
        showSeconds: false,
        language: 'Custom',
        minimumDigits: minDigits
    });

    clock.setTime(clockStart);
    clock.setCountdown(true);
}

jQuery(document).on('mouseleave', '#menu-categories-menu', function (e) {

    jQuery('.lp-header-nav-btn').removeClass('active-can-menu');

    jQuery('#menu-categories-menu').css('opacity', '0');

    jQuery('#menu-categories-menu').css('transform', 'scale(0)');

});

jQuery(document).on('click', '.lp-ann-btn', function (e) {

    e.preventDefault();

    if (jQuery(this).hasClass('lp-no-review-btn')) {

    } else {
        var targetANN = '#' + jQuery(this).attr('data-ann');
        jQuery(targetANN).show();

        jQuery(targetANN).find('.lp-listing-announcement').fadeIn();
        jQuery(targetANN).find('.lp-listing-announcement').addClass('active-ann');

        jQuery('.code-overlay').fadeIn();
    }
});


jQuery(document).on('click', '.close-ann', function (e) {

    e.preventDefault();

    jQuery('.active-ann').fadeOut();
    jQuery('.active-ann').removeClass('active-ann');
    jQuery('.code-overlay').fadeOut();
    jQuery('.lp-listing-announcements').fadeOut();
});


jQuery(document).on('click', '.lp-coupon-btn', function (e) {

    e.preventDefault();


    var targetCOUP = '#' + jQuery(this).data('coupon');


    jQuery(targetCOUP).fadeIn();

    jQuery(targetCOUP).addClass('active-coupon');


    jQuery('.code-overlay').fadeIn();


});

jQuery(document).on('click', '.close-coupon', function (e) {

    e.preventDefault();


    jQuery('.active-coupon').fadeOut();

    jQuery('.active-coupon').removeClass('active-coupon');

    jQuery('.code-overlay').fadeOut();

});


jQuery(document).on('shown.bs.tab', 'a[href="#menu_tab"]', function (e) {
    //slickINIT();
    jQuery('.lp-listing-menuu-slider').slick('refresh');
});


jQuery(document).on('click', '.ann-toggle-btn', function (e) {

    e.preventDefault();
    var $this = jQuery(this),
        status = $this.attr('data-status'),
        annID = $this.data('annid'),
        userID = $this.data('uid');

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'add_announcements_cb',
            'user_id': userID,
            'status': status,
            'annID': annID,
            'annUP': 'on-off',
            'lpNonce': jQuery('#lpNonce').val()
        },

        success: function (res) {
            if (res.status == 0) {
                status = 'inactive';
            } else if (res.status == 1) {
                status = 'active';
            }
            $this.attr('data-status', status);
        },
        error: function (err) {
            $this.find('i').remove();
        }
    });

});
jQuery(document).on('change', '.on-off-ann', function (e) {
    e.preventDefault();

    var $this = jQuery(this),
        status = $this.attr('data-status'),
        annID = $this.data('annid'),
        userID = $this.data('uid');

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'add_announcements_cb',
            'user_id': userID,
            'status': status,
            'annID': annID,
            'annUP': 'on-off',
            'lpNonce': jQuery('#lpNonce').val()
        },

        success: function (res) {
            if (res.status == 0) {
                status = 'inactive';
            } else if (res.status == 1) {
                status = 'active';
            }
            $this.attr('data-status', status);
        },
        error: function (err) {
            $this.find('i').remove();
        }
    });
});


jQuery(document).on('keyup', '#announcements-message', function (e) {

    var thisText = jQuery(this).val();

    jQuery('.ann-preivew-wrap .announcement-wrap span').text(thisText);


    jQuery('.field-desc strong').text(thisText.length);

});

jQuery(document).on('keyup', '#announcements-title', function (e) {

    var thisText = jQuery(this).val();

    jQuery('.ann-preivew-wrap .announcement-wrap strong').text(thisText);

});

jQuery(document).on('keyup', '#announcements-btn-text', function (e) {

    var thisText = jQuery(this).val();

    jQuery('.ann-preivew-wrap .announcement-wrap .announcement-btn').text(thisText);


});

jQuery(document).on('focusout', '#announcements-icon', function (e) {

    var thisText = jQuery(this).val();
    if (thisText == '') {
        return false;
    }

    if (thisText.match("^fa")) {

        jQuery('.announcement-wrap img').hide();

        jQuery('.announcement-wrap i').show();

        jQuery(this).attr('icon-type', 'fa-icon');

        jQuery('.announcement-wrap i').removeClass().addClass('fa ' + thisText);

    } else {

        jQuery('.announcement-wrap i').hide()

        jQuery('.announcement-wrap img').show();

        jQuery('.announcement-wrap img').attr('src', thisText);

        jQuery(this).attr('icon-type', 'img-icon');

    }


});


function slickINIT() {

    if (jQuery('.lp-listing-menuu-slider').length != 0) {
        jQuery('.lp-listing-menuu-slider').slick({
            infinite: true,
            slidesToShow: 1,
            slidesToScroll: 1,
            adaptiveHeight: true,
            nextArrow: "<i class=\"fa fa-angle-right arrow-left\" aria-hidden=\"true\"></i>",
            prevArrow: "<i class=\"fa fa-angle-left arrow-right\" aria-hidden=\"true\"></i>"
        });

    }

}

jQuery(document).on('change', '.coupons-fields-switch input[type="checkbox"]', function (e) {
    e.preventDefault();
    var targetID = jQuery(this).data('target');
    if (targetID == 'coupon-external') {
        if (jQuery(this).is(':checked')) {
            jQuery('#btn-url-switch').slideDown(500);
            //jQuery('#dis-code').closest('.lp-coupon-box-row').slideUp(500);
        } else {
            jQuery('#btn-url-switch').slideUp(500);
            //jQuery('#dis-code').closest('.lp-coupon-box-row').slideDown(500);
        }

    } else if (targetID == 'quote-button') {
        if (jQuery(this).is(':checked')) {
            jQuery('.menu-price-wrap').slideUp(500, function () {
                jQuery('.menu-quote-wrap').slideDown(500);
            });
        } else {
            jQuery('.menu-quote-wrap').slideUp(500, function () {
                jQuery('.menu-price-wrap').slideDown(500);
            });
        }
    } else if (targetID == 'coupon-end') {
        if (jQuery(this).is(':checked')) {
            jQuery('.lp-cpn-end-container').slideDown(500);
        } else {
            jQuery('.lp-cpn-end-container').slideUp(500);
        }
    } else {
        jQuery('#' + targetID + '-switch').slideToggle(500, function () {
            if (!jQuery('#date-switch').is(':visible') && !jQuery('#time-switch').is(':visible')) {
                jQuery('.empty-row-check').slideToggle();
            }
        });
    }

});


jQuery(document).on('click', '.del-all-menu', function (e) {
    e.preventDefault();

    jQuery(this).addClass('remove-active');
    jQuery('#dashboard-delete-modal').modal('show');
    jQuery('.modal-backdrop').hide();


});

jQuery(document).on('click', '#lp-save-events', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        eTitle = jQuery('#event-title').val(),
        eDesc = jQuery('#event-description').val(),
        eDate = jQuery('#event-date-s').val(),
        eDateE = jQuery('#event-date-e').val(),
        eTime = jQuery('#event-time').val(),
        eTimeE = jQuery('#event-time-e').val(),
        eLoc = '',
        eLat = jQuery('#lp-events-form #latitude').val(),
        eLon = jQuery('#lp-events-form #longitude').val(),
        eTUrl = jQuery('#event-tickets-data').val(),
        eLID = jQuery('#event-listing').val(),
        eImg = jQuery('.new-file-upload .frontend-input').val(),
        eUID = $this.data('uid'),
        eUtils = '';
    if (jQuery('.events-map-wrap a[data-type="gaddresscustom"]').hasClass('active')) {
        eLoc = jQuery('#lp-events-form input[name="gAddresscustom"]').val();
    } else {
        eLoc = jQuery('#lp-events-form input[name="gAddress"]').val();
    }

    jQuery('.coupons-fields-switch').find('.switch-checkbox').each(function () {
        var CheckboxX = jQuery(this),
            target = CheckboxX.data('target'),
            targetVal = ''
        if (CheckboxX.is(':checked')) {
            targetVal = 'yes';
        } else {
            targetVal = 'no';
        }
        eUtils += target + '|' + targetVal + '*';
    });
    if (eLID == '' || eLID == 0 || eLID == null) {
        if (jQuery('#event-listing').length) {
            jQuery('#event-listing').addClass('error');
        } else {
            jQuery('#select2-event-listing-container').addClass('error');
        }
    } else {
        if (jQuery('#event-listing').length) {
            jQuery('#event-listing').removeClass('error');
        } else {
            jQuery('#select2-event-listing-container').removeClass('error');
        }

    }
    if (eTitle == '') {
        jQuery('#event-title').addClass('error');
    } else {
        jQuery('#event-title').removeClass('error');
    }

    var checkEndDate = true;
    if (jQuery('.lp-event-end-date-switch').is(':checked')) {
        checkEndDate = false;
        if (eDateE == '' || eTimeE == '') {
            if (eDateE == '') {
                jQuery('#event-date-e').addClass('error');
            }
            if (eTimeE == '') {
                jQuery('#event-time-e').addClass('error');
            }
            checkEndDate = true;
        } else {
            if (eDateE == '') {
                jQuery('#event-date-e').removeClass('error');
            }
            if (eTimeE == '') {
                jQuery('#event-time-e').removeClass('error');
            }
            checkEndDate = false;
        }
    } else {
        jQuery('#event-date-e').removeClass('error');
        jQuery('#event-time-e').removeClass('error');
        checkEndDate = false;
    }

    if (eDate == '') {
        jQuery('#event-date-s').addClass('error');
    } else {
        jQuery('#event-date-s').removeClass('error');
    }
    if (eTime == '') {
        jQuery('#event-time').addClass('error');
    } else {
        jQuery('#event-time').removeClass('error');
    }
    if (eLID == '' || eLID == 0 || eLID == null || eTitle == '' || eTime == '' || eDate == '' || checkEndDate) {
        var dataError = [];
        dataError.status = 'error';
        dataError.msg = jQuery('.lp-notifaction-area').data('error-msg');
        ajax_success_popup(dataError, $this);
        return false;
    }
    if (jQuery('a[data-type="gaddress"]').hasClass('active')) {
        if (eLoc == '') {
            jQuery('#lp-events-form input[name="gAddress"]').addClass('error');
            var dataError = [];
            dataError.status = 'error';
            dataError.msg = jQuery('.lp-notifaction-area').data('error-msg');
            ajax_success_popup(dataError, $this);
            return false;
        } else {
            jQuery('#lp-events-form input[name="gAddress"]').removeClass('error');
        }
    } else {
        if (eLat == '' || eLon == '' || eLoc == '') {

            jQuery('#inputAddresss').addClass('error');

            var dataError = [];
            dataError.status = 'error';
            dataError.msg = jQuery('.lp-notifaction-area').data('error-msg');
            ajax_success_popup(dataError, $this);
            return false;
        }
    }

    $this.append('<i class="fa fa-spin fa-spinner"></i>');
    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'add_events_cb',
            'eTitle': eTitle,
            'eDesc': eDesc,
            'eDate': eDate,
            'eDateE': eDateE,
            'eTime': eTime,
            'eTimeE': eTimeE,
            'eLoc': eLoc,
            'eLat': eLat,
            'eLon': eLon,
            'eTUrl': eTUrl,
            'eLID': eLID,
            'eUID': eUID,
            'eImg': eImg,
            'eUtils': eUtils,
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (res) {
            ajax_success_popup(res, $this);
        },
        error: function (err) {
            console.log(err);
        }
    });
});

//lp-save-events


jQuery(document).on('click', '.lp-save-events', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        eID = $this.data('eid'),
        eTitle = jQuery('#event-title-' + eID).val(),
        eDesc = jQuery('#event-description-' + eID).val(),
        eDate = jQuery('#event-date-s-' + eID).val(),
        eDateE = jQuery('#event-date-e-' + eID).val(),
        eTime = jQuery('#event-time-' + eID).val(),
        eTimeE = jQuery('#event-time-e-' + eID).val(),
        eLoc = jQuery('#event-location-' + eID).val(),
        eLat = $this.closest('.lp-coupons-form-inner').find('.latitude').val(),
        eLong = $this.closest('.lp-coupons-form-inner').find('.longitude').val(),
        eTUrl = jQuery('#event-tickets-data-' + eID).val(),
        eImg = jQuery('.edit-upload-' + eID + ' .frontend-input').val(),
        eUID = $this.data('uid');


    if (eTitle == '') {
        jQuery('#event-title').addClass('error');
    } else {
        jQuery('#event-title').removeClass('error');
    }
    if (eTitle == '') {
        return false;
    }
    if (eImg == '') {
        eImg = jQuery('#event-old-img-' + eID).val();
    }

    if (eLoc == '') {
        jQuery('#event-location-' + eID).addClass('error');
        var dataError = [];
        dataError.status = 'error';
        dataError.msg = jQuery('.lp-notifaction-area').data('error-msg');
        ajax_success_popup(dataError, $this);
        return false;
    } else {
        jQuery('#event-location-' + eID).removeClass('error');
    }
    $this.append('<i class="fa fa-spin fa-spinner"></i>');
    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'add_events_cb',
            'eTitle': eTitle,
            'eDesc': eDesc,
            'eDate': eDate,
            'eDateE': eDateE,
            'eTime': eTime,
            'eTimeE': eTimeE,
            'eLoc': eLoc,
            'eLat': eLat,
            'eLon': eLong,
            'eTUrl': eTUrl,
            'eUID': eUID,
            'eID': eID,
            'eImg': eImg,
            'eUp': 'yes',
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (res) {
            ajax_success_popup(res, $this);
        },
        error: function (err) {
            console.log(err);
        }
    });
});

jQuery(document).on('click', '.attend-event', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        eID = $this.data('event'),
        eUID = $this.data('uid'),
        notGoing = '',
        goingText = jQuery('.going-text').val(),
        nGoingText = jQuery('.not-going-text').val();

    if ($this.hasClass('processing')) {

    } else {
        if ($this.hasClass('not-going')) {
            notGoing = 'yes';
        } else {

        }
        if ($this.hasClass('from-lpec')) {
            $this.find('i').removeClass('fa-plus').addClass('fa-spinner fa-spin');
        } else {
            $this.append('<i class="fa fa-spinner fa-spin"></i>');
        }

        $this.addClass('processing');

        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'event_attending_cb',
                'eID': eID,
                'eUID': eUID,
                'notGoing': notGoing,
                'lpNonce': jQuery('#lpNonce').val()
            },
            success: function (res) {
                if ($this.hasClass('from-lpec')) {
                    jQuery('#lpec-attendee-count-' + eID).text(parseInt(res.total_attending));
                } else {
                    jQuery('.total-going').text(res.total_attending);
                    $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-check');
                }

                $this.removeClass('processing');
                if (notGoing == 'yes') {
                    $this.removeClass('not-going');
                    if ($this.hasClass('from-lpec')) {
                        jQuery('ul#lpec-attendees-avatar-' + eID).find('li#lpec-attendee-avatar-' + eUID + '-' + eID).remove();
                        $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-plus');
                    } else {
                        $this.text(goingText);
                    }

                } else {
                    $this.addClass('not-going');
                    if ($this.hasClass('from-lpec')) {
                        jQuery('ul#lpec-attendees-avatar-' + eID).prepend(res.attendee_avatar);
                        $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-times');
                    } else {
                        $this.text(nGoingText);
                    }
                }

            },
            error: function (err) {
                console.log(err);
            }
        });
    }
});

jQuery(document).on('click', '.cancel-ad-new-btn', function (e) {
    e.preventDefault();
    var targetForm = '#' + jQuery(this).data('cancel') + '-form-toggle';
    jQuery(targetForm).fadeOut("fast", function () {
        if (jQuery('body').find('div.panel.with-nav-tabs.panel-default.lp-dashboard-tabs.col-md-11')) {
            jQuery(".lp-blank-section").fadeIn();
        }
        jQuery('div.panel.with-nav-tabs.panel-default.lp-dashboard-tabs.col-md-11').fadeIn();
    });
});


jQuery(document).on('click', '.menu-add-new', function (e) {
    jQuery('.panel.with-nav-tabs.panel-default.lp-dashboard-tabs').fadeOut("slow", function () {
        jQuery('div.tab-pane.fade.in.active.clearfix.lp-dashboard-menu-container').fadeIn("fast", function () {
            jQuery('div.panel.with-nav-tabs.panel-default.lp-dashboard-tabs.col-md-12.lp-left-panel-height.lp-left-panel-height-outer.padding-bottom0').fadeIn("fast");
        });
    });
});

jQuery(document).on('click', '.lp-view-all-btn', function (e) {
    e.preventDefault();
    if (jQuery(this).hasClass('all-with-refresh')) {
        location.reload();
    } else {
        jQuery('div.panel.with-nav-tabs.panel-default.lp-dashboard-tabs.col-md-12.lp-left-panel-height.lp-left-panel-height-outer.padding-bottom0').fadeOut("fast", function () {
            jQuery('div.tab-pane.fade.in.active.clearfix.lp-dashboard-menu-container').fadeOut("fast", function () {
                jQuery('.panel.with-nav-tabs.panel-default.lp-dashboard-tabs').fadeIn("Slow");
            });
        });
    }

});

jQuery(document).on('click', '.cancel-add-menu', function (e) {
    e.preventDefault();
    jQuery('#lp-save-menu').attr('id', 'lp-save-menu-reopen');
    jQuery('.lp-menu-close-outer.lp-menu-open').slideUp();
});
jQuery(document).on('click', '#lp-save-menu-reopen', function (e) {
    e.preventDefault();
    jQuery(this).attr('id', 'lp-save-menu');
    jQuery('.lp-menu-close-outer.lp-menu-open').slideDown();
});

jQuery(document).on('click', '.lp-notifi-icons', function (e) {
    e.preventDefault();
    jQuery(this).closest('.active-wrap').removeClass('active-wrap');
});
jQuery(document).ready(function () {
    jQuery('#fill-o-bot-check').on('change', function (e) {
        if (jQuery(this).is(':checked')) {
            jQuery('#lptitle').attr('type', 'hidden');
            jQuery('.lptitle').addClass('fill-o-bot-active');
            jQuery('#lptitle').attr('name', '');
            jQuery('#lptitleGoogle').attr('name', 'postTitle');
            jQuery('#lptitleGoogle').attr('type', 'text');
        } else {
            jQuery('#lptitleGoogle').attr('type', 'hidden');
            jQuery('.lptitle').removeClass('fill-o-bot-active');
            jQuery('#lptitle').attr('name', 'postTitle');
            jQuery('#lptitle').attr('type', 'text');
            jQuery('#lptitleGoogle').attr('name', '');

        }
    });

});
jQuery('html').click(function (e) {
    if (jQuery('.lp-multi-star-wrap').is(":visible") && e.target.className != 'open-multi-rate-box') {
        if (jQuery('.lp-multi-star-wrap').hasClass('lp-multi-start-wrap-edit-review')) {

        } else {
            jQuery('.lp-multi-star-wrap').slideUp();
        }
    }
});
jQuery(document).ready(function () {
    jQuery('#fill-o-bot-check').on('change', function (e) {
        if (jQuery(this).is(':checked')) {
            jQuery('#lptitle').attr('type', 'hidden');
            jQuery('#lptitle').removeClass('lp-required-field');
            jQuery('.lptitle').addClass('fill-o-bot-active');
            jQuery('#lptitle').attr('name', '');
            jQuery('#lptitleGoogle').attr('name', 'postTitle');
            jQuery('#lptitleGoogle').attr('type', 'text');
            jQuery('#lptitleGoogle').addClass('lp-required-field');
        } else {
            jQuery('#lptitleGoogle').attr('type', 'hidden');
            jQuery('.lptitle').removeClass('fill-o-bot-active');
            jQuery('#lptitleGoogle').removeClass('lp-required-field');
            jQuery('#lptitle').attr('name', 'postTitle');
            jQuery('#lptitle').attr('type', 'text');
            jQuery('#lptitleGoogle').attr('name', '');
            jQuery('#lptitle').addClass('lp-required-field');
        }
    });
});

function ajax_success_popup(res, $this) {
    if (res.status == 'success') {
        if ($this != '') {
            $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-check');
        }

        jQuery('.lp-notifaction-area').find('h4').text(res.msg);
        jQuery('.lp-notifaction-area').removeClass('lp-notifaction-error').addClass('lp-notifaction-success');
        jQuery('.lp-notifaction-area').addClass('active-wrap');


        location.reload();
    }
    if (res.status == 'error') {
        if ($this != '') {
            $this.find('i').remove();
        }

        jQuery('.lp-notifaction-area').find('h4').text(res.msg);
        jQuery('.lp-notifaction-area').removeClass('lp-notifaction-success').addClass('lp-notifaction-error');
        jQuery('.lp-notifaction-area').addClass('active-wrap');
    }
}

jQuery(document).on('keyup', '#menu-type-new, #menu-group-new', function () {
    var typeGroupText = jQuery(this).val(),
        errMsg = jQuery(this).data('err'),
        re = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi;

    var isSplChar = re.test(typeGroupText);
    if (isSplChar) {
        var no_spl_char = typeGroupText.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');

        jQuery(this).val(no_spl_char);
        jQuery(this).after('<p>' + errMsg + '</p>');
    }

});
//Event detail page view more and less more
jQuery(document).ready(function () {
    jQuery('.lp-event-view-less').click(function (e) {
        e.preventDefault();
        var lessText = jQuery(this).data('contract');
        var moreText = jQuery(this).data('expand');
        if (jQuery(this).hasClass('event-shown')) {
            jQuery(this).removeClass('event-shown');
            jQuery(this).html(moreText);
            jQuery('.lp-attende-extra').removeClass('active');
        } else {
            jQuery(this).addClass('event-shown');
            jQuery('.lp-attende-extra').addClass('active');
            jQuery(this).html(lessText);
        }

    });

    /* for event gaddress */

    function initializeEventAddr() {
        if (jQuery('.event-addr').length > 0) {
            jQuery('.event-addr').each(function (index) {
                var input = document.getElementById(jQuery(this).attr('id'));
                var autocomplete = new google.maps.places.Autocomplete(input);
                google.maps.event.addListener(autocomplete, 'place_changed', function () {
                    var place = autocomplete.getPlace();
                    var lat = place.geometry.location.lat();
                    var lon = place.geometry.location.lng();
                    jQuery('input.latitude').val(lat);
                    jQuery('input.longitude').val(lon);
                });
            });
        }

    }

    google.maps.event.addDomListener(window, 'load', initializeEventAddr);

    /* gaddress ends */
});

jQuery(document).on('click', 'span.remove-menu-img', function (e) {
    e.preventDefault();
    var targetID = jQuery(this).data('target'),
        targetSrc = jQuery(this).data('src') + ',',
        targetImgs = jQuery('.active-upload').find('.frontend-input-multiple').val();
    if (targetImgs == undefined) {
        targetImgs = jQuery('#' + targetID).val();
    }
    targetImgs = targetImgs.replace(targetSrc, '');
    jQuery(this).closest('.menu-edit-img-wrap').remove();
    jQuery('input#' + targetID).val(targetImgs);
});

jQuery(document).on('click', '.select2-results ul li', function (e) {
    jQuery('.lp-pp-noa-tip').fadeIn();
});

jQuery('.select2-ajax-unique').on('select2:select', function (e) {
    jQuery('.lp-pp-noa-tip').fadeOut();
});

jQuery('.select2-ajax').on('select2:select', function (e) {
    jQuery('.lp-pp-noa-tip').fadeOut();
});

jQuery(document).on('click', '.remove-event-old-img', function (e) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();

    var $this = jQuery(this),
        targetID = $this.data('targetid');
    $this.closest('.removeable-image').find('.lp-uploaded-img').remove();
    jQuery('#' + targetID).val('');
    $this.remove();
});

jQuery(document).on('click', '.remove-event-img', function (e) {
    e.preventDefault();
    var $this = jQuery(this);
    if ($this.hasClass('remove-eei')) {
        var targetID = $this.data('targetid');
        $this.closest('.removeable-image').find('.frontend-image').attr('src', '');
        $this.closest('.removeable-image').find('.frontend-image').hide();
        $this.closest('.removeable-image').find('.lp-uploaded-img').remove();
        $this.closest('.removeable-image').find('.frontend-input').val('');
        jQuery('#event-old-img-' + targetID).val('');
        $this.remove();
    } else {
        $this.closest('.removeable-image').find('.frontend-image').attr('src', '');
        $this.closest('.removeable-image').find('.frontend-image').hide();
        $this.closest('.removeable-image').find('.frontend-input').val('');
        $this.remove();
    }
});

jQuery(document).on('click', '.lp-copy-code', function (e) {
    e.preventDefault();
    var $this = jQuery(this);
    var targetCodeEL = jQuery(this).data('target-code'),
        thisHtml = jQuery(this).data('html'),
        targetCodeELC = '.' + targetCodeEL;
    if ($this.hasClass('close-copy-pop')) {
        /*SAUD*/
        $this.closest('.lp-discount-widget').find(targetCodeELC).animate({
            bottom: '-' + jQuery(targetCodeELC).height() + 'px'
        }, 500, function (e) {
            $this.html(thisHtml);
            $this.removeClass('close-copy-pop');
        });
    } else {
        var bottomPlus = 0;
        if ($this.hasClass('lp-discount-btn')) {
            bottomPlus = 49;
        }

        var parent_class = '.coupons-bottom-content-wrap';

        if (jQuery(parent_class).length > 0) {
            parent_class = '.coupons-bottom-content-wrap';
        } else {
            parent_class = '.lp-deal';
            if (jQuery(parent_class).length > 0) {
                parent_class = '.lp-deal';
            } else {
                parent_class = '.lp-discount-widget';
            }
        }

        if (jQuery(parent_class).length < 1) {
            parent_class = '.lp-listing-offer';
        }

        $this.closest(parent_class).find(targetCodeELC).animate({
            bottom: bottomPlus + 'px'
        }, 500, function (e) {
            if ($this.hasClass('lp-discount-btn')) {
                $this.addClass('close-copy-pop');
                $this.html('<span><i class="fa fa-times"></i></span>');
            }
        });
    }
});
jQuery(document).on('click', '.close-right-icon', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        target = '.' + $this.data('target');

    jQuery(target).animate({
        bottom: '-' + jQuery(target).height() + 'px'
    });
});
jQuery(document).on('click', '.copy-now', function (e) {

    e.preventDefault();
    var targetCodeEL = jQuery(this).data('target-code'),
        targetCodeELC = '#' + targetCodeEL;

    jQuery(targetCodeELC).find('input[type="text"]').select();
    document.execCommand("copy");
    jQuery(targetCodeELC).find('.dis-code-copy-pop-inner-cell').find('p:first-child').text(jQuery('.copy-now').data('coppied-label'));
});


jQuery(document).on('click', '.lp-pagination.author-reviews-pagination span', function (e) {
    e.preventDefault();
    var paginNo = jQuery(this).data('pageurl');

    jQuery('.reviews-pagin-wrap').hide();
    jQuery('.reviews-pagin-wrap.reviews-pagin-wrap-' + paginNo).show();
});
jQuery(document).on('click', '.lp-filter-pagination-ajx ul li span.author-haspaglink', function (e) {
    e.preventDefault();
    var pageNo = jQuery(this).data('pageurl'),
        authorID = jQuery('.lp-author-nav').data('author'),
        authorPagin = 'yes',
        listingLayout = jQuery('#mylistings').data('listing-layout');

    jQuery('.lp-filter-pagination-ajx ul li span').removeClass('current');
    jQuery(this).addClass('current');

    jQuery('#mylistings').find('.author-inner-content-wrap').addClass('content-loading');
    jQuery('#mylistings #content-grids').remove();

    jQuery.ajax({
        type: 'POST',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'author_archive_tabs_cb',
            'pageNo': pageNo,
            'authorID': authorID,
            'authorPagin': authorPagin,
            'listingLayout': listingLayout,
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (data) {
            jQuery('#mylistings').find('.author-inner-content-wrap').removeClass('content-loading');
            jQuery('#mylistings').find('.author-inner-content-wrap').html(data);
            console.log(data);
        }
    });
});

jQuery(document).ready(function () {
    if (jQuery('.featuresDataContainer.lp-check-custom-wrapp').length > 0) {
        jQuery('.featuresDataContainerOuterSubmit').show();
        jQuery('.featuresDataContainer.lp-check-custom-wrapp').show();
    }
});
jQuery(document).ready(function () {
    jQuery('.lp-review-form-top .lp-listing-stars').click(function (e) {
        e.preventDefault();
        if (jQuery(this).hasClass('do-not-proceed')) {
        } else {
            jQuery(this).addClass('do-not-proceed');
            jQuery('.lp-review-form-bottom').slideToggle(500);
            jQuery('html,body').animate({
                scrollTop: jQuery(".lp-listing-review-form").offset().top - 100
            }, 'slow');
        }
    });
});
// for events
jQuery(document).on('change', '#toggle-attendees-check', function () {
    if (jQuery(this).is(':checked')) {
        jQuery('.attendee-checkbox').attr('checked', 'checked');
    } else {
        jQuery('.attendee-checkbox').removeAttr('checked');
    }
});
jQuery(document).on('click', '.download-attendees', function (e) {
    e.preventDefault();
});
jQuery(document).on('click', '#lp-send-message', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        msgError = jQuery('#event-msg-error').val(),
        msgSuccess = jQuery('#event-msg-success').val(),
        uid = $this.data('uid'),
        msgContent = jQuery('.attendeesmessage').val(),
        attendees = jQuery(".attendee-checkbox:checked").map(function () {
            return jQuery(this).val();
        }).get();

    var responseData = [];

    if (msgContent == '' || attendees == '') {
        responseData.status = 'error';
        responseData.msg = msgError;
        ajax_success_popup(responseData, $this);
        return false;
    }


    if ($this.hasClass('processing')) {

    } else {
        $this.append('<i class="fa fa-spinner fa-spin"></i>');
        $this.addClass('processing');
        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'send_attendees_msg',
                'msgContent': msgContent,
                'attendees': attendees,
                'uid': uid,
                'lpNonce': jQuery('#lpNonce').val()
            },
            success: function (res) {
                responseData.status = 'success';
                responseData.msg = msgSuccess;
                ajax_success_popup(responseData, $this);
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
});
jQuery(document).on('click', '.open-send-msg-form, .cancel-send-mas-atten', function (e) {
    e.preventDefault();
    jQuery('#notification-form').slideToggle('fast', function () {
        jQuery("html, body").animate({ scrollTop: jQuery('#notification-form').offset().top }, 1000);
    });
});

jQuery(document).on('click', '.attendees-pagination span', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        pageNo = $this.data('pageurl'),
        targetC = '.attendees-pagin-wrap-' + pageNo;

    if (jQuery(this).hasClass('current')) {
        return false;
    }
    jQuery('.attendees-pagination span.current').removeClass('current');
    $this.addClass('current');
    jQuery('.current-pagin-wrap').fadeOut(500, function () {
        jQuery('.current-pagin-wrap').removeClass('current-pagin-wrap');
        jQuery(targetC).fadeIn(500, function () {
            jQuery(targetC).addClass('current-pagin-wrap');
        })
    });
});

jQuery(document).on('click', '.listing-tabs-element li a', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        taxonomy = $this.attr('data-tax'),
        term = $this.attr('data-term'),
        numPost = $this.attr('data-num'),
        layout = $this.attr('data-layout'),
        list = $this.attr('data-list'),
        grid = $this.attr('data-grid');


    jQuery('.listing-tabs-element li.active').removeClass('active');
    $this.closest('li').addClass('active');
    jQuery('#listing-tabs-inner-container').html();
    jQuery('#listing-tabs-inner-container').closest('.wpb_wrapper').find('.listingcampaings').remove();
    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'listing_tabs_get_listings',
            'taxonomy': taxonomy,
            'term': term,
            'numPost': numPost,
            'layout': layout,
            'list': list,
            'grid': grid,
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (res) {
            jQuery('#listing-tabs-inner-container').html(res);
            jQuery('#listing-tabs-inner-container').find('.listingcampaings').remove();

            jQuery('#listing-tabs-inner-container').find('.app-view-new-ads-slider').slick({
                infinite: true,
                slidesToShow: 1,
                slidesToScroll: 1,
                arrows: false
            });

        },
        error: function (err) {
            console.log(err);
        }
    });

})

//for events calander
jQuery(document).on('click', '.calender-header-switcher ul li', function () {
    var $this = jQuery(this);

    jQuery('.calender-header-switcher ul li.active').removeClass('active');
    $this.addClass('active');

    var calanderType = 'event-calender-list-view';
    if (jQuery('.calender-type-wrap').length > 0) {
        calanderType = jQuery('.calender-type-wrap').data('ctype');
    }

    getCalanderMapView(calanderType, $this);

});
jQuery(document).on('click', '.close-active-box', function (e) {
    e.preventDefault();
    jQuery('.current-active-box').removeClass('current-active-box');
    jQuery('.active-event-for-map').removeClass('active-event-for-map');
    jQuery('.caew-box').removeClass('caew-box').fadeOut(500);
    jQuery('.event-calander-classic2').fadeOut(500);
    jQuery('.calender-header-switcher ul li').removeClass('active');
    jQuery('.calender-header-switcher ul li.show-calader-list').addClass('active');
    jQuery('.calender-type-wrap').attr('data-activetoggle', 'calander');
    if (jQuery('.event-calander-classic2').length) {
        jQuery('.event-by-day-wrap').fadeOut();
    }
});
jQuery(document).on('click', '.week-day-date-box.has-events', function (e) {
    e.preventDefault();

    var $this = jQuery(this),
        ewtTarget = $this.data('ewt'),
        targetDate = $this.data('todaytime'),
        targetDateA = targetDate.split('-');

    jQuery('.current-active-box').removeClass('current-active-box');
    if ($this.hasClass('current-active-box')) {
        $this.removeClass('current-active-box');
        jQuery('.active-event-for-map').removeClass('active-event-for-map');
        jQuery('.caew-box').removeClass('caew-box').fadeOut(500);
        jQuery('.event-calander-classic2').fadeOut(500);
        return false;
    } else {
        $this.addClass('current-active-box');
    }
    if (jQuery('.modern-calender-inner-left').length > 0) {
        if (jQuery('.events-by-day-wrap.caew-box').length > 0) {
            if (jQuery('.calender-type-wrap').attr('data-activetoggle') == 'map') {
                jQuery('.active-event-for-map').removeClass('active-event-for-map');
                jQuery('.events-by-day-wrap[data-ebdt="' + ewtTarget + '"]').addClass('caew-box active-event-for-map');
                jQuery('.calender-header-switcher ul li.show-calander-map').trigger('click');
            } else {
                jQuery('.active-event-for-map').removeClass('active-event-for-map');
                jQuery('.caew-box').removeClass('caew-box').fadeOut(500, function () {
                    jQuery('.events-by-day-wrap[data-ebdt="' + ewtTarget + '"]').addClass('caew-box active-event-for-map').fadeIn();
                });
            }
        } else {
            jQuery('.events-by-day-wrap[data-ebdt="' + ewtTarget + '"]').addClass('caew-box active-event-for-map').fadeIn();
        }
        jQuery('.calender-header-moderen-date2 .today-event-date-container p').html(targetDateA[1] + ' ' + targetDateA[0] + '<span>' + targetDateA[2] + '</span>');
    } else {
        if (jQuery('.event-calander-classic2').length > 0) {
            showClassic2CalEvents(ewtTarget, targetDate);
        } else {
            showClassicCalEvents(ewtTarget);
        }
    }

});
jQuery(document).on('click', '.get-npm', function (e) {
    e.preventDefault();
    if (jQuery(this).hasClass('disabled')) {
        return false;
    }
    var $this = jQuery(this),
        targetDate = $this.data('npmnum'),
        currentCMN = jQuery('.cc-month').data('cmn'),
        cTypClass = jQuery('.calender-type-wrap').data('ctype'),
        cTypee = 'classic',
        targetAction = 'nm',
        currentMN = '',
        currentYN = '',
        per_page = '';

    if (jQuery('#event_per_page').length > 0) {
        per_page = jQuery('#event_per_page').val();
    }
    if (cTypee == 'classic' && jQuery('#ec_classic2_check').length > 0) {
        cTypee = jQuery('#ec_classic2_check').val();
    }
    if (cTypClass == 'event-calender-modern') {
        cTypee = 'modern';
    }
    if (cTypClass == 'event-calender-list-view') {
        cTypee = 'list'
    }
    if (cTypClass == 'event-calender-classic-weekly') {
        cTypee = 'weekly';
    }
    if (currentCMN.indexOf(',') > -1) {
        var currentCMNArr = currentCMN.split(','),
            currentMN = currentCMNArr[0],
            currentYN = currentCMNArr[1];
    }

    if ($this.hasClass('btn-pm')) {
        targetAction = 'pm';
    }

    if (targetDate.indexOf(',') > -1) {
        var targetDateArr = targetDate.split(','),
            targetDateM = targetDateArr[0],
            targetDateY = targetDateArr[1];


        jQuery('.' + cTypClass).fadeOut(500, function () {
            jQuery('.event-spinner').fadeIn();
        });

        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'get_event_calender_data',
                'targetDateM': targetDateM,
                'targetDateY': targetDateY,
                'targetAction': targetAction,
                'currentMN': currentMN,
                'currentYN': currentYN,
                'cTypee': cTypee,
                'per_page': per_page,
                'lpNonce': jQuery('#lpNonce').val()
            },
            success: function (res) {
                if (res.status == 'success') {
                    jQuery('.prev-mon-markup').html(res.prev_mon_markup);
                    jQuery('.next-mon-markup').html(res.next_mon_markup);
                    jQuery('.curr-mon-markup').html(res.curr_mon_markup);

                    if (cTypee == 'weekly') {
                        jQuery('.event-calender-weekly').html(res.calender_markup);
                        jQuery('.event-calender-weekly').addClass('events-after-ajax');

                        var weekFirstDate = jQuery('.week-days-wrap.active-week .lp-week-days-wrape-inner-container .week-day-box:first .week-day-date').text();
                        var weekLastDate = jQuery('.week-days-wrap.active-week .lp-week-days-wrape-inner-container .week-day-box:last .week-day-date').text();

                        if (weekFirstDate == '') {
                            weekFirstDate = '1';
                        }
                        if (weekLastDate == '') {
                            weekLastDate = '31';
                        }
                        getActiveWeekEvents(weekFirstDate, weekLastDate);
                    } else {
                        jQuery('.event-calender-monthly').html(res.calender_markup);
                        if (cTypee == 'modern') {
                            if (jQuery('.month-dates-wrap .week-day-date-box.has-events').length) {
                                var target_first_event = jQuery('.month-dates-wrap .week-day-date-box.has-events:first').attr('data-ewt'),
                                    target_daytime = jQuery('.month-dates-wrap .week-day-date-box.has-events:first').attr('data-todaytime');
                            } else {
                                var target_first_event = jQuery('.month-dates-wrap .week-day-date-box.has-no-events:first').attr('data-ewt'),
                                    target_daytime = jQuery('.month-dates-wrap .week-day-date-box.has-no-events:first').attr('data-todaytime');
                            }
                            var target_daytime_arr = target_daytime.split('-');
                            var target_day_markup = target_daytime_arr[1] + ' ' + target_daytime_arr[0] + ' <span>' + target_daytime_arr[2] + '</span>';
                            jQuery('.events-by-day-wrap[data-ebdt=' + target_first_event + ']').addClass('caew-box active-event-for-map').fadeIn();
                            jQuery('.today-event-date-container p').html(target_day_markup);
                        }

                    }
                    jQuery('.event-spinner').fadeOut(500, function () {
                        jQuery('.' + cTypClass).fadeIn();
                    });
                }
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
});
jQuery(document).on('click', '.event-pager ul li span', function (e) {
    var $this = jQuery(this),
        pageNo = $this.data('pageno');

    if ($this.hasClass('current')) {
        return false;
    }
    jQuery('.event-pager ul li .current').removeClass('current');
    $this.addClass('current');
    jQuery('.list-calendar-pager-wrap.current-event-page-active').fadeOut(500, function () {

        jQuery('.list-calendar-pager-wrap.current-event-page-active').removeClass('current-event-page-active');
        jQuery('.list-calendar-pager-wrap .active-event-for-map').removeClass('active-event-for-map');

        if (jQuery('.calender-type-wrap').attr('data-activetoggle') == 'map') {
            jQuery('.list-calendar-pager-wrap:eq( ' + pageNo + ' )').addClass('current-event-page-active');
            jQuery('.current-event-page-active .events-by-day-wrap').addClass('active-event-for-map');
            jQuery('.calender-header-switcher ul li.show-calander-map').trigger('click');
        } else {
            jQuery('.list-calendar-pager-wrap:eq( ' + pageNo + ' )').fadeIn(500, function () {
                jQuery('.list-calendar-pager-wrap:eq( ' + pageNo + ' )').addClass('current-event-page-active');
                jQuery('.current-event-page-active .events-by-day-wrap').addClass('active-event-for-map');
            });
        }

    });
});
jQuery(document).on('click', '.event-npw', function () {
    var $this = jQuery(this),
        targetWeek = $this.data('targetweek');

    var maxWeeks = jQuery('.event-calender-weekly .week-days-wrap').length;

    if (targetWeek > 0 && targetWeek <= maxWeeks) {
        jQuery('.week-days-wrap.active-week').removeClass('active-week');

        jQuery('.week-days-wrap').hide();
        jQuery('.event-week-' + targetWeek).show();
        jQuery('.week-days-wrap.event-week-' + targetWeek).addClass('active-week');

        var weekFirstDate = jQuery('.week-days-wrap.active-week .lp-week-days-wrape-inner-container .week-day-box:first .week-day-date').text();
        var weekLastDate = jQuery('.week-days-wrap.active-week .lp-week-days-wrape-inner-container .week-day-box:last .week-day-date').text();

        if (weekFirstDate == '') {
            weekFirstDate = '1';
        }
        if (weekLastDate == '') {
            weekLastDate = '31';
        }
        getActiveWeekEvents(weekFirstDate, weekLastDate);
    }
});
jQuery(document).on('click', '.week-days-wrap .week-day-box.has-events', function () {

    var $this = jQuery(this),
        targetE = $this.data('ewt');

    jQuery('.events-for-day:visible').slideUp('fast', function () {
        jQuery('.' + targetE).slideDown('fast');
    });

});
jQuery(document).ready(function () {
    jQuery('.active-week').removeClass('active-week');
    jQuery('.week-day-box.has-events:first').closest('.week-days-wrap').addClass('active-week');

    var weekFirstDate = jQuery('.week-days-wrap.active-week .lp-week-days-wrape-inner-container .week-day-box:first .week-day-date').text();
    var weekLastDate = jQuery('.week-days-wrap.active-week .lp-week-days-wrape-inner-container .week-day-box:last .week-day-date').text();

    getActiveWeekEvents(weekFirstDate, weekLastDate);

    if (jQuery('.event-calender-modern').length > 0) {
        jQuery('.week-day-date-box.has-events:first').trigger('click');
    }

});

function showClassicCalEvents(ewtTarget) {
    jQuery('.event-calender-classic-map').empty();
    if (jQuery('.events-by-day-wrap.caew-box').length > 0) {
        jQuery('.active-event-for-map').removeClass('active-event-for-map');
        jQuery('.caew-box').removeClass('caew-box').fadeOut(500, function () {
            jQuery('.events-by-day-wrap[data-ebdt="' + ewtTarget + '"]').addClass('caew-box').fadeIn();
            jQuery('.events-by-day-wrap[data-ebdt="' + ewtTarget + '"]').find('.event-by-day-wrap').addClass('active-event-for-map');
            if (jQuery('.calender-type-wrap').attr('data-activetoggle') == 'map') {
                jQuery('.active-event-for-map').hide();
                jQuery('.calender-header-switcher ul li.show-calander-map.show-calander-map-' + ewtTarget).trigger('click');
            } else {
                jQuery('.calender-header-switcher ul li.show-calader-list').addClass('active');
                jQuery('.active-event-for-map').show();
            }
        });
    } else {
        jQuery('.active-event-for-map').removeClass('active-event-for-map');
        jQuery('.events-by-day-wrap[data-ebdt="' + ewtTarget + '"]').addClass('caew-box').fadeIn();
        jQuery('.events-by-day-wrap[data-ebdt="' + ewtTarget + '"]').find('.event-by-day-wrap').addClass('active-event-for-map');
        if (jQuery('.calender-type-wrap').attr('data-activetoggle') != 'map') {
            jQuery('.events-by-day-wrap[data-ebdt="' + ewtTarget + '"]').find('.event-by-day-wrap').fadeIn();
        }
    }
}

function showClassic2CalEvents(ewtTarget, targetDate) {

    var TargetDate = targetDate.split('-');

    jQuery('.event-calander-classic2 .today-event-date-container span').text(TargetDate[1] + ' ' + TargetDate[0]);
    jQuery('.event-calender-classic-map').empty();
    jQuery('.active-event-for-map').hide().removeClass('active-event-for-map');
    jQuery('.event-calander-classic2').fadeIn(500);
    if (jQuery('.calender-type-wrap').attr('data-activetoggle') == 'map') {
        jQuery('.event-calander-classic2 .event-by-day-wrap[data-ebdt="' + ewtTarget + '"]').addClass('active-event-for-map');
        jQuery('.event-calander-classic2 .calender-header-switcher .show-calander-map').trigger('click');
    } else {
        jQuery('.event-calander-classic2 .event-by-day-wrap[data-ebdt="' + ewtTarget + '"]').addClass('active-event-for-map').fadeIn();
    }
}

function getActiveWeekEvents(weekFirstDate, weekLastDate) {
    jQuery('.event-calender-weekly .event-by-day-wrap-inner.events-for-day').each(function () {
        var $this = jQuery(this),
            targetDate = $this.data('targetdate');
        $this.removeClass('active-event-for-map');
        $this.fadeOut(500);

        if (targetDate >= weekFirstDate && targetDate <= weekLastDate) {
            $this.addClass('active-event-for-map');
            if (
                jQuery('.calender-type-wrap').attr('data-activetoggle') == 'calander' ||
                jQuery('.calender-type-wrap').attr('data-activetoggle') == undefined
            ) {
                $this.fadeIn(500);
            }
        }
    });
    if (jQuery('.calender-type-wrap').attr('data-activetoggle') == 'map') {
        jQuery('.calender-header-switcher ul li.show-calander-map').trigger('click');
    }
}

function getCalanderMapView(cType, $this) {
    var mapWrapTartget = '.event-calender-weekly-map',
        eventWrapTarget = '.event-by-day-wrap-inner',
        mapContainer = 'map';

    if (cType == 'event-calender-list-view') {
        mapWrapTartget = '.event-calander-list-map';
        eventWrapTarget = '.current-event-page-active';
    }
    if (cType == 'event-calender-modern') {
        mapWrapTartget = '.event-calander-moder-map';
        eventWrapTarget = '.events-by-day-wrap.active-event-for-map';
    }
    if (cType == 'event-calender-classic') {
        eventWrapTarget = '.event-by-day-wrap.active-event-for-map';
        if (jQuery('.event-calander-classic2').length == 0) {
            var mapDate = $this.data('targetdate');
            mapWrapTartget = '.event-calender-classic-map.classic-map-' + mapDate;
        } else {
            mapWrapTartget = '.event-calender-classic-map';
        }
    }

    if ($this.hasClass('show-calander-map')) {
        jQuery('div[data-ctype="' + cType + '"]').attr('data-activetoggle', 'map');
        jQuery(eventWrapTarget).fadeOut(500, function () {
            jQuery(mapWrapTartget).empty();
            jQuery(mapWrapTartget).html('<div id="map" class="event-calander-map"></div>');
            jQuery(mapWrapTartget).fadeIn();
            loadCalanderMap(mapContainer);
        });
    }
    if ($this.hasClass('show-calader-list')) {
        jQuery('div[data-ctype="' + cType + '"]').attr('data-activetoggle', 'calander');
        jQuery(mapWrapTartget).fadeOut(500, function () {
            if (cType == 'event-calender-classic-weekly') {
                var weekFirstDate = jQuery('.week-days-wrap.active-week .lp-week-days-wrape-inner-container .week-day-box:first .week-day-date').text();
                var weekLastDate = jQuery('.week-days-wrap.active-week .lp-week-days-wrape-inner-container .week-day-box:last .week-day-date').text();
                getActiveWeekEvents(weekFirstDate, weekLastDate);
            }
            if (cType == 'event-calender-list-view' || cType == 'event-calender-modern' || cType == 'event-calender-classic') {
                jQuery(eventWrapTarget).fadeIn(500);
            }

        });
    }
}

function loadCalanderMap(mapContainer) {
    var defmaplat = jQuery('body').data('defaultmaplat');
    var defmaplong = jQuery('body').data('defaultmaplot');

    var map = null
    $mtoken = jQuery('#page').data("mtoken");
    $mtype = jQuery('#page').data("mtype");
    $mapboxDesign = jQuery('#page').data("mstyle");

    if ($mtoken != '' && $mtype == 'mapbox') {

        L.mapbox.accessToken = $mtoken;
        map = L.mapbox.map(mapContainer);
        L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
            id: jQuery('#page').data("mstyle"),
            accessToken: jQuery('#page').data("mtoken")
        }).addTo(map);

        var markers = new L.MarkerClusterGroup();
        initializeMap(markers);
        if (markers === undefined) {
        } else {
            map.fitBounds(markers.getBounds());
            map.scrollWheelZoom.disable();
        }
    } else {

        var map = new L.Map('map', {
            minZoom: 3,
        }).setView(new L.LatLng(defmaplat, defmaplong), 18);
        if ($mtype == 'google') {
            L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
                maxZoom: 18,
                subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
                noWrap: true,
            });
            var googleLayer = new L.Google('ROADMAP');
            map.addLayer(googleLayer);
        } else {
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
        }
        var markers = new L.MarkerClusterGroup();
        initializeMap(markers);
        if (markers === undefined) {
        } else {

            map.fitBounds(markers.getBounds(), { padding: [50, 50] });

        }
    }

    function initializeMap(markers) {
        markers.clearLayers();
        if (jQuery('.active-event-for-map').length > 0) {
            jQuery('.active-event-for-map').each(function () {
                var LPtitle = jQuery(this).data("title"),
                    siteURL = jQuery('#page').data("site-url");
                LPposturl = jQuery(this).data("posturl"),
                    LPlattitue = jQuery(this).data("lattitue"),
                    LPlongitute = jQuery(this).data("longitute"),
                    LPpostid = jQuery(this).data("postid"),
                    LPimageSrc = jQuery(this).find('.event-img').find('img').attr('src'),
                    LPaddress = jQuery(this).data('address');

                if (LPlattitue != '' && LPlongitute != '') {
                    var LPimage = '';
                    if (LPimageSrc != '') {
                        LPimage = LPimageSrc;
                    }

                    var markerLocation = new L.LatLng(LPlattitue, LPlongitute); // London

                    var CustomHtmlIcon = L.HtmlIcon.extend({
                        options: {
                            html: "<div class='lpmap-icon-shape pin card" + LPpostid + "'><div class='lpmap-icon-contianer'><img alt='image' src='" + siteURL + "/wp-content/themes/listingpro/assets/images/pins/lp-logo.png' /></div></div>",
                        }
                    });

                    var customHtmlIcon = new CustomHtmlIcon();
                    var marker = new L.Marker(markerLocation, { icon: customHtmlIcon }).bindPopup('<div class="map-post"><div class="map-post-thumb"><a href="' + LPposturl + '"><img alt="image" src="' + LPimage + '" ></a></div><div class="map-post-des"><div class="map-post-title"><h5><a href="' + LPposturl + '">' + LPtitle + '</a></h5></div><div class="map-post-address"><p><i class="fa fa-map-marker"></i> ' + LPaddress + '</p></div></div></div>').addTo(map);

                    markers.addLayer(marker);
                    map.addLayer(markers);
                }
            });

        } else {
            alert('no listing found');
        }

    }
}

jQuery(document).on('click', '.event-tickets-list-dash i', function (e) {
    var $this = jQuery(this),
        $thisWrap = $this.closest('.event-tickets-list-dash'),
        currentUrls = $thisWrap.find('input[type="hidden"]').val(),
        ticketPlatform = $this.attr('data-ticket-platform'),
        ticketUrl = $this.attr('data-ticket-url'),
        newUrls = '';
    if (currentUrls.indexOf(',') > -1) {
        if (currentUrls.indexOf(',' + ticketPlatform) > -1) {
            var findStr = ',' + ticketPlatform + '|' + ticketUrl;
        } else {
            var findStr = ticketPlatform + '|' + ticketUrl;
        }
        newUrls = currentUrls.replace(findStr, '');
    } else {
        var findStr = ticketPlatform + '|' + ticketUrl;
        newUrls = currentUrls.replace(findStr, '');
    }
    $thisWrap.find('input[type="hidden"]').val(newUrls);
    jQuery(this).closest('li').remove();
});

jQuery(document).on('click', '#add-event-ticket-platform', function (e) {
    var thisWrap = jQuery(this).closest('.lp-coupon-box-row'),
        ticketPlatform = thisWrap.find('.event-tickets-platforms').val(),
        ticketUrl = thisWrap.find('.event-ticket-url').val(),
        currentUrls = thisWrap.find('input[type="hidden"]').val();
    if (ticketUrl == '') {
        thisWrap.find('.event-ticket-url').addClass('error');
        return false;
    } else {
        thisWrap.find('.event-ticket-url').removeClass('error');
    }
    if (ticketPlatform == '') {
        thisWrap.find('.event-tickets-platforms').addClass('error');
        return false;
    } else {
        thisWrap.find('.event-tickets-platforms').removeClass('error');
    }
    var embedMarkup = '<li><strong>' + ticketPlatform + '</strong> ' + ticketUrl + ' <i class="fa fa-times" data-ticket-platform="' + ticketPlatform + '" data-ticket-url="' + ticketUrl + '"></i></li>';
    thisWrap.find('.event-tickets-list-dash ul').append(embedMarkup);

    if (currentUrls == '') {
        thisWrap.find('input[type="hidden"]').val(ticketPlatform + '|' + ticketUrl);
    } else {
        thisWrap.find('input[type="hidden"]').val(currentUrls + ',' + ticketPlatform + '|' + ticketUrl);
    }
});

jQuery(document).on('click', '#add-new-service', function (e) {
    var $this = jQuery(this),
        uid = $this.attr('data-uid'),
        $thisWrap = $this.closest('.ordering-service-wrap'),
        serviceVal = $thisWrap.find('select').val(),
        serviceUrl = $thisWrap.find('input#service_url').val();
    if ($thisWrap.find('li:contains("' + serviceVal + '")').length) {
        $thisWrap.find('li:contains("' + serviceVal + '")').css('color', 'red');
        return false;
    }
    if (jQuery('#service_url').val().length < 1) {
        jQuery('.form-group.menu_online_order_url').addClass('with_error');
        return false;
    } else {
        jQuery('.form-group.menu_online_order_url').removeClass('with_error');
        if (/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(jQuery("#service_url").val())) {
            jQuery('.form-group.menu_online_order_url').removeClass('with_error');

        } else {
            jQuery('.form-group.menu_online_order_url').addClass('with_error');
            return false;

        }
    }

    jQuery('#add-new-service-spinner').fadeIn();
    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'add_menu_service_cb',
            'serviceVal': serviceVal,
            'serviceUrl': serviceUrl,
            'user_id': uid,
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (res) {
            jQuery('.form-group.menu_online_order_url').removeClass('with_error');
            if (res.status == 'success') {
                jQuery('#add-new-service-spinner').fadeOut();
                $thisWrap.find('li.no-services').remove();
                $thisWrap.find('ul').append(res.msg);
            }
            console.log(res);
        },
        error: function (err) {
            alert(err);
            $this.find('i').remove();
        }
    });
});
jQuery(document).on('click', '#add-new-type', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        $thisWrap = $this.closest('#manage-types-content'),
        newType = $thisWrap.find('input[type="text"]').val(),
        uid = $this.data('uid');
    if (newType == '') {
        $thisWrap.find('input[type="text"]').addClass('error');
        return false;
    } else {
        $thisWrap.find('input[type="text"]').removeClass('error');
        $this.addClass('processing');
    }
    if ($thisWrap.find('li:contains("' + newType + '")').length) {
        $thisWrap.find('li:contains("' + newType + '")').css('color', 'red');
        return false;
    }
    jQuery('#add-new-type-spinner').fadeIn();
    $this.hide();
    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'add_menu_type_cb',
            'user_id': uid,
            'type': newType,
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (res) {
            jQuery('#add-new-type-spinner').fadeOut();
            $this.removeClass('processing');
            $this.show();
            $thisWrap.find('input[type="text"]').val('');
            jQuery('.lp-menu-step-one .panel-heading .nav-tabs li.active').removeClass('active');
            jQuery('.lp-menu-step-one .panel-body .tab-content .tab-pane.active').removeClass('in active');
            var embed_markup = '<li>' + newType + ' <span class="del-group-type del-type del-this" data-uid="' + uid + '" data-targetid="' + res.data_index + '"><i class="fa fa-trash"></i></span></li>';
            var embed_tab = '<li class="active"><a href="#type-' + newType + '" data-toggle="tab">' + newType + '</a></li>';
            var embed_tab_cn = '<div class="tab-pane fade in active" id="type-' + newType + '"></div>';
            $thisWrap.find('ul').append(embed_markup);
            jQuery('.lp-menu-step-one .panel-heading .nav-tabs').append(embed_tab);
            jQuery('.lp-menu-step-one .panel-body .tab-content').append(embed_tab_cn);
        },
        error: function (err) {
            alert(err);
            $this.find('i').remove();
            $this.show();
        }
    });
});
jQuery(document).on('click', '#add-new-group', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        $thisWrap = $this.closest('#manage-groups-content'),
        newGroup = $thisWrap.find('input[type="text"]').val(),
        uid = $this.data('uid');
    if (newGroup == '') {
        $thisWrap.find('input[type="text"]').addClass('error');
        return false;
    } else {
        $thisWrap.find('input[type="text"]').removeClass('error');
        $this.addClass('processing');
    }
    if ($thisWrap.find('li:contains("' + newGroup + '")').length) {
        $thisWrap.find('li:contains("' + newGroup + '")').css('color', 'red');
        return false;
    }
    jQuery('#add-new-group-spinner').fadeIn();
    $this.hide();
    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'add_menu_group_cb',
            'user_id': uid,
            'group': newGroup,
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (res) {
            jQuery('#add-new-group-spinner').fadeOut();
            $this.removeClass('processing');
            $this.show();
            $thisWrap.find('input[type="text"]').val('');
            var embed_markup = '<li>' + newGroup + ' <span class="del-group-type del-group del-this" data-uid="' + uid + '" data-targetid="' + res.data_index + '"><i class="fa fa-trash"></i></span></li>';
            $thisWrap.find('ul').append(embed_markup);
            var optData = {
                id: newGroup,
                text: newGroup
            };
            var newOption = new Option(optData.text, optData.id, false, false);
            jQuery('#menu-group').append(newOption).trigger('change');
            var currentGroups = jQuery('#menu-group').val();
            if (currentGroups == null) {
                jQuery('#menu-group').val(group).trigger('change');
            } else {
                currentGroups.push(group);
                jQuery('#menu-group').val(currentGroups).trigger('change');
            }
        },
        error: function (err) {
            $this.show();
            alert(err);
            $this.find('i').remove();
        }
    });
});
jQuery(document).on('click', '.manange-typs-groups-tabs li', function (e) {
    e.preventDefault();
    jQuery('.manange-typs-groups-tabs li.active').removeClass('active');
    jQuery(this).addClass('active');

    var targetID = jQuery(this).attr('id');

    if (targetID == 'manage-types-tab') {
        jQuery('#manage-groups-content').removeClass('active-content');
        jQuery('#manage-types-content').addClass('active-content');
    } else {
        jQuery('#manage-types-content').removeClass('active-content');
        jQuery('#manage-groups-content').addClass('active-content');
    }
});
jQuery('#menu-group').on('select2:select', function (e) {
    jQuery('#menu-form-toggle').slideDown();
});

function myFuction(el) {
    jQuery(el).find('.show-number').css('display', 'none');
    jQuery(el).find('.grind-number').css('display', 'inline-block');
}

jQuery(document).on('click', '.listing-app-view-new-discount', function () {
    var $this = jQuery(this),
        target = $this.closest('.app-view2-first-recent');

    jQuery('.app-view2-first-recent').find('.popover_overlay.active_popover_overlay').removeClass('active_popover_overlay');

    if ($this.hasClass('current-active-pop')) {
        $this.removeClass('current-active-pop')
    } else {
        $this.addClass('current-active-pop');
        target.find('.popover_overlay').addClass('active_popover_overlay');
    }
});


/* ******************  SHOW ALL MENUS OF SELECTED LISTING  ******************* */
jQuery(document).on('change', '#lp-menus #menu-listing', function () {

    var selectedListingID = jQuery(this).find(":selected").val();


    jQuery.ajax({
        dataType: 'html',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'listingpro_dashboard_menu_of_listing',
            'selectedListingID': selectedListingID,
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (res) {
            jQuery('.lp-compaignForm-leftside .lp-menu-panel-body-outer').html(res);
        },
        error: function (err) {
            console.log(err);
        },
    });

});

/* ******************  DELETE ALL MENUS OF LISTING  ******************* */
jQuery(document).on('click', '.del-this-menu', function (e) {
    e.preventDefault();
    jQuery('.remove-active-menu').removeClass('remove-active-menu');
    jQuery(this).addClass('remove-active-menu');
    jQuery('#dashboard-delete-modal3').modal('show');
    jQuery('.modal-backdrop').hide();
});
jQuery(document).on('click', '.dashboard-confirm-del-menu-btn', function (e) {
    var $this = jQuery('.remove-active-menu'),
        lid = $this.data('targetid'),
        user_id = $this.data('uid');

    jQuery(this).append('<i class="fa fa-spin fa-spinner" style="margin-left: 5px;"></i>');

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_search_term_object.ajaxurl,
        data: {
            'action': 'del_assigned_menu_to_listing',
            'user_id': user_id,
            'lid': lid,
            'lpNonce': jQuery('#lpNonce').val()
        },
        success: function (res) {
            if (res.status == 'success') {
                location.reload();
            }
            $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-trash-o');
        },
        error: function (err) {
            console.log(err);
            $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-trash-o');
        }
    });
});
jQuery(document).on('click', '.open-edit-this-menu', function (e) {
    e.preventDefault();
    var targetID = jQuery(this).data('targetid'),
        listingTitle = jQuery(this).data('targettitle');

    jQuery('.panel.with-nav-tabs.panel-default.lp-dashboard-tabs').fadeOut("slow", function () {
        jQuery('div.tab-pane.fade.in.active.clearfix.lp-dashboard-menu-container').fadeIn("fast", function () {
            jQuery('div.panel.with-nav-tabs.panel-default.lp-dashboard-tabs.lp-left-panel-height.lp-left-panel-height-outer').fadeIn("fast");
        });
    });

    if (jQuery('#menu-listing').hasClass('select2-ajax')) {
        if (jQuery('#menu-listing').find("option[value='" + targetID + "']").length) {
            jQuery('#menu-listing').val(targetID).trigger('change');
        } else {
            var newOption = new Option(listingTitle, targetID, true, true);
            jQuery('#menu-listing').append(newOption).trigger('change');
        }
    } else {
        jQuery('#menu-listing').val(targetID);
        jQuery('#menu-listing').trigger('change');
    }

});

jQuery(document).on('click', '.discount-bar', function (e) {
    var $this = jQuery(this),
        thisWrap = $this.closest('.lp-listing-bottom-right');

    $this.toggleClass('active-discount-bar');

    if ($this.hasClass('active-discount-bar')) {
        $this.find('i.pull-right').removeClass('fa-chevron-down').addClass('fa-chevron-up');
    } else {
        $this.find('i.pull-right').removeClass('fa-chevron-up').addClass('fa-chevron-down');
    }


    thisWrap.find('.coupons-bottom-content-wrap').slideToggle(function () {
        $this.closest('.lp-listing-bottom-right').toggleClass('active');
    });
});

jQuery(document).on('click', '.del-order-service', function (e) {
    var $this = jQuery(this),
        uid = $this.attr('data-uid'),
        target = $this.attr('data-target');

    if ($this.hasClass('active-ajax')) {

    } else {
        $this.addClass('active-ajax');
        $this.find('i').removeClass('fa-trash').addClass('fa-spinner fa-spin');

        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'del_ordering_service',
                'uid': uid,
                'target': target,
                'lpNonce': jQuery('#lpNonce').val()
            },
            success: function (res) {
                if (res.status == 'success') {
                    $this.closest('li').remove();
                }
            },
            error: function (err) {
                console.log(err);
                $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-trash-o');
            }
        });
    }
});
jQuery(document).on('click', '.delete-my-review', function (e) {
    e.preventDefault();
    var $this = jQuery(this),
        reviewID = $this.attr('data-reviewid');

    if ($this.hasClass('active-ajax')) {

    } else {
        $this.addClass('active-ajax');
        $this.append('<i class="fa fa-spinner fa-spin" style="margin-left: 5px;"></i>');

        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_search_term_object.ajaxurl,
            data: {
                'action': 'delete_own_review',
                'reviewID': reviewID,
                'lpNonce': jQuery('#lpNonce').val()
            },
            success: function (res) {
                location.reload();
            },
            error: function (err) {
                console.log(err);
                $this.find('i').removeClass('fa-spin fa-spinner').addClass('fa-trash-o');
            }
        });
    }

});
jQuery(document).ready(function () {
    jQuery('.lp-ad-location-image').click(function (e) {
        e.preventDefault();
        var img_src = jQuery(this).find('img').data('model_img_src_ad');
        jQuery('#ad_preview').find('img#imgsrc').attr('src', img_src);
    });
});
jQuery(document).on('click', '.app-view2-show-search', function (e) {
    e.preventDefault();
    var inputField = jQuery('.dropdown_fields');
    inputField.trigger('click');
});
//change in classic new
jQuery(document).ready(function () {
    // Function to get and display the height of the div
    function checkDivHeight() {
        var divHeight = jQuery('#wpadminbar').height();
        if (jQuery('#wpadminbar').length > 0) {
            divHeight = divHeight;
        }
        jQuery('.page-container:not(.lp-sidebar-filters-style) .outer_all_page_overflow').css({
            "padding-top": divHeight
        });
        jQuery('.header-more-filters .lp_all_page_overflow').css({
            "padding-top": divHeight
        });
        jQuery(document).on('click', '.lp-header-search-filters .more-filters.lp-advence-filtr-colr', function () {
            jQuery('.header-more-filters .lp_all_page_overflow').css({
                "padding-top": divHeight
            });
        })
    }
    jQuery(window).resize(function () {
        checkDivHeight();


    });
    jQuery(document).on('click', '.lp_all_page_overflow_after', function () {
        jQuery(this).closest('.outer_all_page_overflow').removeClass('hide-filters');
    });

    jQuery('.more-filters.lp-advence-filtr-colr').click(function () {
        var $formInline = jQuery('.form-inline.lp-features-filter.tags-area');
        $formInline.prependTo(".header-more-filters.form-inline .lp_all_page_overflow h2");
        console.log($formInline.html());
    });

});

//classic new style
// detail slider
jQuery(document).ready(function ($) {
    if ($('.single-page-gallery-slider-masonry').length > 0) {
        $('.single-page-gallery-slider-masonry').on('init', function () {
            $(this).addClass('slider-loaded'); // Add class when the slider has finished loading
        }).slick({
            centerMode: false,
            centerPadding: '60px',
            slidesToShow: 3,
            variableWidth: true,
            infinite: true,
            responsive: [{
                breakpoint: 768,
                settings: {
                    arrows: false,
                    centerMode: true,
                    centerPadding: '40px',
                    slidesToShow: 3
                }
            },
            {
                breakpoint: 480,
                settings: {
                    arrows: false,
                    centerMode: true,
                    centerPadding: '40px',
                    slidesToShow: 1
                }
            }
            ]
        })
    }
});
jQuery(document).ready(function ($) {
    if ($('.listing-slide-style4 a').length > 1) {
        $('.listing-slide-style4').on('init', function () {
            $(this).addClass('slider-loaded'); // Add class when the slider has finished loading
        }).slick({
            centerMode: true,
            centerPadding: '60px',
            slidesToShow: 3,
            infinite: true,
            responsive: [{
                breakpoint: 768,
                settings: {
                    arrows: true,
                    centerMode: true,
                    centerPadding: '40px',
                    slidesToShow: 3
                }
            },
            {
                breakpoint: 480,
                settings: {
                    arrows: true,
                    slidesToScroll: 1,
                    centerMode: true,
                    centerPadding: '40px',
                    slidesToShow: 1
                }
            }
            ]
        })
    }
});
// detail slider
// detail page faq
const items = document.querySelectorAll('.classic-accordion button');


function toggleAccordion() {
    const itemToggle = this.getAttribute('aria-expanded');
    for (i = 0; i < items.length; i++) {
        items[i].setAttribute('aria-expanded', 'false');
    }
    if (itemToggle == 'false') {
        this.setAttribute('aria-expanded', 'true');
    }
}
items.forEach((item) => item.addEventListener('click', toggleAccordion));
// detail page faq;
// source --> https://classified.maalz.com/wp-content/plugins/js_composer/assets/js/dist/js_composer_front.min.js?ver=8.6.1 
document.documentElement.className+=" js_active ",document.documentElement.className+="ontouchstart"in document.documentElement?" vc_mobile ":" vc_desktop ",(()=>{for(var e=["-webkit-","-moz-","-ms-","-o-",""],t=0;t<e.length;t++)e[t]+"transform"in document.documentElement.style&&(document.documentElement.className+=" vc_transform ")})(),(c=>{"function"!=typeof window.vc_js&&(window.vc_js=function(){vc_toggleBehaviour(),vc_tabsBehaviour(),vc_accordionBehaviour(),vc_teaserGrid(),vc_carouselBehaviour(),vc_slidersBehaviour(),vc_prettyPhoto(),vc_pinterest(),vc_progress_bar(),vc_plugin_flexslider(),vc_gridBehaviour(),vc_rowBehaviour(),vc_prepareHoverBox(),vc_googleMapsPointer(),vc_ttaActivation(),vc_ttaToggleBehaviour(),jQuery(document).trigger("vc_js"),window.setTimeout(vc_waypoints,500)}),"function"!=typeof window.vc_plugin_flexslider&&(window.vc_plugin_flexslider=function(e){(e?e.find(".wpb_flexslider"):jQuery(".wpb_flexslider")).each(function(){var e=jQuery(this),t=1e3*parseInt(e.attr("data-interval"),10),i=e.attr("data-flex_fx"),o=0==t?!1:!0;e.is(":visible")&&setTimeout(function(){e.flexslider({animation:i,slideshow:o,slideshowSpeed:t,sliderSpeed:800,smoothHeight:!0})},1)})}),"function"!=typeof window.vc_googleplus&&(window.vc_googleplus=function(){var e,t;0<jQuery(".wpb_googleplus").length&&((e=document.createElement("script")).type="text/javascript",e.async=!0,e.src="https://apis.google.com/js/plusone.js",(t=document.getElementsByTagName("script")[0]).parentNode.insertBefore(e,t))}),"function"!=typeof window.vc_pinterest&&(window.vc_pinterest=function(){var e,t;0<jQuery(".wpb_pinterest").length&&((e=document.createElement("script")).type="text/javascript",e.async=!0,e.src="https://assets.pinterest.com/js/pinit.js",(t=document.getElementsByTagName("script")[0]).parentNode.insertBefore(e,t))}),"function"!=typeof window.vc_progress_bar&&(window.vc_progress_bar=function(){void 0!==jQuery.fn.vcwaypoint&&jQuery(".vc_progress_bar").each(function(){var e=jQuery(this);e.vcwaypoint(function(){e.find(".vc_single_bar").each(function(e){var t=jQuery(this).find(".vc_bar"),i=t.data("percentage-value");setTimeout(function(){t.css({width:i+"%"})},200*e)})},{offset:"85%"})})}),"function"!=typeof window.vc_waypoints&&(window.vc_waypoints=function(){void 0!==jQuery.fn.vcwaypoint&&jQuery(".wpb_animate_when_almost_visible:not(.wpb_start_animation)").each(function(){var e=jQuery(this);e.vcwaypoint(function(){e.addClass("wpb_start_animation animated")},{offset:"85%"})})}),"function"!=typeof window.vc_toggleBehaviour&&(window.vc_toggleBehaviour=function(e){function t(e){e&&e.preventDefault&&e.preventDefault();var t=jQuery(this).closest(".vc_toggle"),e=t.find(".vc_toggle_content");t.hasClass("vc_toggle_active")?e.slideUp({duration:300,complete:function(){t.removeClass("vc_toggle_active")}}):e.slideDown({duration:300,complete:function(){t.addClass("vc_toggle_active")}})}(e?e.hasClass("vc_toggle_title")?e.unbind("click"):e.find(".vc_toggle_title").off("click"):jQuery(".vc_toggle_title").off("click")).on("click",t)}),"function"!=typeof window.vc_ttaToggleBehaviour&&(window.vc_ttaToggleBehaviour=function(e){function t(){var e=jQuery(this);e.toggleClass("wpb-tta-toggle-active"),e.parent().parent().parent().find(".vc_pagination-item").each(function(){if(!c(this).hasClass("vc_active"))return c(this).find("a").click(),!1})}(e?e.find(".wpb-tta-toggle"):jQuery(".wpb-tta-toggle")).off("click").on("click",t),setTimeout(function(){jQuery(".wpb-tta-toggle").each(function(){var e=jQuery(this);e.parent().parent().parent().find(".vc_tta-panels-container .vc_pagination li:first").hasClass("vc_active")||e.addClass("wpb-tta-toggle-active")})},1e3)}),"function"!=typeof window.vc_tabsBehaviour&&(window.vc_tabsBehaviour=function(e){var t,o;jQuery.ui&&(e=e||jQuery(".wpb_tabs, .wpb_tour"),t=jQuery.ui&&jQuery.ui.version?jQuery.ui.version.split("."):"1.10",o=1===parseInt(t[0],10)&&parseInt(t[1],10)<9,e.each(function(){var e=jQuery(this).attr("data-interval"),t=[],i=jQuery(this).find(".wpb_tour_tabs_wrapper").tabs({show:function(e,t){wpb_prepare_tab_content(e,t)},activate:function(e,t){wpb_prepare_tab_content(e,t)}});if(e&&0<e)try{i.tabs("rotate",1e3*e)}catch(e){window.console&&window.console.warn&&console.warn("tabs behaviours error",e)}jQuery(this).find(".wpb_tab").each(function(){t.push(this.id)}),jQuery(this).find(".wpb_tabs_nav li").on("click",function(e){return e&&e.preventDefault&&e.preventDefault(),o?i.tabs("select",jQuery("a",this).attr("href")):i.tabs("option","active",jQuery(this).index()),!1}),jQuery(this).find(".wpb_prev_slide a, .wpb_next_slide a").on("click",function(e){var t;e&&e.preventDefault&&e.preventDefault(),o?(t=i.tabs("option","selected"),jQuery(this).parent().hasClass("wpb_next_slide")?t++:t--,t<0?t=i.tabs("length")-1:t>=i.tabs("length")&&(t=0),i.tabs("select",t)):(t=i.tabs("option","active"),e=i.find(".wpb_tab").length,t=jQuery(this).parent().hasClass("wpb_next_slide")?e<=t+1?0:t+1:t-1<0?e-1:t-1,i.tabs("option","active",t))})}))}),"function"!=typeof window.vc_accordionBehaviour&&(window.vc_accordionBehaviour=function(){jQuery(".wpb_accordion").each(function(){var e=jQuery(this),t=(e.attr("data-interval"),!isNaN(jQuery(this).data("active-tab"))&&0<parseInt(e.data("active-tab"),10)&&parseInt(e.data("active-tab"),10)-1),i=!1===t||"yes"===e.data("collapsible"),t=e.find(".wpb_accordion_wrapper").accordion({header:"> div > h3",autoHeight:!1,heightStyle:"content",active:t,collapsible:i,navigation:!0,activate:vc_accordionActivate,change:function(e,t){void 0!==jQuery.fn.isotope&&t.newContent.find(".isotope").isotope("layout"),vc_carouselBehaviour(t.newPanel)}});!0===e.data("vcDisableKeydown")&&(t.data("uiAccordion")._keydown=function(){})})}),"function"!=typeof window.vc_teaserGrid&&(window.vc_teaserGrid=function(){var o={fitrows:"fitRows",masonry:"masonry"};jQuery(".wpb_grid .teaser_grid_container:not(.wpb_carousel), .wpb_filtered_grid .teaser_grid_container:not(.wpb_carousel)").each(function(){var e=jQuery(this),t=e.find(".wpb_thumbnails"),i=t.attr("data-layout-mode");t.isotope({itemSelector:".isotope-item",layoutMode:void 0===o[i]?"fitRows":o[i]}),e.find(".categories_filter a").data("isotope",t).on("click",function(e){e&&e.preventDefault&&e.preventDefault();e=jQuery(this).data("isotope");jQuery(this).parent().parent().find(".active").removeClass("active"),jQuery(this).parent().addClass("active"),e.isotope({filter:jQuery(this).attr("data-filter")})}),jQuery(window).on("load resize",function(){t.isotope("layout")})})}),"function"!=typeof window.vc_carouselBehaviour&&(window.vc_carouselBehaviour=function(e){(e?e.find(".wpb_carousel"):jQuery(".wpb_carousel")).each(function(){var e=jQuery(this);!0!==e.data("carousel_enabled")&&e.is(":visible")&&(e.data("carousel_enabled",!0),getColumnsCount(jQuery(this)),jQuery(this).hasClass("columns_count_1"),(e=jQuery(this).find(".wpb_thumbnails-fluid li")).css({"margin-right":e.css("margin-left"),"margin-left":0}),(e=jQuery(this).find("ul.wpb_thumbnails-fluid")).width(e.width()+300))})}),"function"!=typeof window.vc_slidersBehaviour&&(window.vc_slidersBehaviour=function(){jQuery(".wpb_gallery_slides").each(function(){var e,t,i=jQuery(this);i.hasClass("wpb_slider_nivo")?(0===(t=1e3*i.attr("data-interval"))&&(t=9999999999),jQuery.fn.nivoSlider&&!i.data("nivo-initialized")&&(i.data("nivo-initialized",!0),i.find(".nivoSlider").nivoSlider({effect:"boxRainGrow,boxRain,boxRainReverse,boxRainGrowReverse",slices:15,boxCols:8,boxRows:4,animSpeed:800,pauseTime:t,startSlide:0,directionNav:!0,directionNavHide:!0,controlNav:!0,keyboardNav:!1,pauseOnHover:!0,manualAdvance:!1,prevText:"Prev",nextText:"Next",afterLoad:function(){var e=c(this),t=e.find(".nivo-main-image");t.length&&e.height(t.height())},afterChange:function(){var e=c(this),t=e.find(".nivo-main-image");t.length&&e.height(t.height())}}))):i.hasClass("wpb_image_grid")&&i.find(".wpb_image_grid_ul")&&i.find(".wpb_image_grid_ul").isotope&&(jQuery.fn.imagesLoaded?e=i.find(".wpb_image_grid_ul").imagesLoaded(function(){e.isotope({itemSelector:".isotope-item",layoutMode:"fitRows",percentPosition:!0})}):i.find(".wpb_image_grid_ul").isotope({itemSelector:".isotope-item",layoutMode:"fitRows",percentPosition:!0}))})}),"function"!=typeof window.vc_prettyPhoto&&(window.vc_prettyPhoto=function(){try{jQuery&&jQuery.fn&&jQuery.fn.prettyPhoto&&jQuery('a.prettyphoto, .gallery-icon a[href*=".jpg"]').prettyPhoto({animationSpeed:"normal",hook:"data-rel",padding:15,opacity:.7,showTitle:!0,allowresize:!0,counter_separator_label:"/",hideflash:!1,deeplinking:!1,modal:!1,callback:function(){-1<location.href.indexOf("#!prettyPhoto")&&(location.hash="")},social_tools:""})}catch(e){window.console&&window.console.warn&&window.console.warn("vc_prettyPhoto initialize error",e)}}),"function"!=typeof window.vc_google_fonts&&(window.vc_google_fonts=function(){return window.console&&window.console.warn&&window.console.warn("function vc_google_fonts is deprecated, no need to use it"),!1}),window.vcParallaxSkroll=!1,"function"!=typeof window.vc_rowBehaviour&&(window.vc_rowBehaviour=function(){var s=window.jQuery;function e(){var e;void 0!==window.wpb_disable_full_width_row_js&&window.wpb_disable_full_width_row_js||(e=s('[data-vc-full-width="true"]'),s.each(e,function(){var e,t,i,o,n,a,r,c=s(this),d=(c.addClass("vc_hidden"),c.next(".vc_row-full-width"));(d=d.length?d:c.parent().next(".vc_row-full-width")).length&&(c.removeAttr("data-vc-full-width-temp"),e=parseInt(c.css("margin-left"),10),t=parseInt(c.css("margin-right"),10),i=0-d.offset().left-e,o=s(window).width(),n={position:"relative",left:i="rtl"===c.css("direction")?(i=i-d.width()+o)+e+t:i,"box-sizing":"border-box",width:o,"max-width":o},c.css(n),c.data("vcStretchContent")||("rtl"===c.css("direction")?((a=i)<0&&(a=0),(r=i)<0&&(r=0)):(r=o-(a=(a=-1*i)<0?0:a)-d.width()+e+t)<0&&(r=0),c.css({"padding-left":a+"px","padding-right":r+"px"})),c.attr("data-vc-full-width-init","true"),c.removeClass("vc_hidden"),s(document).trigger("vc-full-width-row-single",{el:c,offset:i,marginLeft:e,marginRight:t,elFull:d,width:o,maxWidth:o}))}),s(document).trigger("vc-full-width-row",e))}function t(){var e,t,i=s(".vc_row-o-full-height:first");i.length&&(e=s(window).height(),(t=i.offset().top)<e)&&i.css("min-height",100-t/(e/100)+"vh"),s(document).trigger("vc-full-height-row",i)}s(window).off("resize.vcRowBehaviour").on("resize.vcRowBehaviour",e).on("resize.vcRowBehaviour",t),e(),t(),(0<window.navigator.userAgent.indexOf("MSIE ")||navigator.userAgent.match(/Trident.*rv\:11\./))&&s(".vc_row-o-full-height").each(function(){"flex"===s(this).css("display")&&s(this).wrap('<div class="vc_ie-flexbox-fixer"></div>')}),vc_initVideoBackgrounds();var n=!1;if(window.vcParallaxSkroll&&window.vcParallaxSkroll.destroy(),s(".vc_parallax-inner").remove(),s("[data-5p-top-bottom]").removeAttr("data-5p-top-bottom data-30p-top-bottom"),s("[data-vc-parallax]").each(function(){var e,t,i,o;n=!0,"on"===s(this).data("vcParallaxOFade")&&s(this).children().attr("data-5p-top-bottom","opacity:0;").attr("data-30p-top-bottom","opacity:1;"),e=100*s(this).data("vcParallax"),(t=s("<div />").addClass("vc_parallax-inner").appendTo(s(this))).height(e+"%"),i=s(this).data("vcParallaxImage"),(o=vcExtractYoutubeId(i))?insertYoutubeVideoAsBackground(t,o):void 0!==i&&t.css("background-image","url("+i+")"),t.attr("data-bottom-top","top: "+-(e-100)+"%;").attr("data-top-bottom","top: 0%;")}),n&&window.skrollr)window.vcParallaxSkroll=skrollr.init({forceHeight:!1,smoothScrolling:!1,mobileCheck:function(){return!1}}),window.vcParallaxSkroll}),"function"!=typeof window.vc_gridBehaviour&&(window.vc_gridBehaviour=function(){jQuery.fn.vcGrid&&jQuery("[data-vc-grid]").vcGrid()}),"function"!=typeof window.getColumnsCount&&(window.getColumnsCount=function(e){for(var t=!1,i=1;!1===t;){if(e.hasClass("columns_count_"+i))return t=!0,i;i++}}),"function"!=typeof window.wpb_prepare_tab_content&&(window.wpb_prepare_tab_content=function(e,t){var i=t.panel||t.newPanel,o=i.find(".vc_pie_chart:not(.vc_ready)"),n=i.find(".vc_round-chart"),a=i.find(".vc_line-chart"),r=i.find('[data-ride="vc_carousel"]');vc_carouselBehaviour(),vc_plugin_flexslider(i),t.newPanel.find(".vc_masonry_media_grid, .vc_masonry_grid").length&&t.newPanel.find(".vc_masonry_media_grid, .vc_masonry_grid").each(function(){var e=jQuery(this).data("vcGrid");e&&e.gridBuilder&&e.gridBuilder.setMasonry&&e.gridBuilder.setMasonry()}),i.find(".vc_masonry_media_grid, .vc_masonry_grid").length&&i.find(".vc_masonry_media_grid, .vc_masonry_grid").each(function(){var e=jQuery(this).data("vcGrid");e&&e.gridBuilder&&e.gridBuilder.setMasonry&&e.gridBuilder.setMasonry()}),o.length&&jQuery.fn.vcChat&&o.vcChat(),n.length&&jQuery.fn.vcRoundChart&&n.vcRoundChart({reload:!1}),a.length&&jQuery.fn.vcLineChart&&a.vcLineChart({reload:!1}),r.length&&jQuery.fn.carousel&&r.carousel("resizeAction"),t=i.find(".isotope, .wpb_image_grid_ul"),o=i.find(".wpb_gmaps_widget"),0<t.length&&t.isotope("layout"),o.length&&!o.is(".map_ready")&&((n=o.find("iframe")).attr("src",n.attr("src")),o.addClass("map_ready")),i.parents(".isotope").length&&i.parents(".isotope").each(function(){jQuery(this).isotope("layout")}),c(document).trigger("wpb_prepare_tab_content",i)}),"function"!=typeof window.vc_ttaActivation&&(window.vc_ttaActivation=function(){jQuery("[data-vc-accordion]").on("show.vc.accordion",function(e){var t=window.jQuery,i={};i.newPanel=t(this).data("vc.accordion").getTarget(),window.wpb_prepare_tab_content(e,i)})}),"function"!=typeof window.vc_accordionActivate&&(window.vc_accordionActivate=function(e,t){var i,o,n,a;t.newPanel.length&&t.newHeader.length&&(i=t.newPanel.find(".vc_pie_chart:not(.vc_ready)"),o=t.newPanel.find(".vc_round-chart"),n=t.newPanel.find(".vc_line-chart"),a=t.newPanel.find('[data-ride="vc_carousel"]'),void 0!==jQuery.fn.isotope&&t.newPanel.find(".isotope, .wpb_image_grid_ul").isotope("layout"),t.newPanel.find(".vc_masonry_media_grid, .vc_masonry_grid").length&&t.newPanel.find(".vc_masonry_media_grid, .vc_masonry_grid").each(function(){var e=jQuery(this).data("vcGrid");e&&e.gridBuilder&&e.gridBuilder.setMasonry&&e.gridBuilder.setMasonry()}),vc_carouselBehaviour(t.newPanel),vc_plugin_flexslider(t.newPanel),i.length&&jQuery.fn.vcChat&&i.vcChat(),o.length&&jQuery.fn.vcRoundChart&&o.vcRoundChart({reload:!1}),n.length&&jQuery.fn.vcLineChart&&n.vcLineChart({reload:!1}),a.length&&jQuery.fn.carousel&&a.carousel("resizeAction"),t.newPanel.parents(".isotope").length)&&t.newPanel.parents(".isotope").each(function(){jQuery(this).isotope("layout")})}),"function"!=typeof window.initVideoBackgrounds&&(window.initVideoBackgrounds=function(){return window.console&&window.console.warn&&window.console.warn("this function is deprecated use vc_initVideoBackgrounds"),vc_initVideoBackgrounds()}),"function"!=typeof window.vc_initVideoBackgrounds&&(window.vc_initVideoBackgrounds=function(){c(".vc_video-bg").remove(),c("[data-vc-video-bg]").each(function(){var e,i=jQuery(this);i.data("vcVideoBg")?(e=i.data("vcVideoBg"),(e=vcExtractYoutubeId(e))&&(i.find(".vc_video-bg").remove(),insertYoutubeVideoAsBackground(i,e)),jQuery(window).on("grid:items:added",function(e,t){i.has(t).length&&vcResizeVideoBackground(i)})):i.find(".vc_video-bg").remove()})}),"function"!=typeof window.insertYoutubeVideoAsBackground&&(window.insertYoutubeVideoAsBackground=function(e,t,i){if("undefined"==typeof YT||void 0===YT.Player)return 100<(i=void 0===i?0:i)?void console.warn("Too many attempts to load YouTube api"):void setTimeout(function(){insertYoutubeVideoAsBackground(e,t,i++)},100);var o=e.prepend('<div class="vc_video-bg"><div class="inner"></div></div>').find(".inner");new YT.Player(o[0],{width:"100%",height:"100%",videoId:t,playerVars:{playlist:t,iv_load_policy:3,enablejsapi:1,disablekb:1,autoplay:1,controls:0,showinfo:0,rel:0,loop:1,mute:1,wmode:"transparent"},events:{onReady:function(e){e.target.mute().setLoop(!0)}}}),vcResizeVideoBackground(e),jQuery(window).on("resize",function(){vcResizeVideoBackground(e)})}),"function"!=typeof window.vcResizeVideoBackground&&(window.vcResizeVideoBackground=function(e){var t,i,o,n,a=e.innerWidth(),r=e.innerHeight();a/r<16/9?(t=r*(16/9),i=r,o=-Math.round((t-a)/2)+"px",n=-Math.round((i-r)/2)+"px"):(i=(t=a)*(9/16),n=-Math.round((i-r)/2)+"px",o=-Math.round((t-a)/2)+"px"),t+="px",i+="px",e.find(".vc_video-bg iframe").css({maxWidth:"1000%",marginLeft:o,marginTop:n,width:t,height:i})}),"function"!=typeof window.vcExtractYoutubeId&&(window.vcExtractYoutubeId=function(e){return void 0!==e&&null!==(e=e.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/))&&e[1]}),"function"!=typeof window.vc_googleMapsPointer&&(window.vc_googleMapsPointer=function(){var e=window.jQuery,t=e(".wpb_gmaps_widget");t.on("click",function(){e("iframe",this).css("pointer-events","auto")}),t.on("mouseleave",function(){e("iframe",this).css("pointer-events","none")}),e(".wpb_gmaps_widget iframe").css("pointer-events","none")}),"function"!=typeof window.vc_setHoverBoxPerspective&&(window.vc_setHoverBoxPerspective=function(e){e.each(function(){var e=jQuery(this),t=e.width();e.css("perspective",4*t+"px")})}),"function"!=typeof window.vc_setHoverBoxHeight&&(window.vc_setHoverBoxHeight=function(e){e.each(function(){var e=jQuery(this),t=e.find(".vc-hoverbox-inner"),i=(t.css("min-height",0),e.find(".vc-hoverbox-front-inner").outerHeight()),e=e.find(".vc-hoverbox-back-inner").outerHeight(),i=e<i?i:e;t.css("min-height",(i=i<250?250:i)+"px")})}),"function"!=typeof window.vc_prepareHoverBox&&(window.vc_prepareHoverBox=function(){var e=jQuery(".vc-hoverbox");vc_setHoverBoxHeight(e),vc_setHoverBoxPerspective(e)}),jQuery(document).ready(window.vc_prepareHoverBox),jQuery(window).on("resize",window.vc_prepareHoverBox),jQuery(document).ready(function(){window.vc_js()})})(window.jQuery);